{"text":"Resolves: fdo#65501 ensure configured backup dir exists before using it<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/plugins\/ppapi\/ppb_image_data_impl.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"ppapi\/c\/pp_instance.h\"\n#include \"ppapi\/c\/pp_resource.h\"\n#include \"ppapi\/c\/ppb_image_data.h\"\n#include \"ppapi\/c\/trusted\/ppb_image_data_trusted.h\"\n#include \"ppapi\/thunk\/thunk.h\"\n#include \"third_party\/skia\/include\/core\/SkColorPriv.h\"\n#include \"webkit\/plugins\/ppapi\/common.h\"\n#include \"webkit\/plugins\/ppapi\/ppapi_plugin_instance.h\"\n#include \"webkit\/plugins\/ppapi\/resource_helper.h\"\n\nusing ::ppapi::thunk::PPB_ImageData_API;\n\nnamespace webkit {\nnamespace ppapi {\n\nPPB_ImageData_Impl::PPB_ImageData_Impl(PP_Instance instance,\n ImageDataType type)\n : Resource(::ppapi::OBJECT_IS_IMPL, instance),\n format_(PP_IMAGEDATAFORMAT_BGRA_PREMUL),\n width_(0),\n height_(0) {\n switch (type) {\n case PLATFORM:\n backend_.reset(new ImageDataPlatformBackend);\n return;\n case NACL:\n backend_.reset(new ImageDataNaClBackend);\n return;\n \/\/ No default: so that we get a compiler warning if any types are added.\n }\n NOTREACHED();\n}\n\nPPB_ImageData_Impl::~PPB_ImageData_Impl() {\n}\n\nbool PPB_ImageData_Impl::Init(PP_ImageDataFormat format,\n int width, int height,\n bool init_to_zero) {\n \/\/ TODO(brettw) this should be called only on the main thread!\n if (!IsImageDataFormatSupported(format))\n return false; \/\/ Only support this one format for now.\n if (width <= 0 || height <= 0)\n return false;\n if (static_cast(width) * static_cast(height) * 4 >=\n std::numeric_limits::max())\n return false; \/\/ Prevent overflow of signed 32-bit ints.\n\n format_ = format;\n width_ = width;\n height_ = height;\n return backend_->Init(this, format, width, height, init_to_zero);\n}\n\n\/\/ static\nPP_Resource PPB_ImageData_Impl::CreatePlatform(PP_Instance instance,\n PP_ImageDataFormat format,\n const PP_Size& size,\n PP_Bool init_to_zero) {\n scoped_refptr\n data(new PPB_ImageData_Impl(instance, PLATFORM));\n if (!data->Init(format, size.width, size.height, !!init_to_zero))\n return 0;\n return data->GetReference();\n}\n\n\/\/ static\nPP_Resource PPB_ImageData_Impl::CreateNaCl(PP_Instance instance,\n PP_ImageDataFormat format,\n const PP_Size& size,\n PP_Bool init_to_zero) {\n scoped_refptr\n data(new PPB_ImageData_Impl(instance, NACL));\n if (!data->Init(format, size.width, size.height, !!init_to_zero))\n return 0;\n return data->GetReference();\n}\n\nPPB_ImageData_API* PPB_ImageData_Impl::AsPPB_ImageData_API() {\n return this;\n}\n\nbool PPB_ImageData_Impl::IsMapped() const {\n return backend_->IsMapped();\n}\n\nPluginDelegate::PlatformImage2D* PPB_ImageData_Impl::PlatformImage() const {\n return backend_->PlatformImage();\n}\n\nPP_Bool PPB_ImageData_Impl::Describe(PP_ImageDataDesc* desc) {\n desc->format = format_;\n desc->size.width = width_;\n desc->size.height = height_;\n desc->stride = width_ * 4;\n return PP_TRUE;\n}\n\nvoid* PPB_ImageData_Impl::Map() {\n return backend_->Map();\n}\n\nvoid PPB_ImageData_Impl::Unmap() {\n backend_->Unmap();\n}\n\nint32_t PPB_ImageData_Impl::GetSharedMemory(int* handle, uint32_t* byte_count) {\n return backend_->GetSharedMemory(handle, byte_count);\n}\n\nskia::PlatformCanvas* PPB_ImageData_Impl::GetPlatformCanvas() {\n return backend_->GetPlatformCanvas();\n}\n\nSkCanvas* PPB_ImageData_Impl::GetCanvas() {\n return backend_->GetCanvas();\n}\n\nconst SkBitmap* PPB_ImageData_Impl::GetMappedBitmap() const {\n return backend_->GetMappedBitmap();\n}\n\n\/\/ ImageDataPlatformBackend --------------------------------------------------\n\nImageDataPlatformBackend::ImageDataPlatformBackend() {\n}\n\nImageDataPlatformBackend::~ImageDataPlatformBackend() {\n}\n\nbool ImageDataPlatformBackend::Init(PPB_ImageData_Impl* impl,\n PP_ImageDataFormat format,\n int width, int height,\n bool init_to_zero) {\n PluginDelegate* plugin_delegate = ResourceHelper::GetPluginDelegate(impl);\n if (!plugin_delegate)\n return false;\n\n \/\/ TODO(brettw) use init_to_zero when we implement caching.\n platform_image_.reset(plugin_delegate->CreateImage2D(width, height));\n return !!platform_image_.get();\n}\n\nbool ImageDataPlatformBackend::IsMapped() const {\n return !!mapped_canvas_.get();\n}\n\nPluginDelegate::PlatformImage2D*\nImageDataPlatformBackend::PlatformImage() const {\n return platform_image_.get();\n}\n\nvoid* ImageDataPlatformBackend::Map() {\n if (!mapped_canvas_.get()) {\n mapped_canvas_.reset(platform_image_->Map());\n if (!mapped_canvas_.get())\n return NULL;\n }\n const SkBitmap& bitmap =\n skia::GetTopDevice(*mapped_canvas_)->accessBitmap(true);\n\n \/\/ Our platform bitmaps are set to opaque by default, which we don't want.\n const_cast(bitmap).setIsOpaque(false);\n\n bitmap.lockPixels();\n return bitmap.getAddr32(0, 0);\n}\n\nvoid ImageDataPlatformBackend::Unmap() {\n \/\/ This is currently unimplemented, which is OK. The data will just always\n \/\/ be around once it's mapped. Chrome's TransportDIB isn't currently\n \/\/ unmappable without freeing it, but this may be something we want to support\n \/\/ in the future to save some memory.\n}\n\nint32_t ImageDataPlatformBackend::GetSharedMemory(int* handle,\n uint32_t* byte_count) {\n *handle = platform_image_->GetSharedMemoryHandle(byte_count);\n return PP_OK;\n}\n\nskia::PlatformCanvas* ImageDataPlatformBackend::GetPlatformCanvas() {\n return mapped_canvas_.get();\n}\n\nSkCanvas* ImageDataPlatformBackend::GetCanvas() {\n return mapped_canvas_.get();\n}\n\nconst SkBitmap* ImageDataPlatformBackend::GetMappedBitmap() const {\n if (!mapped_canvas_.get())\n return NULL;\n return &skia::GetTopDevice(*mapped_canvas_)->accessBitmap(false);\n}\n\n\/\/ ImageDataNaClBackend ------------------------------------------------------\n\nImageDataNaClBackend::ImageDataNaClBackend()\n : map_count_(0) {\n}\n\nImageDataNaClBackend::~ImageDataNaClBackend() {\n}\n\nbool ImageDataNaClBackend::Init(PPB_ImageData_Impl* impl,\n PP_ImageDataFormat format,\n int width, int height,\n bool init_to_zero) {\n skia_bitmap_.setConfig(SkBitmap::kARGB_8888_Config,\n impl->width(), impl->height());\n PluginDelegate* plugin_delegate = ResourceHelper::GetPluginDelegate(impl);\n if (!plugin_delegate)\n return false;\n shared_memory_.reset(\n plugin_delegate->CreateAnonymousSharedMemory(skia_bitmap_.getSize()));\n return !!shared_memory_.get();\n}\n\nbool ImageDataNaClBackend::IsMapped() const {\n return map_count_ > 0;\n}\n\nPluginDelegate::PlatformImage2D* ImageDataNaClBackend::PlatformImage() const {\n return NULL;\n}\n\nvoid* ImageDataNaClBackend::Map() {\n DCHECK(shared_memory_.get());\n if (map_count_++ == 0) {\n shared_memory_->Map(skia_bitmap_.getSize());\n skia_bitmap_.setPixels(shared_memory_->memory());\n \/\/ Our platform bitmaps are set to opaque by default, which we don't want.\n skia_bitmap_.setIsOpaque(false);\n skia_canvas_.reset(new SkCanvas(skia_bitmap_));\n return skia_bitmap_.getAddr32(0, 0);\n }\n return shared_memory_->memory();\n}\n\nvoid ImageDataNaClBackend::Unmap() {\n if (--map_count_ == 0)\n shared_memory_->Unmap();\n}\n\nint32_t ImageDataNaClBackend::GetSharedMemory(int* handle,\n uint32_t* byte_count) {\n *byte_count = skia_bitmap_.getSize();\n#if defined(OS_POSIX)\n *handle = shared_memory_->handle().fd;\n#elif defined(OS_WIN)\n *handle = reinterpret_cast(shared_memory_->handle());\n#else\n#error \"Platform not supported.\"\n#endif\n return PP_OK;\n}\n\nskia::PlatformCanvas* ImageDataNaClBackend::GetPlatformCanvas() {\n return NULL;\n}\n\nSkCanvas* ImageDataNaClBackend::GetCanvas() {\n if (!IsMapped())\n return NULL;\n return skia_canvas_.get();\n}\n\nconst SkBitmap* ImageDataNaClBackend::GetMappedBitmap() const {\n if (!IsMapped())\n return NULL;\n return &skia_bitmap_;\n}\n\n} \/\/ namespace ppapi\n} \/\/ namespace webkit\n\nSecurity fix: integer overflow on checking image size\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/plugins\/ppapi\/ppb_image_data_impl.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"skia\/ext\/platform_canvas.h\"\n#include \"ppapi\/c\/pp_instance.h\"\n#include \"ppapi\/c\/pp_resource.h\"\n#include \"ppapi\/c\/ppb_image_data.h\"\n#include \"ppapi\/c\/trusted\/ppb_image_data_trusted.h\"\n#include \"ppapi\/thunk\/thunk.h\"\n#include \"third_party\/skia\/include\/core\/SkColorPriv.h\"\n#include \"webkit\/plugins\/ppapi\/common.h\"\n#include \"webkit\/plugins\/ppapi\/ppapi_plugin_instance.h\"\n#include \"webkit\/plugins\/ppapi\/resource_helper.h\"\n\nusing ::ppapi::thunk::PPB_ImageData_API;\n\nnamespace webkit {\nnamespace ppapi {\n\nPPB_ImageData_Impl::PPB_ImageData_Impl(PP_Instance instance,\n ImageDataType type)\n : Resource(::ppapi::OBJECT_IS_IMPL, instance),\n format_(PP_IMAGEDATAFORMAT_BGRA_PREMUL),\n width_(0),\n height_(0) {\n switch (type) {\n case PLATFORM:\n backend_.reset(new ImageDataPlatformBackend);\n return;\n case NACL:\n backend_.reset(new ImageDataNaClBackend);\n return;\n \/\/ No default: so that we get a compiler warning if any types are added.\n }\n NOTREACHED();\n}\n\nPPB_ImageData_Impl::~PPB_ImageData_Impl() {\n}\n\nbool PPB_ImageData_Impl::Init(PP_ImageDataFormat format,\n int width, int height,\n bool init_to_zero) {\n \/\/ TODO(brettw) this should be called only on the main thread!\n if (!IsImageDataFormatSupported(format))\n return false; \/\/ Only support this one format for now.\n if (width <= 0 || height <= 0)\n return false;\n if (static_cast(width) * static_cast(height) >=\n std::numeric_limits::max() \/ 4)\n return false; \/\/ Prevent overflow of signed 32-bit ints.\n\n format_ = format;\n width_ = width;\n height_ = height;\n return backend_->Init(this, format, width, height, init_to_zero);\n}\n\n\/\/ static\nPP_Resource PPB_ImageData_Impl::CreatePlatform(PP_Instance instance,\n PP_ImageDataFormat format,\n const PP_Size& size,\n PP_Bool init_to_zero) {\n scoped_refptr\n data(new PPB_ImageData_Impl(instance, PLATFORM));\n if (!data->Init(format, size.width, size.height, !!init_to_zero))\n return 0;\n return data->GetReference();\n}\n\n\/\/ static\nPP_Resource PPB_ImageData_Impl::CreateNaCl(PP_Instance instance,\n PP_ImageDataFormat format,\n const PP_Size& size,\n PP_Bool init_to_zero) {\n scoped_refptr\n data(new PPB_ImageData_Impl(instance, NACL));\n if (!data->Init(format, size.width, size.height, !!init_to_zero))\n return 0;\n return data->GetReference();\n}\n\nPPB_ImageData_API* PPB_ImageData_Impl::AsPPB_ImageData_API() {\n return this;\n}\n\nbool PPB_ImageData_Impl::IsMapped() const {\n return backend_->IsMapped();\n}\n\nPluginDelegate::PlatformImage2D* PPB_ImageData_Impl::PlatformImage() const {\n return backend_->PlatformImage();\n}\n\nPP_Bool PPB_ImageData_Impl::Describe(PP_ImageDataDesc* desc) {\n desc->format = format_;\n desc->size.width = width_;\n desc->size.height = height_;\n desc->stride = width_ * 4;\n return PP_TRUE;\n}\n\nvoid* PPB_ImageData_Impl::Map() {\n return backend_->Map();\n}\n\nvoid PPB_ImageData_Impl::Unmap() {\n backend_->Unmap();\n}\n\nint32_t PPB_ImageData_Impl::GetSharedMemory(int* handle, uint32_t* byte_count) {\n return backend_->GetSharedMemory(handle, byte_count);\n}\n\nskia::PlatformCanvas* PPB_ImageData_Impl::GetPlatformCanvas() {\n return backend_->GetPlatformCanvas();\n}\n\nSkCanvas* PPB_ImageData_Impl::GetCanvas() {\n return backend_->GetCanvas();\n}\n\nconst SkBitmap* PPB_ImageData_Impl::GetMappedBitmap() const {\n return backend_->GetMappedBitmap();\n}\n\n\/\/ ImageDataPlatformBackend --------------------------------------------------\n\nImageDataPlatformBackend::ImageDataPlatformBackend() {\n}\n\nImageDataPlatformBackend::~ImageDataPlatformBackend() {\n}\n\nbool ImageDataPlatformBackend::Init(PPB_ImageData_Impl* impl,\n PP_ImageDataFormat format,\n int width, int height,\n bool init_to_zero) {\n PluginDelegate* plugin_delegate = ResourceHelper::GetPluginDelegate(impl);\n if (!plugin_delegate)\n return false;\n\n \/\/ TODO(brettw) use init_to_zero when we implement caching.\n platform_image_.reset(plugin_delegate->CreateImage2D(width, height));\n return !!platform_image_.get();\n}\n\nbool ImageDataPlatformBackend::IsMapped() const {\n return !!mapped_canvas_.get();\n}\n\nPluginDelegate::PlatformImage2D*\nImageDataPlatformBackend::PlatformImage() const {\n return platform_image_.get();\n}\n\nvoid* ImageDataPlatformBackend::Map() {\n if (!mapped_canvas_.get()) {\n mapped_canvas_.reset(platform_image_->Map());\n if (!mapped_canvas_.get())\n return NULL;\n }\n const SkBitmap& bitmap =\n skia::GetTopDevice(*mapped_canvas_)->accessBitmap(true);\n\n \/\/ Our platform bitmaps are set to opaque by default, which we don't want.\n const_cast(bitmap).setIsOpaque(false);\n\n bitmap.lockPixels();\n return bitmap.getAddr32(0, 0);\n}\n\nvoid ImageDataPlatformBackend::Unmap() {\n \/\/ This is currently unimplemented, which is OK. The data will just always\n \/\/ be around once it's mapped. Chrome's TransportDIB isn't currently\n \/\/ unmappable without freeing it, but this may be something we want to support\n \/\/ in the future to save some memory.\n}\n\nint32_t ImageDataPlatformBackend::GetSharedMemory(int* handle,\n uint32_t* byte_count) {\n *handle = platform_image_->GetSharedMemoryHandle(byte_count);\n return PP_OK;\n}\n\nskia::PlatformCanvas* ImageDataPlatformBackend::GetPlatformCanvas() {\n return mapped_canvas_.get();\n}\n\nSkCanvas* ImageDataPlatformBackend::GetCanvas() {\n return mapped_canvas_.get();\n}\n\nconst SkBitmap* ImageDataPlatformBackend::GetMappedBitmap() const {\n if (!mapped_canvas_.get())\n return NULL;\n return &skia::GetTopDevice(*mapped_canvas_)->accessBitmap(false);\n}\n\n\/\/ ImageDataNaClBackend ------------------------------------------------------\n\nImageDataNaClBackend::ImageDataNaClBackend()\n : map_count_(0) {\n}\n\nImageDataNaClBackend::~ImageDataNaClBackend() {\n}\n\nbool ImageDataNaClBackend::Init(PPB_ImageData_Impl* impl,\n PP_ImageDataFormat format,\n int width, int height,\n bool init_to_zero) {\n skia_bitmap_.setConfig(SkBitmap::kARGB_8888_Config,\n impl->width(), impl->height());\n PluginDelegate* plugin_delegate = ResourceHelper::GetPluginDelegate(impl);\n if (!plugin_delegate)\n return false;\n shared_memory_.reset(\n plugin_delegate->CreateAnonymousSharedMemory(skia_bitmap_.getSize()));\n return !!shared_memory_.get();\n}\n\nbool ImageDataNaClBackend::IsMapped() const {\n return map_count_ > 0;\n}\n\nPluginDelegate::PlatformImage2D* ImageDataNaClBackend::PlatformImage() const {\n return NULL;\n}\n\nvoid* ImageDataNaClBackend::Map() {\n DCHECK(shared_memory_.get());\n if (map_count_++ == 0) {\n shared_memory_->Map(skia_bitmap_.getSize());\n skia_bitmap_.setPixels(shared_memory_->memory());\n \/\/ Our platform bitmaps are set to opaque by default, which we don't want.\n skia_bitmap_.setIsOpaque(false);\n skia_canvas_.reset(new SkCanvas(skia_bitmap_));\n return skia_bitmap_.getAddr32(0, 0);\n }\n return shared_memory_->memory();\n}\n\nvoid ImageDataNaClBackend::Unmap() {\n if (--map_count_ == 0)\n shared_memory_->Unmap();\n}\n\nint32_t ImageDataNaClBackend::GetSharedMemory(int* handle,\n uint32_t* byte_count) {\n *byte_count = skia_bitmap_.getSize();\n#if defined(OS_POSIX)\n *handle = shared_memory_->handle().fd;\n#elif defined(OS_WIN)\n *handle = reinterpret_cast(shared_memory_->handle());\n#else\n#error \"Platform not supported.\"\n#endif\n return PP_OK;\n}\n\nskia::PlatformCanvas* ImageDataNaClBackend::GetPlatformCanvas() {\n return NULL;\n}\n\nSkCanvas* ImageDataNaClBackend::GetCanvas() {\n if (!IsMapped())\n return NULL;\n return skia_canvas_.get();\n}\n\nconst SkBitmap* ImageDataNaClBackend::GetMappedBitmap() const {\n if (!IsMapped())\n return NULL;\n return &skia_bitmap_;\n}\n\n} \/\/ namespace ppapi\n} \/\/ namespace webkit\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"formeditorscene.h\"\n#include \"formeditorview.h\"\n#include \"formeditorwidget.h\"\n#include \"formeditoritem.h\"\n#include \"qmldesignerplugin.h\"\n#include \"designersettings.h\"\n\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\n\nnamespace QmlDesigner {\n\nFormEditorScene::FormEditorScene(FormEditorWidget *view, FormEditorView *editorView)\n : QGraphicsScene(),\n m_editorView(editorView),\n m_showBoundingRects(true)\n{\n setupScene();\n view->setScene(this);\n setItemIndexMethod(QGraphicsScene::NoIndex);\n}\n\nFormEditorScene::~FormEditorScene()\n{\n clear(); \/\/FormEditorItems have to be cleared before destruction\n \/\/Reason: FormEditorItems accesses FormEditorScene in destructor\n}\n\n\nvoid FormEditorScene::setupScene()\n{\n m_formLayerItem = new LayerItem(this);\n m_manipulatorLayerItem = new LayerItem(this);\n m_manipulatorLayerItem->setZValue(1.0);\n m_manipulatorLayerItem->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);\n m_formLayerItem->setZValue(0.0);\n m_formLayerItem->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);\n}\n\nvoid FormEditorScene::resetScene()\n{\n foreach (QGraphicsItem *item, m_manipulatorLayerItem->childItems())\n removeItem(item);\n\n setSceneRect(-canvasWidth()\/2., -canvasHeight()\/2., canvasWidth(), canvasHeight());\n}\n\nFormEditorItem* FormEditorScene::itemForQmlItemNode(const QmlItemNode &qmlItemNode) const\n{\n Q_ASSERT(hasItemForQmlItemNode(qmlItemNode));\n return m_qmlItemNodeItemHash.value(qmlItemNode);\n}\n\ndouble FormEditorScene::canvasWidth() const\n{\n DesignerSettings settings = QmlDesignerPlugin::instance()->settings();\n return settings.canvasWidth;\n}\n\ndouble FormEditorScene::canvasHeight() const\n{\n DesignerSettings settings = QmlDesignerPlugin::instance()->settings();\n return settings.canvasHeight;\n}\n\nQList FormEditorScene::itemsForQmlItemNodes(const QList &nodeList) const\n{\n QList itemList;\n foreach (const QmlItemNode &node, nodeList) {\n if (hasItemForQmlItemNode(node))\n itemList += itemForQmlItemNode(node);\n }\n\n return itemList;\n}\n\nQList FormEditorScene::allFormEditorItems() const\n{\n return m_qmlItemNodeItemHash.values();\n}\n\nvoid FormEditorScene::updateAllFormEditorItems()\n{\n foreach (FormEditorItem *item, allFormEditorItems()) {\n item->update();\n }\n}\n\nbool FormEditorScene::hasItemForQmlItemNode(const QmlItemNode &qmlItemNode) const\n{\n return m_qmlItemNodeItemHash.contains(qmlItemNode);\n}\n\nvoid FormEditorScene::removeItemFromHash(FormEditorItem *item)\n{\n m_qmlItemNodeItemHash.remove(item->qmlItemNode());\n}\n\n\nAbstractFormEditorTool* FormEditorScene::currentTool() const\n{\n return m_editorView->currentTool();\n}\n\n\/\/This function calculates the possible parent for reparent\nFormEditorItem* FormEditorScene::calulateNewParent(FormEditorItem *formEditorItem)\n{\n if (formEditorItem->qmlItemNode().isValid()) {\n QList list = items(formEditorItem->qmlItemNode().instanceBoundingRect().center());\n foreach (QGraphicsItem *graphicsItem, list) {\n if (qgraphicsitem_cast(graphicsItem) &&\n graphicsItem->collidesWithItem(formEditorItem, Qt::ContainsItemShape))\n return qgraphicsitem_cast(graphicsItem);\n }\n }\n\n return 0;\n}\n\nvoid FormEditorScene::synchronizeTransformation(const QmlItemNode &qmlItemNode)\n{\n FormEditorItem *item = itemForQmlItemNode(qmlItemNode);\n item->updateGeometry();\n item->update();\n\n if (qmlItemNode.isRootNode()) {\n formLayerItem()->update();\n manipulatorLayerItem()->update();\n }\n}\n\nvoid FormEditorScene::synchronizeParent(const QmlItemNode &qmlItemNode)\n{\n QmlItemNode parentNode = qmlItemNode.instanceParent().toQmlItemNode();\n reparentItem(qmlItemNode, parentNode);\n}\n\nvoid FormEditorScene::synchronizeOtherProperty(const QmlItemNode &qmlItemNode, const QString &propertyName)\n{\n if (hasItemForQmlItemNode(qmlItemNode)) {\n FormEditorItem *item = itemForQmlItemNode(qmlItemNode);\n\n if (propertyName == \"opacity\")\n item->setOpacity(qmlItemNode.instanceValue(\"opacity\").toDouble());\n\n if (propertyName == \"clip\")\n item->setFlag(QGraphicsItem::ItemClipsChildrenToShape, qmlItemNode.instanceValue(\"clip\").toBool());\n\n if (propertyName == \"z\")\n item->setZValue(qmlItemNode.instanceValue(\"z\").toDouble());\n\n if (propertyName == \"visible\")\n item->setContentVisible(qmlItemNode.instanceValue(\"visible\").toBool());\n }\n}\n\nvoid FormEditorScene::synchronizeState(const QmlItemNode &qmlItemNode)\n{\n if (hasItemForQmlItemNode(qmlItemNode)) {\n FormEditorItem *item = itemForQmlItemNode(qmlItemNode);\n if (item)\n item->update();\n }\n}\n\n\nFormEditorItem *FormEditorScene::addFormEditorItem(const QmlItemNode &qmlItemNode)\n{\n FormEditorItem *formEditorItem = new FormEditorItem(qmlItemNode, this);\n Q_ASSERT(!m_qmlItemNodeItemHash.contains(qmlItemNode));\n\n m_qmlItemNodeItemHash.insert(qmlItemNode, formEditorItem);\n if (qmlItemNode.isRootNode()) {\n setSceneRect(-canvasWidth()\/2., -canvasHeight()\/2., canvasWidth(), canvasHeight());\n formLayerItem()->update();\n manipulatorLayerItem()->update();\n }\n\n\n\n return formEditorItem;\n}\n\nvoid FormEditorScene::dropEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dropEvent(event);\n\n if (views().first())\n views().first()->setFocus();\n}\n\nvoid FormEditorScene::dragEnterEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dragEnterEvent(event);\n}\n\nvoid FormEditorScene::dragLeaveEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dragLeaveEvent(event);\n\n return;\n}\n\nvoid FormEditorScene::dragMoveEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dragMoveEvent(event);\n}\n\nQList FormEditorScene::removeLayerItems(const QList &itemList)\n{\n QList itemListWithoutLayerItems;\n\n foreach (QGraphicsItem *item, itemList)\n if (item != manipulatorLayerItem() && item != formLayerItem())\n itemListWithoutLayerItems.append(item);\n\n return itemListWithoutLayerItems;\n}\n\nvoid FormEditorScene::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n if (editorView() && editorView()->model())\n currentTool()->mousePressEvent(removeLayerItems(items(event->scenePos())), event);\n}\n\nstatic QTime staticTimer()\n{\n QTime timer;\n timer.start();\n return timer;\n}\n\nvoid FormEditorScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)\n{\n static QTime time = staticTimer();\n\n if (time.elapsed() > 30) {\n time.restart();\n if (event->buttons())\n currentTool()->mouseMoveEvent(removeLayerItems(items(event->scenePos())), event);\n else\n currentTool()->hoverMoveEvent(removeLayerItems(items(event->scenePos())), event);\n\n event->accept();\n }\n}\n\nvoid FormEditorScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n if (editorView() && editorView()->model()) {\n currentTool()->mouseReleaseEvent(removeLayerItems(items(event->scenePos())), event);\n\n event->accept();\n }\n }\n\nvoid FormEditorScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)\n{\n if (editorView() && editorView()->model()) {\n currentTool()->mouseDoubleClickEvent(removeLayerItems(items(event->scenePos())), event);\n\n event->accept();\n }\n}\n\nvoid FormEditorScene::keyPressEvent(QKeyEvent *keyEvent)\n{\n if (editorView() && editorView()->model())\n currentTool()->keyPressEvent(keyEvent);\n}\n\nvoid FormEditorScene::keyReleaseEvent(QKeyEvent *keyEvent)\n{\n if (editorView() && editorView()->model())\n currentTool()->keyReleaseEvent(keyEvent);\n}\n\nFormEditorView *FormEditorScene::editorView() const\n{\n return m_editorView;\n}\n\nLayerItem* FormEditorScene::manipulatorLayerItem() const\n{\n return m_manipulatorLayerItem.data();\n}\n\nLayerItem* FormEditorScene::formLayerItem() const\n{\n return m_formLayerItem.data();\n}\n\nbool FormEditorScene::event(QEvent * event)\n{\n switch (event->type())\n {\n case QEvent::GraphicsSceneHoverEnter :\n hoverEnterEvent(static_cast(event));\n return true;\n case QEvent::GraphicsSceneHoverMove :\n hoverMoveEvent(static_cast(event));\n return true;\n case QEvent::GraphicsSceneHoverLeave :\n hoverLeaveEvent(static_cast(event));\n return true;\n case QEvent::ShortcutOverride :\n if (static_cast(event)->key() == Qt::Key_Escape) {\n currentTool()->keyPressEvent(static_cast(event));\n return true;\n }\n default: return QGraphicsScene::event(event);\n }\n\n}\n\nvoid FormEditorScene::hoverEnterEvent(QGraphicsSceneHoverEvent * \/*event*\/)\n{\n qDebug() << __FUNCTION__;\n}\n\nvoid FormEditorScene::hoverMoveEvent(QGraphicsSceneHoverEvent * \/*event*\/)\n{\n qDebug() << __FUNCTION__;\n}\n\nvoid FormEditorScene::hoverLeaveEvent(QGraphicsSceneHoverEvent * \/*event*\/)\n{\n qDebug() << __FUNCTION__;\n}\n\n\nvoid FormEditorScene::reparentItem(const QmlItemNode &node, const QmlItemNode &newParent)\n{\n Q_ASSERT(hasItemForQmlItemNode(node));\n FormEditorItem *item = itemForQmlItemNode(node);\n FormEditorItem *parentItem = 0;\n if (newParent.isValid() && hasItemForQmlItemNode(newParent))\n parentItem = itemForQmlItemNode(newParent);\n\n item->setParentItem(0);\n item->setParentItem(parentItem);\n}\n\nFormEditorItem* FormEditorScene::rootFormEditorItem() const\n{\n if (hasItemForQmlItemNode(editorView()->rootModelNode()))\n return itemForQmlItemNode(editorView()->rootModelNode());\n return 0;\n}\n\nvoid FormEditorScene::clearFormEditorItems()\n{\n QList itemList(items());\n\n foreach (QGraphicsItem *item, itemList) {\n if (qgraphicsitem_cast(item))\n item->setParentItem(0);\n }\n\n foreach (QGraphicsItem *item, itemList) {\n if (qgraphicsitem_cast(item))\n delete item;\n }\n}\n\nvoid FormEditorScene::highlightBoundingRect(FormEditorItem *highlighItem)\n{\n foreach (FormEditorItem *item, allFormEditorItems()) {\n if (item == highlighItem)\n item->setHighlightBoundingRect(true);\n else\n item->setHighlightBoundingRect(false);\n }\n}\n\nvoid FormEditorScene::setShowBoundingRects(bool show)\n{\n m_showBoundingRects = show;\n updateAllFormEditorItems();\n}\n\nbool FormEditorScene::showBoundingRects() const\n{\n return m_showBoundingRects;\n}\n\n}\n\nQmlDesigner: Delete manipulator items\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"formeditorscene.h\"\n#include \"formeditorview.h\"\n#include \"formeditorwidget.h\"\n#include \"formeditoritem.h\"\n#include \"qmldesignerplugin.h\"\n#include \"designersettings.h\"\n\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\n\nnamespace QmlDesigner {\n\nFormEditorScene::FormEditorScene(FormEditorWidget *view, FormEditorView *editorView)\n : QGraphicsScene(),\n m_editorView(editorView),\n m_showBoundingRects(true)\n{\n setupScene();\n view->setScene(this);\n setItemIndexMethod(QGraphicsScene::NoIndex);\n}\n\nFormEditorScene::~FormEditorScene()\n{\n clear(); \/\/FormEditorItems have to be cleared before destruction\n \/\/Reason: FormEditorItems accesses FormEditorScene in destructor\n}\n\n\nvoid FormEditorScene::setupScene()\n{\n m_formLayerItem = new LayerItem(this);\n m_manipulatorLayerItem = new LayerItem(this);\n m_manipulatorLayerItem->setZValue(1.0);\n m_manipulatorLayerItem->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);\n m_formLayerItem->setZValue(0.0);\n m_formLayerItem->setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);\n}\n\nvoid FormEditorScene::resetScene()\n{\n foreach (QGraphicsItem *item, m_manipulatorLayerItem->childItems()) {\n removeItem(item);\n delete item;\n }\n\n setSceneRect(-canvasWidth()\/2., -canvasHeight()\/2., canvasWidth(), canvasHeight());\n}\n\nFormEditorItem* FormEditorScene::itemForQmlItemNode(const QmlItemNode &qmlItemNode) const\n{\n Q_ASSERT(hasItemForQmlItemNode(qmlItemNode));\n return m_qmlItemNodeItemHash.value(qmlItemNode);\n}\n\ndouble FormEditorScene::canvasWidth() const\n{\n DesignerSettings settings = QmlDesignerPlugin::instance()->settings();\n return settings.canvasWidth;\n}\n\ndouble FormEditorScene::canvasHeight() const\n{\n DesignerSettings settings = QmlDesignerPlugin::instance()->settings();\n return settings.canvasHeight;\n}\n\nQList FormEditorScene::itemsForQmlItemNodes(const QList &nodeList) const\n{\n QList itemList;\n foreach (const QmlItemNode &node, nodeList) {\n if (hasItemForQmlItemNode(node))\n itemList += itemForQmlItemNode(node);\n }\n\n return itemList;\n}\n\nQList FormEditorScene::allFormEditorItems() const\n{\n return m_qmlItemNodeItemHash.values();\n}\n\nvoid FormEditorScene::updateAllFormEditorItems()\n{\n foreach (FormEditorItem *item, allFormEditorItems()) {\n item->update();\n }\n}\n\nbool FormEditorScene::hasItemForQmlItemNode(const QmlItemNode &qmlItemNode) const\n{\n return m_qmlItemNodeItemHash.contains(qmlItemNode);\n}\n\nvoid FormEditorScene::removeItemFromHash(FormEditorItem *item)\n{\n m_qmlItemNodeItemHash.remove(item->qmlItemNode());\n}\n\n\nAbstractFormEditorTool* FormEditorScene::currentTool() const\n{\n return m_editorView->currentTool();\n}\n\n\/\/This function calculates the possible parent for reparent\nFormEditorItem* FormEditorScene::calulateNewParent(FormEditorItem *formEditorItem)\n{\n if (formEditorItem->qmlItemNode().isValid()) {\n QList list = items(formEditorItem->qmlItemNode().instanceBoundingRect().center());\n foreach (QGraphicsItem *graphicsItem, list) {\n if (qgraphicsitem_cast(graphicsItem) &&\n graphicsItem->collidesWithItem(formEditorItem, Qt::ContainsItemShape))\n return qgraphicsitem_cast(graphicsItem);\n }\n }\n\n return 0;\n}\n\nvoid FormEditorScene::synchronizeTransformation(const QmlItemNode &qmlItemNode)\n{\n FormEditorItem *item = itemForQmlItemNode(qmlItemNode);\n item->updateGeometry();\n item->update();\n\n if (qmlItemNode.isRootNode()) {\n formLayerItem()->update();\n manipulatorLayerItem()->update();\n }\n}\n\nvoid FormEditorScene::synchronizeParent(const QmlItemNode &qmlItemNode)\n{\n QmlItemNode parentNode = qmlItemNode.instanceParent().toQmlItemNode();\n reparentItem(qmlItemNode, parentNode);\n}\n\nvoid FormEditorScene::synchronizeOtherProperty(const QmlItemNode &qmlItemNode, const QString &propertyName)\n{\n if (hasItemForQmlItemNode(qmlItemNode)) {\n FormEditorItem *item = itemForQmlItemNode(qmlItemNode);\n\n if (propertyName == \"opacity\")\n item->setOpacity(qmlItemNode.instanceValue(\"opacity\").toDouble());\n\n if (propertyName == \"clip\")\n item->setFlag(QGraphicsItem::ItemClipsChildrenToShape, qmlItemNode.instanceValue(\"clip\").toBool());\n\n if (propertyName == \"z\")\n item->setZValue(qmlItemNode.instanceValue(\"z\").toDouble());\n\n if (propertyName == \"visible\")\n item->setContentVisible(qmlItemNode.instanceValue(\"visible\").toBool());\n }\n}\n\nvoid FormEditorScene::synchronizeState(const QmlItemNode &qmlItemNode)\n{\n if (hasItemForQmlItemNode(qmlItemNode)) {\n FormEditorItem *item = itemForQmlItemNode(qmlItemNode);\n if (item)\n item->update();\n }\n}\n\n\nFormEditorItem *FormEditorScene::addFormEditorItem(const QmlItemNode &qmlItemNode)\n{\n FormEditorItem *formEditorItem = new FormEditorItem(qmlItemNode, this);\n Q_ASSERT(!m_qmlItemNodeItemHash.contains(qmlItemNode));\n\n m_qmlItemNodeItemHash.insert(qmlItemNode, formEditorItem);\n if (qmlItemNode.isRootNode()) {\n setSceneRect(-canvasWidth()\/2., -canvasHeight()\/2., canvasWidth(), canvasHeight());\n formLayerItem()->update();\n manipulatorLayerItem()->update();\n }\n\n\n\n return formEditorItem;\n}\n\nvoid FormEditorScene::dropEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dropEvent(event);\n\n if (views().first())\n views().first()->setFocus();\n}\n\nvoid FormEditorScene::dragEnterEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dragEnterEvent(event);\n}\n\nvoid FormEditorScene::dragLeaveEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dragLeaveEvent(event);\n\n return;\n}\n\nvoid FormEditorScene::dragMoveEvent(QGraphicsSceneDragDropEvent * event)\n{\n currentTool()->dragMoveEvent(event);\n}\n\nQList FormEditorScene::removeLayerItems(const QList &itemList)\n{\n QList itemListWithoutLayerItems;\n\n foreach (QGraphicsItem *item, itemList)\n if (item != manipulatorLayerItem() && item != formLayerItem())\n itemListWithoutLayerItems.append(item);\n\n return itemListWithoutLayerItems;\n}\n\nvoid FormEditorScene::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n if (editorView() && editorView()->model())\n currentTool()->mousePressEvent(removeLayerItems(items(event->scenePos())), event);\n}\n\nstatic QTime staticTimer()\n{\n QTime timer;\n timer.start();\n return timer;\n}\n\nvoid FormEditorScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)\n{\n static QTime time = staticTimer();\n\n if (time.elapsed() > 30) {\n time.restart();\n if (event->buttons())\n currentTool()->mouseMoveEvent(removeLayerItems(items(event->scenePos())), event);\n else\n currentTool()->hoverMoveEvent(removeLayerItems(items(event->scenePos())), event);\n\n event->accept();\n }\n}\n\nvoid FormEditorScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n if (editorView() && editorView()->model()) {\n currentTool()->mouseReleaseEvent(removeLayerItems(items(event->scenePos())), event);\n\n event->accept();\n }\n }\n\nvoid FormEditorScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)\n{\n if (editorView() && editorView()->model()) {\n currentTool()->mouseDoubleClickEvent(removeLayerItems(items(event->scenePos())), event);\n\n event->accept();\n }\n}\n\nvoid FormEditorScene::keyPressEvent(QKeyEvent *keyEvent)\n{\n if (editorView() && editorView()->model())\n currentTool()->keyPressEvent(keyEvent);\n}\n\nvoid FormEditorScene::keyReleaseEvent(QKeyEvent *keyEvent)\n{\n if (editorView() && editorView()->model())\n currentTool()->keyReleaseEvent(keyEvent);\n}\n\nFormEditorView *FormEditorScene::editorView() const\n{\n return m_editorView;\n}\n\nLayerItem* FormEditorScene::manipulatorLayerItem() const\n{\n return m_manipulatorLayerItem.data();\n}\n\nLayerItem* FormEditorScene::formLayerItem() const\n{\n return m_formLayerItem.data();\n}\n\nbool FormEditorScene::event(QEvent * event)\n{\n switch (event->type())\n {\n case QEvent::GraphicsSceneHoverEnter :\n hoverEnterEvent(static_cast(event));\n return true;\n case QEvent::GraphicsSceneHoverMove :\n hoverMoveEvent(static_cast(event));\n return true;\n case QEvent::GraphicsSceneHoverLeave :\n hoverLeaveEvent(static_cast(event));\n return true;\n case QEvent::ShortcutOverride :\n if (static_cast(event)->key() == Qt::Key_Escape) {\n currentTool()->keyPressEvent(static_cast(event));\n return true;\n }\n default: return QGraphicsScene::event(event);\n }\n\n}\n\nvoid FormEditorScene::hoverEnterEvent(QGraphicsSceneHoverEvent * \/*event*\/)\n{\n qDebug() << __FUNCTION__;\n}\n\nvoid FormEditorScene::hoverMoveEvent(QGraphicsSceneHoverEvent * \/*event*\/)\n{\n qDebug() << __FUNCTION__;\n}\n\nvoid FormEditorScene::hoverLeaveEvent(QGraphicsSceneHoverEvent * \/*event*\/)\n{\n qDebug() << __FUNCTION__;\n}\n\n\nvoid FormEditorScene::reparentItem(const QmlItemNode &node, const QmlItemNode &newParent)\n{\n Q_ASSERT(hasItemForQmlItemNode(node));\n FormEditorItem *item = itemForQmlItemNode(node);\n FormEditorItem *parentItem = 0;\n if (newParent.isValid() && hasItemForQmlItemNode(newParent))\n parentItem = itemForQmlItemNode(newParent);\n\n item->setParentItem(0);\n item->setParentItem(parentItem);\n}\n\nFormEditorItem* FormEditorScene::rootFormEditorItem() const\n{\n if (hasItemForQmlItemNode(editorView()->rootModelNode()))\n return itemForQmlItemNode(editorView()->rootModelNode());\n return 0;\n}\n\nvoid FormEditorScene::clearFormEditorItems()\n{\n QList itemList(items());\n\n foreach (QGraphicsItem *item, itemList) {\n if (qgraphicsitem_cast(item))\n item->setParentItem(0);\n }\n\n foreach (QGraphicsItem *item, itemList) {\n if (qgraphicsitem_cast(item))\n delete item;\n }\n}\n\nvoid FormEditorScene::highlightBoundingRect(FormEditorItem *highlighItem)\n{\n foreach (FormEditorItem *item, allFormEditorItems()) {\n if (item == highlighItem)\n item->setHighlightBoundingRect(true);\n else\n item->setHighlightBoundingRect(false);\n }\n}\n\nvoid FormEditorScene::setShowBoundingRects(bool show)\n{\n m_showBoundingRects = show;\n updateAllFormEditorItems();\n}\n\nbool FormEditorScene::showBoundingRects() const\n{\n return m_showBoundingRects;\n}\n\n}\n\n<|endoftext|>"} {"text":"#include \"..\/..\/..\/..\/Block_Diagonal_Matrix.hxx\"\n\n\/\/ Minimum eigenvalue of A. A is assumed to be symmetric.\n\n\/\/ Annoyingly, El::HermitianEig modifies 'block'. It is OK, because\n\/\/ it is only called from step_length(), which passes in a temporary.\n\/\/ Still ugly.\nEl::BigFloat min_eigenvalue(Block_Diagonal_Matrix &A)\n{\n El::BigFloat local_min(El::limits::Max());\n\n for(auto &block : A.blocks)\n {\n El::DistMatrix eigenvalues(block.Grid());\n \/\/\/ There is a bug in El::HermitianEig when there is more than\n \/\/\/ one level of recursion when computing eigenvalues. One fix\n \/\/\/ is to increase the cutoff so that there is no more than one\n \/\/\/ level of recursion.\n\n \/\/\/ An alternate workaround is to compute both eigenvalues and\n \/\/\/ eigenvectors, but that seems to be significantly slower.\n El::HermitianEigCtrl hermitian_eig_ctrl;\n hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff = block.Height() \/ 2 + 1;\n\n \/\/\/ The default number of iterations is 40. That is sometimes\n \/\/\/ not enough, so we bump it up significantly.\n hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.secularCtrl.maxIterations = 400;\n El::HermitianEig(El::UpperOrLowerNS::LOWER, block, eigenvalues,\n hermitian_eig_ctrl);\n local_min = El::Min(local_min, El::Min(eigenvalues));\n }\n return El::mpi::AllReduce(local_min, El::mpi::MIN, El::mpi::COMM_WORLD);\n}\nIncrease maxIterations for step length eigenvalues to 16384#include \"..\/..\/..\/..\/Block_Diagonal_Matrix.hxx\"\n\n\/\/ Minimum eigenvalue of A. A is assumed to be symmetric.\n\n\/\/ Annoyingly, El::HermitianEig modifies 'block'. It is OK, because\n\/\/ it is only called from step_length(), which passes in a temporary.\n\/\/ Still ugly.\nEl::BigFloat min_eigenvalue(Block_Diagonal_Matrix &A)\n{\n El::BigFloat local_min(El::limits::Max());\n\n for(auto &block : A.blocks)\n {\n El::DistMatrix eigenvalues(block.Grid());\n \/\/\/ There is a bug in El::HermitianEig when there is more than\n \/\/\/ one level of recursion when computing eigenvalues. One fix\n \/\/\/ is to increase the cutoff so that there is no more than one\n \/\/\/ level of recursion.\n\n \/\/\/ An alternate workaround is to compute both eigenvalues and\n \/\/\/ eigenvectors, but that seems to be significantly slower.\n El::HermitianEigCtrl hermitian_eig_ctrl;\n hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.cutoff = block.Height() \/ 2 + 1;\n\n \/\/\/ The default number of iterations is 40. That is sometimes\n \/\/\/ not enough, so we bump it up significantly.\n hermitian_eig_ctrl.tridiagEigCtrl.dcCtrl.secularCtrl.maxIterations = 16384;\n El::HermitianEig(El::UpperOrLowerNS::LOWER, block, eigenvalues,\n hermitian_eig_ctrl);\n local_min = El::Min(local_min, El::Min(eigenvalues));\n }\n return El::mpi::AllReduce(local_min, El::mpi::MIN, El::mpi::COMM_WORLD);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2017 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ RobustBufferAccessBehaviorTest:\n\/\/ Various tests related for GL_KHR_robust_buffer_access_behavior.\n\/\/\n\n#include \"test_utils\/ANGLETest.h\"\n#include \"test_utils\/gl_raii.h\"\n\n#include \n\nusing namespace angle;\n\nnamespace\n{\n\nclass RobustBufferAccessBehaviorTest : public ANGLETest\n{\n protected:\n RobustBufferAccessBehaviorTest() : mProgram(0), mTestAttrib(-1)\n {\n setWindowWidth(128);\n setWindowHeight(128);\n setConfigRedBits(8);\n setConfigGreenBits(8);\n setConfigBlueBits(8);\n setConfigAlphaBits(8);\n }\n\n void TearDown() override\n {\n glDeleteProgram(mProgram);\n ANGLETest::TearDown();\n }\n\n bool initExtension()\n {\n EGLWindow *window = getEGLWindow();\n EGLDisplay display = window->getDisplay();\n if (!eglDisplayExtensionEnabled(display, \"EGL_EXT_create_context_robustness\"))\n {\n return false;\n }\n\n ANGLETest::TearDown();\n setRobustAccess(true);\n ANGLETest::SetUp();\n if (!extensionEnabled(\"GL_KHR_robust_buffer_access_behavior\"))\n {\n return false;\n }\n return true;\n }\n\n void initBasicProgram()\n {\n const std::string &vsCheckOutOfBounds =\n \"precision mediump float;\\n\"\n \"attribute vec4 position;\\n\"\n \"attribute vec4 vecRandom;\\n\"\n \"varying vec4 v_color;\\n\"\n \"bool testFloatComponent(float component) {\\n\"\n \" return (component == 0.2 || component == 0.0);\\n\"\n \"}\\n\"\n \"bool testLastFloatComponent(float component) {\\n\"\n \" return testFloatComponent(component) || component == 1.0;\\n\"\n \"}\\n\"\n \"void main() {\\n\"\n \" if (testFloatComponent(vecRandom.x) &&\\n\"\n \" testFloatComponent(vecRandom.y) &&\\n\"\n \" testFloatComponent(vecRandom.z) &&\\n\"\n \" testLastFloatComponent(vecRandom.w)) {\\n\"\n \" v_color = vec4(0.0, 1.0, 0.0, 1.0);\\n\"\n \" } else {\\n\"\n \" v_color = vec4(1.0, 0.0, 0.0, 1.0);\\n\"\n \" }\\n\"\n \" gl_Position = position;\\n\"\n \"}\\n\";\n\n const std::string &fragmentShaderSource =\n \"precision mediump float;\\n\"\n \"varying vec4 v_color;\\n\"\n \"void main() {\\n\"\n \" gl_FragColor = v_color;\\n\"\n \"}\\n\";\n\n mProgram = CompileProgram(vsCheckOutOfBounds, fragmentShaderSource);\n ASSERT_NE(0u, mProgram);\n\n mTestAttrib = glGetAttribLocation(mProgram, \"vecRandom\");\n ASSERT_NE(-1, mTestAttrib);\n\n glUseProgram(mProgram);\n }\n\n void runIndexOutOfRangeTests(GLenum drawType)\n {\n if (mProgram == 0)\n {\n initBasicProgram();\n }\n\n GLBuffer bufferIncomplete;\n glBindBuffer(GL_ARRAY_BUFFER, bufferIncomplete);\n std::array randomData = {\n {0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f}};\n glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * randomData.size(), randomData.data(),\n drawType);\n\n glEnableVertexAttribArray(mTestAttrib);\n glVertexAttribPointer(mTestAttrib, 4, GL_FLOAT, GL_FALSE, 0, nullptr);\n\n glClearColor(0.0, 0.0, 1.0, 1.0);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n drawIndexedQuad(mProgram, \"position\", 0.5f);\n\n int width = getWindowWidth();\n int height = getWindowHeight();\n GLenum result = glGetError();\n \/\/ For D3D dynamic draw, we still return invalid operation. Once we force the index buffer\n \/\/ to clamp any out of range indices instead of invalid operation, this part can be removed.\n \/\/ We can always get GL_NO_ERROR.\n if (result == GL_INVALID_OPERATION)\n {\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 1 \/ 4, GLColor::blue);\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 3 \/ 4, GLColor::blue);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 1 \/ 4, GLColor::blue);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 3 \/ 4, GLColor::blue);\n }\n else\n {\n EXPECT_GLENUM_EQ(GL_NO_ERROR, result);\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 1 \/ 4, GLColor::green);\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 3 \/ 4, GLColor::green);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 1 \/ 4, GLColor::green);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 3 \/ 4, GLColor::green);\n }\n }\n\n GLuint mProgram;\n GLint mTestAttrib;\n};\n\n\/\/ Test that static draw with out-of-bounds reads will not read outside of the data store of the\n\/\/ buffer object and will not result in GL interruption or termination when\n\/\/ GL_KHR_robust_buffer_access_behavior is supported.\nTEST_P(RobustBufferAccessBehaviorTest, DrawElementsIndexOutOfRangeWithStaticDraw)\n{\n ANGLE_SKIP_TEST_IF(IsNVIDIA() && IsWindows() && IsOpenGL());\n ANGLE_SKIP_TEST_IF(!initExtension());\n\n runIndexOutOfRangeTests(GL_STATIC_DRAW);\n}\n\n\/\/ Test that dynamic draw with out-of-bounds reads will not read outside of the data store of the\n\/\/ buffer object and will not result in GL interruption or termination when\n\/\/ GL_KHR_robust_buffer_access_behavior is supported.\nTEST_P(RobustBufferAccessBehaviorTest, DrawElementsIndexOutOfRangeWithDynamicDraw)\n{\n ANGLE_SKIP_TEST_IF(IsNVIDIA() && IsWindows() && IsOpenGL());\n ANGLE_SKIP_TEST_IF(!initExtension());\n\n runIndexOutOfRangeTests(GL_DYNAMIC_DRAW);\n}\n\n\/\/ Test that vertex buffers are rebound with the correct offsets in subsequent calls in the D3D11\n\/\/ backend. http:\/\/crbug.com\/837002\nTEST_P(RobustBufferAccessBehaviorTest, D3D11StateSynchronizationOrderBug)\n{\n ANGLE_SKIP_TEST_IF(!initExtension());\n\n glDisable(GL_DEPTH_TEST);\n\n \/\/ 2 quads, the first one red, the second one green\n const std::array vertices{\n angle::Vector4(-1.0f, 1.0f, 0.5f, 1.0f), \/\/ v0\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c0\n angle::Vector4(-1.0f, -1.0f, 0.5f, 1.0f), \/\/ v1\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c1\n angle::Vector4(1.0f, -1.0f, 0.5f, 1.0f), \/\/ v2\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c2\n angle::Vector4(1.0f, 1.0f, 0.5f, 1.0f), \/\/ v3\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c3\n\n angle::Vector4(-1.0f, 1.0f, 0.5f, 1.0f), \/\/ v4\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c4\n angle::Vector4(-1.0f, -1.0f, 0.5f, 1.0f), \/\/ v5\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c5\n angle::Vector4(1.0f, -1.0f, 0.5f, 1.0f), \/\/ v6\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c6\n angle::Vector4(1.0f, 1.0f, 0.5f, 1.0f), \/\/ v7\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c7\n };\n\n GLBuffer vb;\n glBindBuffer(GL_ARRAY_BUFFER, vb);\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW);\n\n const std::array indicies{\n 0, 1, 2, 0, 2, 3, \/\/ quad0\n 4, 5, 6, 4, 6, 7, \/\/ quad1\n };\n\n GLBuffer ib;\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indicies), indicies.data(), GL_STATIC_DRAW);\n\n constexpr char kVS[] = R\"(\nprecision highp float;\nattribute vec4 a_position;\nattribute vec4 a_color;\n\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_Position = a_position;\n v_color = a_color;\n})\";\n\n constexpr char kFS[] = R\"(\nprecision highp float;\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_FragColor = v_color;\n})\";\n\n ANGLE_GL_PROGRAM(program, kVS, kFS);\n glUseProgram(program);\n\n GLint positionLocation = glGetAttribLocation(program, \"a_position\");\n glEnableVertexAttribArray(positionLocation);\n glVertexAttribPointer(positionLocation, 4, GL_FLOAT, GL_FALSE, sizeof(angle::Vector4) * 2, 0);\n\n GLint colorLocation = glGetAttribLocation(program, \"a_color\");\n glEnableVertexAttribArray(colorLocation);\n glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(angle::Vector4) * 2,\n reinterpret_cast(sizeof(angle::Vector4)));\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,\n reinterpret_cast(sizeof(GLshort) * 6));\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,\n reinterpret_cast(sizeof(GLshort) * 6));\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);\n}\n\n\/\/ Covers drawing with a very large vertex range which overflows GLsizei. http:\/\/crbug.com\/842028\nTEST_P(RobustBufferAccessBehaviorTest, VeryLargeVertexCountWithDynamicVertexData)\n{\n ANGLE_SKIP_TEST_IF(!initExtension());\n ANGLE_SKIP_TEST_IF(!extensionEnabled(\"GL_OES_element_index_uint\"));\n\n constexpr GLsizei kIndexCount = 32;\n std::array indices = {{}};\n for (GLsizei index = 0; index < kIndexCount; ++index)\n {\n indices[index] = ((std::numeric_limits::max() - 2) \/ kIndexCount) * index;\n }\n\n GLBuffer indexBuffer;\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), indices.data(),\n GL_STATIC_DRAW);\n\n std::array vertexData = {{}};\n\n GLBuffer vertexBuffer;\n glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(GLfloat), vertexData.data(),\n GL_DYNAMIC_DRAW);\n\n ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Simple(), essl1_shaders::fs::Red());\n glUseProgram(program);\n\n GLint attribLoc = glGetAttribLocation(program, essl1_shaders::PositionAttrib());\n ASSERT_NE(-1, attribLoc);\n\n glVertexAttribPointer(attribLoc, 2, GL_FLOAT, GL_FALSE, 0, nullptr);\n glEnableVertexAttribArray(attribLoc);\n ASSERT_GL_NO_ERROR();\n\n glDrawElements(GL_TRIANGLES, kIndexCount, GL_UNSIGNED_INT, nullptr);\n\n \/\/ This may or may not generate an error, but it should not crash.\n}\n\nANGLE_INSTANTIATE_TEST(RobustBufferAccessBehaviorTest,\n ES2_D3D9(),\n ES2_D3D11_FL9_3(),\n ES2_D3D11(),\n ES3_D3D11(),\n ES31_D3D11(),\n ES2_OPENGL(),\n ES3_OPENGL(),\n ES31_OPENGL(),\n ES2_OPENGLES(),\n ES3_OPENGLES(),\n ES31_OPENGLES());\n\n} \/\/ namespace\nSkip DrawElementsIndexOutOfRangeWithStaticDraw on NVIDIA D3D11 FL9.3.\/\/\n\/\/ Copyright 2017 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ RobustBufferAccessBehaviorTest:\n\/\/ Various tests related for GL_KHR_robust_buffer_access_behavior.\n\/\/\n\n#include \"test_utils\/ANGLETest.h\"\n#include \"test_utils\/gl_raii.h\"\n\n#include \n\nusing namespace angle;\n\nnamespace\n{\n\nclass RobustBufferAccessBehaviorTest : public ANGLETest\n{\n protected:\n RobustBufferAccessBehaviorTest() : mProgram(0), mTestAttrib(-1)\n {\n setWindowWidth(128);\n setWindowHeight(128);\n setConfigRedBits(8);\n setConfigGreenBits(8);\n setConfigBlueBits(8);\n setConfigAlphaBits(8);\n }\n\n void TearDown() override\n {\n glDeleteProgram(mProgram);\n ANGLETest::TearDown();\n }\n\n bool initExtension()\n {\n EGLWindow *window = getEGLWindow();\n EGLDisplay display = window->getDisplay();\n if (!eglDisplayExtensionEnabled(display, \"EGL_EXT_create_context_robustness\"))\n {\n return false;\n }\n\n ANGLETest::TearDown();\n setRobustAccess(true);\n ANGLETest::SetUp();\n if (!extensionEnabled(\"GL_KHR_robust_buffer_access_behavior\"))\n {\n return false;\n }\n return true;\n }\n\n void initBasicProgram()\n {\n const std::string &vsCheckOutOfBounds =\n \"precision mediump float;\\n\"\n \"attribute vec4 position;\\n\"\n \"attribute vec4 vecRandom;\\n\"\n \"varying vec4 v_color;\\n\"\n \"bool testFloatComponent(float component) {\\n\"\n \" return (component == 0.2 || component == 0.0);\\n\"\n \"}\\n\"\n \"bool testLastFloatComponent(float component) {\\n\"\n \" return testFloatComponent(component) || component == 1.0;\\n\"\n \"}\\n\"\n \"void main() {\\n\"\n \" if (testFloatComponent(vecRandom.x) &&\\n\"\n \" testFloatComponent(vecRandom.y) &&\\n\"\n \" testFloatComponent(vecRandom.z) &&\\n\"\n \" testLastFloatComponent(vecRandom.w)) {\\n\"\n \" v_color = vec4(0.0, 1.0, 0.0, 1.0);\\n\"\n \" } else {\\n\"\n \" v_color = vec4(1.0, 0.0, 0.0, 1.0);\\n\"\n \" }\\n\"\n \" gl_Position = position;\\n\"\n \"}\\n\";\n\n const std::string &fragmentShaderSource =\n \"precision mediump float;\\n\"\n \"varying vec4 v_color;\\n\"\n \"void main() {\\n\"\n \" gl_FragColor = v_color;\\n\"\n \"}\\n\";\n\n mProgram = CompileProgram(vsCheckOutOfBounds, fragmentShaderSource);\n ASSERT_NE(0u, mProgram);\n\n mTestAttrib = glGetAttribLocation(mProgram, \"vecRandom\");\n ASSERT_NE(-1, mTestAttrib);\n\n glUseProgram(mProgram);\n }\n\n void runIndexOutOfRangeTests(GLenum drawType)\n {\n if (mProgram == 0)\n {\n initBasicProgram();\n }\n\n GLBuffer bufferIncomplete;\n glBindBuffer(GL_ARRAY_BUFFER, bufferIncomplete);\n std::array randomData = {\n {0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f}};\n glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * randomData.size(), randomData.data(),\n drawType);\n\n glEnableVertexAttribArray(mTestAttrib);\n glVertexAttribPointer(mTestAttrib, 4, GL_FLOAT, GL_FALSE, 0, nullptr);\n\n glClearColor(0.0, 0.0, 1.0, 1.0);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n drawIndexedQuad(mProgram, \"position\", 0.5f);\n\n int width = getWindowWidth();\n int height = getWindowHeight();\n GLenum result = glGetError();\n \/\/ For D3D dynamic draw, we still return invalid operation. Once we force the index buffer\n \/\/ to clamp any out of range indices instead of invalid operation, this part can be removed.\n \/\/ We can always get GL_NO_ERROR.\n if (result == GL_INVALID_OPERATION)\n {\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 1 \/ 4, GLColor::blue);\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 3 \/ 4, GLColor::blue);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 1 \/ 4, GLColor::blue);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 3 \/ 4, GLColor::blue);\n }\n else\n {\n EXPECT_GLENUM_EQ(GL_NO_ERROR, result);\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 1 \/ 4, GLColor::green);\n EXPECT_PIXEL_COLOR_EQ(width * 1 \/ 4, height * 3 \/ 4, GLColor::green);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 1 \/ 4, GLColor::green);\n EXPECT_PIXEL_COLOR_EQ(width * 3 \/ 4, height * 3 \/ 4, GLColor::green);\n }\n }\n\n GLuint mProgram;\n GLint mTestAttrib;\n};\n\n\/\/ Test that static draw with out-of-bounds reads will not read outside of the data store of the\n\/\/ buffer object and will not result in GL interruption or termination when\n\/\/ GL_KHR_robust_buffer_access_behavior is supported.\nTEST_P(RobustBufferAccessBehaviorTest, DrawElementsIndexOutOfRangeWithStaticDraw)\n{\n ANGLE_SKIP_TEST_IF(IsNVIDIA() && IsWindows() && IsOpenGL());\n\n \/\/ Failing after changing the shard count of angle_end2end_tests. http:\/\/anglebug.com\/2799\n ANGLE_SKIP_TEST_IF(IsNVIDIA() && IsD3D11_FL93());\n\n ANGLE_SKIP_TEST_IF(!initExtension());\n\n runIndexOutOfRangeTests(GL_STATIC_DRAW);\n}\n\n\/\/ Test that dynamic draw with out-of-bounds reads will not read outside of the data store of the\n\/\/ buffer object and will not result in GL interruption or termination when\n\/\/ GL_KHR_robust_buffer_access_behavior is supported.\nTEST_P(RobustBufferAccessBehaviorTest, DrawElementsIndexOutOfRangeWithDynamicDraw)\n{\n ANGLE_SKIP_TEST_IF(IsNVIDIA() && IsWindows() && IsOpenGL());\n ANGLE_SKIP_TEST_IF(!initExtension());\n\n runIndexOutOfRangeTests(GL_DYNAMIC_DRAW);\n}\n\n\/\/ Test that vertex buffers are rebound with the correct offsets in subsequent calls in the D3D11\n\/\/ backend. http:\/\/crbug.com\/837002\nTEST_P(RobustBufferAccessBehaviorTest, D3D11StateSynchronizationOrderBug)\n{\n ANGLE_SKIP_TEST_IF(!initExtension());\n\n glDisable(GL_DEPTH_TEST);\n\n \/\/ 2 quads, the first one red, the second one green\n const std::array vertices{\n angle::Vector4(-1.0f, 1.0f, 0.5f, 1.0f), \/\/ v0\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c0\n angle::Vector4(-1.0f, -1.0f, 0.5f, 1.0f), \/\/ v1\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c1\n angle::Vector4(1.0f, -1.0f, 0.5f, 1.0f), \/\/ v2\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c2\n angle::Vector4(1.0f, 1.0f, 0.5f, 1.0f), \/\/ v3\n angle::Vector4(1.0f, 0.0f, 0.0f, 1.0f), \/\/ c3\n\n angle::Vector4(-1.0f, 1.0f, 0.5f, 1.0f), \/\/ v4\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c4\n angle::Vector4(-1.0f, -1.0f, 0.5f, 1.0f), \/\/ v5\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c5\n angle::Vector4(1.0f, -1.0f, 0.5f, 1.0f), \/\/ v6\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c6\n angle::Vector4(1.0f, 1.0f, 0.5f, 1.0f), \/\/ v7\n angle::Vector4(0.0f, 1.0f, 0.0f, 1.0f), \/\/ c7\n };\n\n GLBuffer vb;\n glBindBuffer(GL_ARRAY_BUFFER, vb);\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW);\n\n const std::array indicies{\n 0, 1, 2, 0, 2, 3, \/\/ quad0\n 4, 5, 6, 4, 6, 7, \/\/ quad1\n };\n\n GLBuffer ib;\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indicies), indicies.data(), GL_STATIC_DRAW);\n\n constexpr char kVS[] = R\"(\nprecision highp float;\nattribute vec4 a_position;\nattribute vec4 a_color;\n\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_Position = a_position;\n v_color = a_color;\n})\";\n\n constexpr char kFS[] = R\"(\nprecision highp float;\nvarying vec4 v_color;\n\nvoid main()\n{\n gl_FragColor = v_color;\n})\";\n\n ANGLE_GL_PROGRAM(program, kVS, kFS);\n glUseProgram(program);\n\n GLint positionLocation = glGetAttribLocation(program, \"a_position\");\n glEnableVertexAttribArray(positionLocation);\n glVertexAttribPointer(positionLocation, 4, GL_FLOAT, GL_FALSE, sizeof(angle::Vector4) * 2, 0);\n\n GLint colorLocation = glGetAttribLocation(program, \"a_color\");\n glEnableVertexAttribArray(colorLocation);\n glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(angle::Vector4) * 2,\n reinterpret_cast(sizeof(angle::Vector4)));\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,\n reinterpret_cast(sizeof(GLshort) * 6));\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);\n\n glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,\n reinterpret_cast(sizeof(GLshort) * 6));\n EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::green);\n}\n\n\/\/ Covers drawing with a very large vertex range which overflows GLsizei. http:\/\/crbug.com\/842028\nTEST_P(RobustBufferAccessBehaviorTest, VeryLargeVertexCountWithDynamicVertexData)\n{\n ANGLE_SKIP_TEST_IF(!initExtension());\n ANGLE_SKIP_TEST_IF(!extensionEnabled(\"GL_OES_element_index_uint\"));\n\n constexpr GLsizei kIndexCount = 32;\n std::array indices = {{}};\n for (GLsizei index = 0; index < kIndexCount; ++index)\n {\n indices[index] = ((std::numeric_limits::max() - 2) \/ kIndexCount) * index;\n }\n\n GLBuffer indexBuffer;\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), indices.data(),\n GL_STATIC_DRAW);\n\n std::array vertexData = {{}};\n\n GLBuffer vertexBuffer;\n glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(GLfloat), vertexData.data(),\n GL_DYNAMIC_DRAW);\n\n ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Simple(), essl1_shaders::fs::Red());\n glUseProgram(program);\n\n GLint attribLoc = glGetAttribLocation(program, essl1_shaders::PositionAttrib());\n ASSERT_NE(-1, attribLoc);\n\n glVertexAttribPointer(attribLoc, 2, GL_FLOAT, GL_FALSE, 0, nullptr);\n glEnableVertexAttribArray(attribLoc);\n ASSERT_GL_NO_ERROR();\n\n glDrawElements(GL_TRIANGLES, kIndexCount, GL_UNSIGNED_INT, nullptr);\n\n \/\/ This may or may not generate an error, but it should not crash.\n}\n\nANGLE_INSTANTIATE_TEST(RobustBufferAccessBehaviorTest,\n ES2_D3D9(),\n ES2_D3D11_FL9_3(),\n ES2_D3D11(),\n ES3_D3D11(),\n ES31_D3D11(),\n ES2_OPENGL(),\n ES3_OPENGL(),\n ES31_OPENGL(),\n ES2_OPENGLES(),\n ES3_OPENGLES(),\n ES31_OPENGLES());\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \"..\/..\/local\/include\/gtest\/gtest.h\"\n\n#include \n\n#include \"genetic.h\"\n#include \"genetic_circuit.h\"\n#include \"circuit.h\"\n#include \"utility.h\"\n\nTEST(InnocuousAttempt, NumberTwo) {\n BooleanTable expected_o = {{true, true, true},\n {true, true, false},\n {true, false, true},\n {true, false, false},\n {false, true, true},\n {false, true, false},\n {false, false, true},\n {false, false, false}};\n std::mt19937 rand(std::random_device{}());\n \/\/ std::minstd_rand0 rand(std::random_device{}());\n GeneticCircuit* c = new GeneticCircuit(3, 3, &rand);\n while (c->evaluateAllInputs() != expected_o) {\n delete c;\n c = new GeneticCircuit(3, 3, &rand);\n }\n}\nadd xor test#include \"..\/..\/local\/include\/gtest\/gtest.h\"\n\n#include \n\n\/\/ uncomment to use threads\n\/\/#define THREADED\n\n#ifdef THREADED\n\n\/\/ Tron\n\/\/#define NUM_CORES 4\n\/\/ Clue\n#define NUM_CORES 12\n\n#include \n#include \n\n#endif \/\/ THREADED\n\n#include \"genetic.h\"\n#include \"genetic_circuit.h\"\n#include \"circuit.h\"\n#include \"utility.h\"\n\nTEST(InnocuousAttempt, XOR) {\n BooleanTable expected_o = {{false, false},\n {false, true},\n {false, true},\n {true, false},\n {false, true},\n {true, false},\n {true, false},\n {true, true}};\n BooleanTable expected_o_bar = {{false, false},\n {true, false},\n {true, false},\n {false, true},\n {true, false},\n {false, true},\n {false, true},\n {true, true}};\n std::mt19937 rand(std::random_device{}());\n \/\/ std::minstd_rand0 rand(std::random_device{}());\n GeneticCircuit* c = new GeneticCircuit(3, 2, &rand);\n BooleanTable answer = c->evaluateAllInputs();\n int i = 0;\n\n \/\/ #ifdef THREADED\n \/\/ std::vector> boolean_table_futures;\n \/\/ #endif THREADED\n\n while ((answer != expected_o) || (answer != expected_o_bar)) {\n \/\/ #ifdef THREADED\n \/\/ for (int i = 0; i < (NUM_CORES - 1); ++i) {\n \/\/ boolean_table_futures.push_back(\n \/\/ std::async(std::launch::async, , points));\n \/\/ }\n \/\/ #endif THREADED\n\n \/\/ std::vector paths; \/\/ vector of possible paths\n \/\/ \/\/ Calculate a path on main thread while waiting for other threads\n \/\/ \/\/ If we're doing more than 1 set, do NUM_SETS random path calculations\n \/\/ on\n \/\/ \/\/ main thread\n \/\/ for (int i = 0; i < NUM_SETS; i++) {\n \/\/ paths.push_back(FindRandomPath(points));\n \/\/ }\n\n \/\/ \/\/ Get Paths from threads\n \/\/ for (auto& pathfuture : pathfutures) {\n \/\/ paths.push_back(pathfuture.get());\n \/\/ }\n\n delete c;\n c = new GeneticCircuit(3, 2, &rand);\n std::cerr << \"Iteration: \" + std::to_string(++i) << std::endl;\n \/\/ std::cerr << *c << std::endl;\n answer = c->evaluateAllInputs();\n }\n}\n\n\/\/ TEST(InnocuousAttempt, InvertInputs) {\n\/\/ BooleanTable expected_o = {{true, true, true},\n\/\/ {true, true, false},\n\/\/ {true, false, true},\n\/\/ {true, false, false},\n\/\/ {false, true, true},\n\/\/ {false, true, false},\n\/\/ {false, false, true},\n\/\/ {false, false, false}};\n\/\/ std::mt19937 rand(std::random_device{}());\n\/\/ \/\/ std::minstd_rand0 rand(std::random_device{}());\n\/\/ GeneticCircuit* c = new GeneticCircuit(3, 3, &rand);\n\/\/ while (c->evaluateAllInputs() != expected_o) {\n\/\/ delete c;\n\/\/ c = new GeneticCircuit(3, 3, &rand);\n\/\/ std::cerr << *c << std::endl;\n\/\/ }\n\/\/ }\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n : context_(ctx),\n trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector& clocks) {\n const auto snapshot_id = cur_snapshot_id_++;\n\n \/\/ Clear the cache\n cache_.fill({});\n\n \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n \/\/ used by the clock pathfinding logic.\n base::Hash hasher;\n for (const auto& clock : clocks)\n hasher.Update(clock.clock_id);\n const auto snapshot_hash = static_cast(hasher.digest());\n\n \/\/ Add a new entry in each clock's snapshot vector.\n for (const auto& clock : clocks) {\n ClockId clock_id = clock.clock_id;\n ClockDomain& domain = clocks_[clock_id];\n if (domain.snapshots.empty()) {\n if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n \" cannot use incremental encoding; this is only \"\n \"supported for sequence-scoped clocks.\",\n clock_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n domain.is_incremental = clock.is_incremental;\n } else if (PERFETTO_UNLIKELY(\n domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n domain.is_incremental != clock.is_incremental)) {\n PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n \" (unit=%\" PRIu64\n \", incremental=%d), was previously registered with \"\n \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n domain.unit_multiplier_ns, domain.is_incremental);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n const int64_t timestamp_ns =\n clock.absolute_timestamp * domain.unit_multiplier_ns;\n domain.last_timestamp_ns = timestamp_ns;\n\n ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n if (!vect.snapshot_ids.empty() &&\n PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n \" at snapshot %\" PRIu32 \".\",\n clock_id, snapshot_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n \/\/ this function.\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n \/\/ Snapshot IDs must be always monotonic.\n PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n vect.snapshot_ids.back() < snapshot_id);\n\n if (!vect.timestamps_ns.empty() &&\n timestamp_ns < vect.timestamps_ns.back()) {\n \/\/ Clock is not monotonic.\n\n if (clock_id == trace_time_clock_id_) {\n \/\/ The trace clock cannot be non-monotonic.\n PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n \" not >= %\" PRId64 \".\",\n clock_id, snapshot_id, timestamp_ns,\n vect.timestamps_ns.back());\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n \/\/ For the other clocks the best thing we can do is mark it as\n \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n \/\/ graph. We can still use it as a target clock, but not viceversa.\n \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n \/\/ daylight saving. We can still answer the question \"what was the\n \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n \/\/ same REALTIME instant because of the 1:many relationship.\n non_monotonic_clocks_.insert(clock_id);\n\n \/\/ Erase all edges from the graph that start from this clock (but keep the\n \/\/ ones that end on this clock).\n auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n graph_.erase(begin, end);\n }\n vect.snapshot_ids.emplace_back(snapshot_id);\n vect.timestamps_ns.emplace_back(timestamp_ns);\n }\n\n \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n \/\/ This is to store the information: Clock A is syncable to Clock B via the\n \/\/ snapshots of type (hash).\n \/\/ Clocks that were previously marked as non-monotonic won't be added as\n \/\/ valid sources.\n for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n auto it2 = it1;\n ++it2;\n for (; it2 != clocks.end(); ++it2) {\n if (!non_monotonic_clocks_.count(it1->clock_id))\n graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n if (!non_monotonic_clocks_.count(it2->clock_id))\n graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n }\n }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n \/\/ This is a classic breadth-first search. Each node in the queue holds also\n \/\/ the full path to reach that node.\n \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n \/\/ stop the search anyways.\n PERFETTO_CHECK(src != target);\n std::queue queue;\n queue.emplace(src);\n\n while (!queue.empty()) {\n ClockPath cur_path = queue.front();\n queue.pop();\n\n const ClockId cur_clock_id = cur_path.last;\n if (cur_clock_id == target)\n return cur_path;\n\n if (cur_path.len >= ClockPath::kMaxLen)\n continue;\n\n \/\/ Expore all the adjacent clocks.\n \/\/ The lower_bound() below returns an iterator to the first edge that starts\n \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n ClockGraphEdge(cur_clock_id, 0, 0));\n it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n ClockId next_clock_id = std::get<1>(*it);\n SnapshotHash hash = std::get<2>(*it);\n queue.push(ClockPath(cur_path, next_clock_id, hash));\n }\n }\n return ClockPath(); \/\/ invalid path.\n}\n\nbase::Optional ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n int64_t src_timestamp,\n ClockId target_clock_id) {\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n ClockPath path = FindPath(src_clock_id, target_clock_id);\n if (!path.valid()) {\n \/\/ Too many logs maybe emitted when path is invalid.\n static std::atomic dlog_count = 0;\n if (dlog_count++ < 10) {\n PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n \" at timestamp %\" PRId64,\n src_clock_id, target_clock_id, src_timestamp);\n }\n context_->storage->IncrementStats(stats::clock_sync_failure);\n return base::nullopt;\n }\n\n \/\/ We can cache only single-path resolutions between two clocks.\n \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n \/\/ too frequent these days, so we focus only on caching the more frequent\n \/\/ one-step resolutions (typically from any clock to the trace clock).\n const bool cacheable = path.len == 1;\n CachedClockPath cache_entry{};\n\n \/\/ Iterate trough the path found and translate timestamps onto the new clock\n \/\/ domain on each step, until the target domain is reached.\n ClockDomain* src_domain = GetClock(src_clock_id);\n int64_t ns = src_domain->ToNs(src_timestamp);\n for (uint32_t i = 0; i < path.len; ++i) {\n const ClockGraphEdge edge = path.at(i);\n ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n ClockDomain* next_clock = GetClock(std::get<1>(edge));\n const SnapshotHash hash = std::get<2>(edge);\n\n \/\/ Find the closest timestamp within the snapshots of the source clock.\n const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n const auto& ts_vec = cur_snap.timestamps_ns;\n auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n if (it != ts_vec.begin())\n --it;\n\n \/\/ Now lookup the snapshot id that matches the closest timestamp.\n size_t index = static_cast(std::distance(ts_vec.begin(), it));\n PERFETTO_DCHECK(index < ts_vec.size());\n PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n \/\/ And use that to retrieve the corresponding time in the next clock domain.\n \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n \/\/ either the hash logic or the pathfinding logic are bugged.\n \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n \/\/ of the snapshot.\n const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n \/\/ a binary search. std::find would do a linear scan.\n auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n next_snap.snapshot_ids.end(), snapshot_id);\n if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n continue;\n }\n size_t next_index = static_cast(\n std::distance(next_snap.snapshot_ids.begin(), next_it));\n PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n \/\/ The translated timestamp is the relative delta of the source timestamp\n \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n \/\/ the new clock domain for the same snapshot id.\n const int64_t adj = next_timestamp_ns - *it;\n ns += adj;\n\n \/\/ On the first iteration, keep track of the bounds for the cache entry.\n \/\/ This will allow future Convert() calls to skip the pathfinder logic\n \/\/ as long as the query stays within the bound.\n if (cacheable) {\n PERFETTO_DCHECK(i == 0);\n const int64_t kInt64Min = std::numeric_limits::min();\n const int64_t kInt64Max = std::numeric_limits::max();\n cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n auto ubound = it + 1;\n cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n cache_entry.translation_ns = adj;\n }\n\n \/\/ The last clock in the path must be the target clock.\n PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n }\n\n if (cacheable) {\n cache_entry.src = src_clock_id;\n cache_entry.src_domain = src_domain;\n cache_entry.target = target_clock_id;\n cache_[rnd_() % cache_.size()] = cache_entry;\n }\n\n return ns;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\nFix clock_tracker.cc am: 5dc147f282 am: f2faa3dd19 am: caf328c24a am: 55af9a1d07\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/importers\/common\/clock_tracker.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/ext\/base\/hash.h\"\n#include \"src\/trace_processor\/storage\/trace_storage.h\"\n#include \"src\/trace_processor\/types\/trace_processor_context.h\"\n\n#include \"protos\/perfetto\/common\/builtin_clock.pbzero.h\"\n#include \"protos\/perfetto\/trace\/clock_snapshot.pbzero.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nusing Clock = protos::pbzero::ClockSnapshot::Clock;\n\nClockTracker::ClockTracker(TraceProcessorContext* ctx)\n : context_(ctx),\n trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}\n\nClockTracker::~ClockTracker() = default;\n\nvoid ClockTracker::AddSnapshot(const std::vector& clocks) {\n const auto snapshot_id = cur_snapshot_id_++;\n\n \/\/ Clear the cache\n cache_.fill({});\n\n \/\/ Compute the fingerprint of the snapshot by hashing all clock ids. This is\n \/\/ used by the clock pathfinding logic.\n base::Hash hasher;\n for (const auto& clock : clocks)\n hasher.Update(clock.clock_id);\n const auto snapshot_hash = static_cast(hasher.digest());\n\n \/\/ Add a new entry in each clock's snapshot vector.\n for (const auto& clock : clocks) {\n ClockId clock_id = clock.clock_id;\n ClockDomain& domain = clocks_[clock_id];\n if (domain.snapshots.empty()) {\n if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {\n PERFETTO_ELOG(\"Clock sync error: the global clock with id=%\" PRIu64\n \" cannot use incremental encoding; this is only \"\n \"supported for sequence-scoped clocks.\",\n clock_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n domain.unit_multiplier_ns = clock.unit_multiplier_ns;\n domain.is_incremental = clock.is_incremental;\n } else if (PERFETTO_UNLIKELY(\n domain.unit_multiplier_ns != clock.unit_multiplier_ns ||\n domain.is_incremental != clock.is_incremental)) {\n PERFETTO_ELOG(\"Clock sync error: the clock domain with id=%\" PRIu64\n \" (unit=%\" PRIu64\n \", incremental=%d), was previously registered with \"\n \"different properties (unit=%\" PRIu64 \", incremental=%d).\",\n clock_id, clock.unit_multiplier_ns, clock.is_incremental,\n domain.unit_multiplier_ns, domain.is_incremental);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n const int64_t timestamp_ns =\n clock.absolute_timestamp * domain.unit_multiplier_ns;\n domain.last_timestamp_ns = timestamp_ns;\n\n ClockSnapshots& vect = domain.snapshots[snapshot_hash];\n if (!vect.snapshot_ids.empty() &&\n PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {\n PERFETTO_ELOG(\"Clock sync error: duplicate clock domain with id=%\" PRIu64\n \" at snapshot %\" PRIu32 \".\",\n clock_id, snapshot_id);\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n \/\/ Clock ids in the range [64, 128) are sequence-scoped and must be\n \/\/ translated to global ids via SeqScopedClockIdToGlobal() before calling\n \/\/ this function.\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));\n\n \/\/ Snapshot IDs must be always monotonic.\n PERFETTO_DCHECK(vect.snapshot_ids.empty() ||\n vect.snapshot_ids.back() < snapshot_id);\n\n if (!vect.timestamps_ns.empty() &&\n timestamp_ns < vect.timestamps_ns.back()) {\n \/\/ Clock is not monotonic.\n\n if (clock_id == trace_time_clock_id_) {\n \/\/ The trace clock cannot be non-monotonic.\n PERFETTO_ELOG(\"Clock sync error: the trace clock (id=%\" PRIu64\n \") is not monotonic at snapshot %\" PRIu32 \". %\" PRId64\n \" not >= %\" PRId64 \".\",\n clock_id, snapshot_id, timestamp_ns,\n vect.timestamps_ns.back());\n context_->storage->IncrementStats(stats::invalid_clock_snapshots);\n return;\n }\n\n PERFETTO_DLOG(\"Detected non-monotonic clock with ID %\" PRIu64, clock_id);\n\n \/\/ For the other clocks the best thing we can do is mark it as\n \/\/ non-monotonic and refuse to use it as a source clock in the resolution\n \/\/ graph. We can still use it as a target clock, but not viceversa.\n \/\/ The concrete example is the CLOCK_REALTIME going 1h backwards during\n \/\/ daylight saving. We can still answer the question \"what was the\n \/\/ REALTIME timestamp when BOOTTIME was X?\" but we can't answer the\n \/\/ opposite question because there can be two valid BOOTTIME(s) for the\n \/\/ same REALTIME instant because of the 1:many relationship.\n non_monotonic_clocks_.insert(clock_id);\n\n \/\/ Erase all edges from the graph that start from this clock (but keep the\n \/\/ ones that end on this clock).\n auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});\n auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});\n graph_.erase(begin, end);\n }\n vect.snapshot_ids.emplace_back(snapshot_id);\n vect.timestamps_ns.emplace_back(timestamp_ns);\n }\n\n \/\/ Create graph edges for all the possible tuples of clocks in this snapshot.\n \/\/ If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,\n \/\/ cd] and the symmetrical ones [ba, ca, da, bc, db, dc].\n \/\/ This is to store the information: Clock A is syncable to Clock B via the\n \/\/ snapshots of type (hash).\n \/\/ Clocks that were previously marked as non-monotonic won't be added as\n \/\/ valid sources.\n for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {\n auto it2 = it1;\n ++it2;\n for (; it2 != clocks.end(); ++it2) {\n if (!non_monotonic_clocks_.count(it1->clock_id))\n graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);\n\n if (!non_monotonic_clocks_.count(it2->clock_id))\n graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);\n }\n }\n}\n\n\/\/ Finds the shortest clock resolution path in the graph that allows to\n\/\/ translate a timestamp from |src| to |target| clocks.\n\/\/ The return value looks like the following: \"If you want to convert a\n\/\/ timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the\n\/\/ snapshot hash A, then convert C3 -> C2 via snapshot hash B\".\nClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {\n \/\/ This is a classic breadth-first search. Each node in the queue holds also\n \/\/ the full path to reach that node.\n \/\/ We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will\n \/\/ stop the search anyways.\n PERFETTO_CHECK(src != target);\n std::queue queue;\n queue.emplace(src);\n\n while (!queue.empty()) {\n ClockPath cur_path = queue.front();\n queue.pop();\n\n const ClockId cur_clock_id = cur_path.last;\n if (cur_clock_id == target)\n return cur_path;\n\n if (cur_path.len >= ClockPath::kMaxLen)\n continue;\n\n \/\/ Expore all the adjacent clocks.\n \/\/ The lower_bound() below returns an iterator to the first edge that starts\n \/\/ on |cur_clock_id|. The edges are sorted by (src, target, hash).\n for (auto it = std::lower_bound(graph_.begin(), graph_.end(),\n ClockGraphEdge(cur_clock_id, 0, 0));\n it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {\n ClockId next_clock_id = std::get<1>(*it);\n SnapshotHash hash = std::get<2>(*it);\n queue.push(ClockPath(cur_path, next_clock_id, hash));\n }\n }\n return ClockPath(); \/\/ invalid path.\n}\n\nbase::Optional ClockTracker::ConvertSlowpath(ClockId src_clock_id,\n int64_t src_timestamp,\n ClockId target_clock_id) {\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));\n PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));\n\n context_->storage->IncrementStats(stats::clock_sync_cache_miss);\n\n ClockPath path = FindPath(src_clock_id, target_clock_id);\n if (!path.valid()) {\n \/\/ Too many logs maybe emitted when path is invalid.\n static std::atomic dlog_count(0);\n if (dlog_count++ < 10) {\n PERFETTO_DLOG(\"No path from clock %\" PRIu64 \" to %\" PRIu64\n \" at timestamp %\" PRId64,\n src_clock_id, target_clock_id, src_timestamp);\n }\n context_->storage->IncrementStats(stats::clock_sync_failure);\n return base::nullopt;\n }\n\n \/\/ We can cache only single-path resolutions between two clocks.\n \/\/ Caching multi-path resolutions is harder because the (src,target) tuple\n \/\/ is not enough as a cache key: at any step the |ns| value can yield to a\n \/\/ different choice of the next snapshot. Multi-path resolutions don't seem\n \/\/ too frequent these days, so we focus only on caching the more frequent\n \/\/ one-step resolutions (typically from any clock to the trace clock).\n const bool cacheable = path.len == 1;\n CachedClockPath cache_entry{};\n\n \/\/ Iterate trough the path found and translate timestamps onto the new clock\n \/\/ domain on each step, until the target domain is reached.\n ClockDomain* src_domain = GetClock(src_clock_id);\n int64_t ns = src_domain->ToNs(src_timestamp);\n for (uint32_t i = 0; i < path.len; ++i) {\n const ClockGraphEdge edge = path.at(i);\n ClockDomain* cur_clock = GetClock(std::get<0>(edge));\n ClockDomain* next_clock = GetClock(std::get<1>(edge));\n const SnapshotHash hash = std::get<2>(edge);\n\n \/\/ Find the closest timestamp within the snapshots of the source clock.\n const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);\n const auto& ts_vec = cur_snap.timestamps_ns;\n auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);\n if (it != ts_vec.begin())\n --it;\n\n \/\/ Now lookup the snapshot id that matches the closest timestamp.\n size_t index = static_cast(std::distance(ts_vec.begin(), it));\n PERFETTO_DCHECK(index < ts_vec.size());\n PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());\n uint32_t snapshot_id = cur_snap.snapshot_ids[index];\n\n \/\/ And use that to retrieve the corresponding time in the next clock domain.\n \/\/ The snapshot id must exist in the target clock domain. If it doesn't\n \/\/ either the hash logic or the pathfinding logic are bugged.\n \/\/ This can also happen if the checks in AddSnapshot fail and we skip part\n \/\/ of the snapshot.\n const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);\n\n \/\/ Using std::lower_bound because snapshot_ids is sorted, so we can do\n \/\/ a binary search. std::find would do a linear scan.\n auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),\n next_snap.snapshot_ids.end(), snapshot_id);\n if (next_it == next_snap.snapshot_ids.end() || *next_it != snapshot_id) {\n PERFETTO_DFATAL(\"Snapshot does not exist in clock domain.\");\n continue;\n }\n size_t next_index = static_cast(\n std::distance(next_snap.snapshot_ids.begin(), next_it));\n PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());\n int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];\n\n \/\/ The translated timestamp is the relative delta of the source timestamp\n \/\/ from the closest snapshot found (ns - *it), plus the timestamp in\n \/\/ the new clock domain for the same snapshot id.\n const int64_t adj = next_timestamp_ns - *it;\n ns += adj;\n\n \/\/ On the first iteration, keep track of the bounds for the cache entry.\n \/\/ This will allow future Convert() calls to skip the pathfinder logic\n \/\/ as long as the query stays within the bound.\n if (cacheable) {\n PERFETTO_DCHECK(i == 0);\n const int64_t kInt64Min = std::numeric_limits::min();\n const int64_t kInt64Max = std::numeric_limits::max();\n cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;\n auto ubound = it + 1;\n cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;\n cache_entry.translation_ns = adj;\n }\n\n \/\/ The last clock in the path must be the target clock.\n PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);\n }\n\n if (cacheable) {\n cache_entry.src = src_clock_id;\n cache_entry.src_domain = src_domain;\n cache_entry.target = target_clock_id;\n cache_[rnd_() % cache_.size()] = cache_entry;\n }\n\n return ns;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/\/\n\/\/ W A R N I N G\n\/\/ -------------\n\/\/\n\/\/ This file is not part of the Qt API. It exists for the convenience\n\/\/ of other Qt classes. This header file may change from version to\n\/\/ version without notice, or even be removed.\n\/\/\n\/\/ We mean it.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"qaudio_mac_p.h\"\n#include \"qaudiodeviceinfo_mac_p.h\"\n\n\n\nQT_BEGIN_NAMESPACE\n\n\nQAudioDeviceInfoInternal::QAudioDeviceInfoInternal(QByteArray const& handle, QAudio::Mode)\n{\n QDataStream ds(handle);\n quint32 did, tm;\n\n ds >> did >> tm >> name;\n deviceId = AudioDeviceID(did);\n mode = QAudio::Mode(tm);\n}\n\nbool QAudioDeviceInfoInternal::isFormatSupported(const QAudioFormat& format) const\n{\n return format.codec() == QString::fromLatin1(\"audio\/pcm\");\n}\n\nQAudioFormat QAudioDeviceInfoInternal::preferredFormat() const\n{\n QAudioFormat rc;\n\n UInt32 propSize = 0;\n\n if (AudioDeviceGetPropertyInfo(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreams,\n &propSize,\n 0) == noErr) {\n\n const int sc = propSize \/ sizeof(AudioStreamID);\n\n if (sc > 0) {\n AudioStreamID* streams = new AudioStreamID[sc];\n\n if (AudioDeviceGetProperty(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreams,\n &propSize,\n streams) == noErr) {\n\n for (int i = 0; i < sc; ++i) {\n if (AudioStreamGetPropertyInfo(streams[i],\n 0,\n kAudioStreamPropertyPhysicalFormat,\n &propSize,\n 0) == noErr) {\n\n AudioStreamBasicDescription sf;\n\n if (AudioStreamGetProperty(streams[i],\n 0,\n kAudioStreamPropertyPhysicalFormat,\n &propSize,\n &sf) == noErr) {\n rc = toQAudioFormat(sf);\n break;\n }\n }\n }\n }\n\n delete streams;\n }\n }\n\n return rc;\n}\n\nQString QAudioDeviceInfoInternal::deviceName() const\n{\n return name;\n}\n\nQStringList QAudioDeviceInfoInternal::supportedCodecs()\n{\n return QStringList() << QString::fromLatin1(\"audio\/pcm\");\n}\n\nQList QAudioDeviceInfoInternal::supportedSampleRates()\n{\n QSet rc;\n\n \/\/ Add some common frequencies\n rc << 8000 << 11025 << 22050 << 44100;\n\n \/\/\n UInt32 propSize = 0;\n\n if (AudioDeviceGetPropertyInfo(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyAvailableNominalSampleRates,\n &propSize,\n 0) == noErr) {\n\n const int pc = propSize \/ sizeof(AudioValueRange);\n\n if (pc > 0) {\n AudioValueRange* vr = new AudioValueRange[pc];\n\n if (AudioDeviceGetProperty(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyAvailableNominalSampleRates,\n &propSize,\n vr) == noErr) {\n\n for (int i = 0; i < pc; ++i)\n rc << vr[i].mMaximum;\n }\n\n delete vr;\n }\n }\n\n return rc.toList();\n}\n\nQList QAudioDeviceInfoInternal::supportedChannelCounts()\n{\n QList rc;\n\n \/\/ Can mix down to 1 channel\n rc << 1;\n\n UInt32 propSize = 0;\n int channels = 0;\n\n if (AudioDeviceGetPropertyInfo(deviceId, \n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreamConfiguration,\n &propSize, \n 0) == noErr) {\n\n AudioBufferList* audioBufferList = static_cast(qMalloc(propSize));\n\n if (audioBufferList != 0) {\n if (AudioDeviceGetProperty(deviceId, \n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreamConfiguration,\n &propSize,\n audioBufferList) == noErr) {\n\n for (int i = 0; i < int(audioBufferList->mNumberBuffers); ++i) {\n channels += audioBufferList->mBuffers[i].mNumberChannels;\n rc << channels;\n }\n }\n\n qFree(audioBufferList);\n }\n }\n\n return rc;\n}\n\nQList QAudioDeviceInfoInternal::supportedSampleSizes()\n{\n return QList() << 8 << 16 << 24 << 32 << 64;\n}\n\nQList QAudioDeviceInfoInternal::supportedByteOrders()\n{\n return QList() << QAudioFormat::LittleEndian << QAudioFormat::BigEndian;\n}\n\nQList QAudioDeviceInfoInternal::supportedSampleTypes()\n{\n return QList() << QAudioFormat::SignedInt << QAudioFormat::UnSignedInt << QAudioFormat::Float;\n}\n\nstatic QByteArray get_device_info(AudioDeviceID audioDevice, QAudio::Mode mode)\n{\n UInt32 size;\n QByteArray device;\n QDataStream ds(&device, QIODevice::WriteOnly);\n AudioStreamBasicDescription sf;\n CFStringRef name;\n Boolean isInput = mode == QAudio::AudioInput;\n\n \/\/ Id\n ds << quint32(audioDevice);\n\n \/\/ Mode\n size = sizeof(AudioStreamBasicDescription);\n if (AudioDeviceGetProperty(audioDevice, 0, isInput, kAudioDevicePropertyStreamFormat,\n &size, &sf) != noErr) {\n return QByteArray();\n }\n ds << quint32(mode);\n\n \/\/ Name\n size = sizeof(CFStringRef);\n if (AudioDeviceGetProperty(audioDevice, 0, isInput, kAudioObjectPropertyName,\n &size, &name) != noErr) {\n qWarning() << \"QAudioDeviceInfo: Unable to find device name\";\n }\n ds << QCFString::toQString(name);\n\n CFRelease(name);\n\n return device;\n}\n\nQByteArray QAudioDeviceInfoInternal::defaultInputDevice()\n{\n AudioDeviceID audioDevice;\n UInt32 size = sizeof(audioDevice);\n\n if (AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &size,\n &audioDevice) != noErr) {\n qWarning() << \"QAudioDeviceInfo: Unable to find default input device\";\n return QByteArray();\n }\n\n return get_device_info(audioDevice, QAudio::AudioInput);\n}\n\nQByteArray QAudioDeviceInfoInternal::defaultOutputDevice()\n{\n AudioDeviceID audioDevice;\n UInt32 size = sizeof(audioDevice);\n\n if (AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size,\n &audioDevice) != noErr) {\n qWarning() << \"QAudioDeviceInfo: Unable to find default output device\";\n return QByteArray();\n }\n\n return get_device_info(audioDevice, QAudio::AudioOutput);\n}\n\nQList QAudioDeviceInfoInternal::availableDevices(QAudio::Mode mode)\n{\n QList devices;\n\n UInt32 propSize = 0;\n\n if (AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propSize, 0) == noErr) {\n\n const int dc = propSize \/ sizeof(AudioDeviceID);\n\n if (dc > 0) {\n AudioDeviceID* audioDevices = new AudioDeviceID[dc];\n\n if (AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propSize, audioDevices) == noErr) {\n for (int i = 0; i < dc; ++i) {\n QByteArray info = get_device_info(audioDevices[i], mode);\n if (!info.isNull())\n devices << info;\n }\n }\n\n delete audioDevices;\n }\n }\n\n return devices;\n}\n\n\nQT_END_NAMESPACE\n\nRemove use of Qt private API.\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/\/\n\/\/ W A R N I N G\n\/\/ -------------\n\/\/\n\/\/ This file is not part of the Qt API. It exists for the convenience\n\/\/ of other Qt classes. This header file may change from version to\n\/\/ version without notice, or even be removed.\n\/\/\n\/\/ We mean it.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"qaudio_mac_p.h\"\n#include \"qaudiodeviceinfo_mac_p.h\"\n\n\n\nQT_BEGIN_NAMESPACE\n\n\/\/ XXX: remove at some future date\nstatic inline QString cfStringToQString(CFStringRef str)\n{\n CFIndex length = CFStringGetLength(str);\n const UniChar *chars = CFStringGetCharactersPtr(str);\n if (chars)\n return QString(reinterpret_cast(chars), length);\n\n UniChar buffer[length];\n CFStringGetCharacters(str, CFRangeMake(0, length), buffer);\n return QString(reinterpret_cast(buffer), length);\n}\n\nQAudioDeviceInfoInternal::QAudioDeviceInfoInternal(QByteArray const& handle, QAudio::Mode)\n{\n QDataStream ds(handle);\n quint32 did, tm;\n\n ds >> did >> tm >> name;\n deviceId = AudioDeviceID(did);\n mode = QAudio::Mode(tm);\n}\n\nbool QAudioDeviceInfoInternal::isFormatSupported(const QAudioFormat& format) const\n{\n return format.codec() == QString::fromLatin1(\"audio\/pcm\");\n}\n\nQAudioFormat QAudioDeviceInfoInternal::preferredFormat() const\n{\n QAudioFormat rc;\n\n UInt32 propSize = 0;\n\n if (AudioDeviceGetPropertyInfo(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreams,\n &propSize,\n 0) == noErr) {\n\n const int sc = propSize \/ sizeof(AudioStreamID);\n\n if (sc > 0) {\n AudioStreamID* streams = new AudioStreamID[sc];\n\n if (AudioDeviceGetProperty(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreams,\n &propSize,\n streams) == noErr) {\n\n for (int i = 0; i < sc; ++i) {\n if (AudioStreamGetPropertyInfo(streams[i],\n 0,\n kAudioStreamPropertyPhysicalFormat,\n &propSize,\n 0) == noErr) {\n\n AudioStreamBasicDescription sf;\n\n if (AudioStreamGetProperty(streams[i],\n 0,\n kAudioStreamPropertyPhysicalFormat,\n &propSize,\n &sf) == noErr) {\n rc = toQAudioFormat(sf);\n break;\n }\n }\n }\n }\n\n delete streams;\n }\n }\n\n return rc;\n}\n\nQString QAudioDeviceInfoInternal::deviceName() const\n{\n return name;\n}\n\nQStringList QAudioDeviceInfoInternal::supportedCodecs()\n{\n return QStringList() << QString::fromLatin1(\"audio\/pcm\");\n}\n\nQList QAudioDeviceInfoInternal::supportedSampleRates()\n{\n QSet rc;\n\n \/\/ Add some common frequencies\n rc << 8000 << 11025 << 22050 << 44100;\n\n \/\/\n UInt32 propSize = 0;\n\n if (AudioDeviceGetPropertyInfo(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyAvailableNominalSampleRates,\n &propSize,\n 0) == noErr) {\n\n const int pc = propSize \/ sizeof(AudioValueRange);\n\n if (pc > 0) {\n AudioValueRange* vr = new AudioValueRange[pc];\n\n if (AudioDeviceGetProperty(deviceId,\n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyAvailableNominalSampleRates,\n &propSize,\n vr) == noErr) {\n\n for (int i = 0; i < pc; ++i)\n rc << vr[i].mMaximum;\n }\n\n delete vr;\n }\n }\n\n return rc.toList();\n}\n\nQList QAudioDeviceInfoInternal::supportedChannelCounts()\n{\n QList rc;\n\n \/\/ Can mix down to 1 channel\n rc << 1;\n\n UInt32 propSize = 0;\n int channels = 0;\n\n if (AudioDeviceGetPropertyInfo(deviceId, \n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreamConfiguration,\n &propSize, \n 0) == noErr) {\n\n AudioBufferList* audioBufferList = static_cast(qMalloc(propSize));\n\n if (audioBufferList != 0) {\n if (AudioDeviceGetProperty(deviceId, \n 0,\n mode == QAudio::AudioInput,\n kAudioDevicePropertyStreamConfiguration,\n &propSize,\n audioBufferList) == noErr) {\n\n for (int i = 0; i < int(audioBufferList->mNumberBuffers); ++i) {\n channels += audioBufferList->mBuffers[i].mNumberChannels;\n rc << channels;\n }\n }\n\n qFree(audioBufferList);\n }\n }\n\n return rc;\n}\n\nQList QAudioDeviceInfoInternal::supportedSampleSizes()\n{\n return QList() << 8 << 16 << 24 << 32 << 64;\n}\n\nQList QAudioDeviceInfoInternal::supportedByteOrders()\n{\n return QList() << QAudioFormat::LittleEndian << QAudioFormat::BigEndian;\n}\n\nQList QAudioDeviceInfoInternal::supportedSampleTypes()\n{\n return QList() << QAudioFormat::SignedInt << QAudioFormat::UnSignedInt << QAudioFormat::Float;\n}\n\nstatic QByteArray get_device_info(AudioDeviceID audioDevice, QAudio::Mode mode)\n{\n UInt32 size;\n QByteArray device;\n QDataStream ds(&device, QIODevice::WriteOnly);\n AudioStreamBasicDescription sf;\n CFStringRef name;\n Boolean isInput = mode == QAudio::AudioInput;\n\n \/\/ Id\n ds << quint32(audioDevice);\n\n \/\/ Mode\n size = sizeof(AudioStreamBasicDescription);\n if (AudioDeviceGetProperty(audioDevice, 0, isInput, kAudioDevicePropertyStreamFormat,\n &size, &sf) != noErr) {\n return QByteArray();\n }\n ds << quint32(mode);\n\n \/\/ Name\n size = sizeof(CFStringRef);\n if (AudioDeviceGetProperty(audioDevice, 0, isInput, kAudioObjectPropertyName,\n &size, &name) != noErr) {\n qWarning() << \"QAudioDeviceInfo: Unable to find device name\";\n }\n ds << cfStringToQString(name);\n\n CFRelease(name);\n\n return device;\n}\n\nQByteArray QAudioDeviceInfoInternal::defaultInputDevice()\n{\n AudioDeviceID audioDevice;\n UInt32 size = sizeof(audioDevice);\n\n if (AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &size,\n &audioDevice) != noErr) {\n qWarning() << \"QAudioDeviceInfo: Unable to find default input device\";\n return QByteArray();\n }\n\n return get_device_info(audioDevice, QAudio::AudioInput);\n}\n\nQByteArray QAudioDeviceInfoInternal::defaultOutputDevice()\n{\n AudioDeviceID audioDevice;\n UInt32 size = sizeof(audioDevice);\n\n if (AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size,\n &audioDevice) != noErr) {\n qWarning() << \"QAudioDeviceInfo: Unable to find default output device\";\n return QByteArray();\n }\n\n return get_device_info(audioDevice, QAudio::AudioOutput);\n}\n\nQList QAudioDeviceInfoInternal::availableDevices(QAudio::Mode mode)\n{\n QList devices;\n\n UInt32 propSize = 0;\n\n if (AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propSize, 0) == noErr) {\n\n const int dc = propSize \/ sizeof(AudioDeviceID);\n\n if (dc > 0) {\n AudioDeviceID* audioDevices = new AudioDeviceID[dc];\n\n if (AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propSize, audioDevices) == noErr) {\n for (int i = 0; i < dc; ++i) {\n QByteArray info = get_device_info(audioDevices[i], mode);\n if (!info.isNull())\n devices << info;\n }\n }\n\n delete audioDevices;\n }\n }\n\n return devices;\n}\n\n\nQT_END_NAMESPACE\n\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2014 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"language.h\"\n#include \"lookup_key.h\"\n#include \"region_data_constants.h\"\n#include \"rule.h\"\n#include \"util\/string_compare.h\"\n\nnamespace i18n {\nnamespace addressinput {\n\nSynonyms::Synonyms(const PreloadSupplier* supplier)\n : supplier_(supplier),\n compare_(new StringCompare) {\n assert(supplier_ != NULL);\n}\n\nSynonyms::~Synonyms() {}\n\nvoid Synonyms::NormalizeForDisplay(AddressData* address) const {\n assert(address != NULL);\n assert(supplier_->IsLoaded(address->region_code));\n\n AddressData region_address;\n region_address.region_code = address->region_code;\n LookupKey parent_key;\n parent_key.FromAddress(region_address);\n const Rule* parent_rule = supplier_->GetRule(parent_key);\n assert(parent_rule != NULL);\n\n const Language& best_language =\n ChooseBestAddressLanguage(*parent_rule, Language(address->language_code));\n\n LookupKey lookup_key;\n for (size_t depth = 1; depth < arraysize(LookupKey::kHierarchy); ++depth) {\n AddressField field = LookupKey::kHierarchy[depth];\n if (address->IsFieldEmpty(field)) {\n return;\n }\n const std::string& field_value = address->GetFieldValue(field);\n bool no_match_found_yet = true;\n for (std::vector::const_iterator\n key_it = parent_rule->GetSubKeys().begin();\n key_it != parent_rule->GetSubKeys().end(); ++key_it) {\n lookup_key.FromLookupKey(parent_key, *key_it);\n const Rule* rule = supplier_->GetRule(lookup_key);\n assert(rule != NULL);\n\n bool matches_latin_name =\n compare_->NaturalEquals(field_value, rule->GetLatinName());\n bool matches_local_name_id =\n compare_->NaturalEquals(field_value, *key_it) ||\n compare_->NaturalEquals(field_value, rule->GetName());\n if (matches_latin_name || matches_local_name_id) {\n address->SetFieldValue(\n field, matches_latin_name ? rule->GetLatinName() : *key_it);\n no_match_found_yet = false;\n parent_key.FromLookupKey(parent_key, *key_it);\n parent_rule = supplier_->GetRule(parent_key);\n assert(parent_rule != NULL);\n break;\n }\n }\n if (no_match_found_yet) {\n return; \/\/ Abort search.\n }\n }\n}\n\n} \/\/ namespace addressinput\n} \/\/ namespace i18n\nDelete unused call to ChooseBestAddressLanguage().\/\/ Copyright (C) 2014 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"lookup_key.h\"\n#include \"region_data_constants.h\"\n#include \"rule.h\"\n#include \"util\/string_compare.h\"\n\nnamespace i18n {\nnamespace addressinput {\n\nSynonyms::Synonyms(const PreloadSupplier* supplier)\n : supplier_(supplier),\n compare_(new StringCompare) {\n assert(supplier_ != NULL);\n}\n\nSynonyms::~Synonyms() {}\n\nvoid Synonyms::NormalizeForDisplay(AddressData* address) const {\n assert(address != NULL);\n assert(supplier_->IsLoaded(address->region_code));\n\n AddressData region_address;\n region_address.region_code = address->region_code;\n LookupKey parent_key;\n parent_key.FromAddress(region_address);\n const Rule* parent_rule = supplier_->GetRule(parent_key);\n assert(parent_rule != NULL);\n\n LookupKey lookup_key;\n for (size_t depth = 1; depth < arraysize(LookupKey::kHierarchy); ++depth) {\n AddressField field = LookupKey::kHierarchy[depth];\n if (address->IsFieldEmpty(field)) {\n return;\n }\n const std::string& field_value = address->GetFieldValue(field);\n bool no_match_found_yet = true;\n for (std::vector::const_iterator\n key_it = parent_rule->GetSubKeys().begin();\n key_it != parent_rule->GetSubKeys().end(); ++key_it) {\n lookup_key.FromLookupKey(parent_key, *key_it);\n const Rule* rule = supplier_->GetRule(lookup_key);\n assert(rule != NULL);\n\n bool matches_latin_name =\n compare_->NaturalEquals(field_value, rule->GetLatinName());\n bool matches_local_name_id =\n compare_->NaturalEquals(field_value, *key_it) ||\n compare_->NaturalEquals(field_value, rule->GetName());\n if (matches_latin_name || matches_local_name_id) {\n address->SetFieldValue(\n field, matches_latin_name ? rule->GetLatinName() : *key_it);\n no_match_found_yet = false;\n parent_key.FromLookupKey(parent_key, *key_it);\n parent_rule = supplier_->GetRule(parent_key);\n assert(parent_rule != NULL);\n break;\n }\n }\n if (no_match_found_yet) {\n return; \/\/ Abort search.\n }\n }\n}\n\n} \/\/ namespace addressinput\n} \/\/ namespace i18n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"camera.h\"\n#include \"ui_camera.h\"\n#include \"videosettings.h\"\n#include \"imagesettings.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#if (defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)) && QT_VERSION >= 0x040700\n#define HAVE_CAMERA_BUTTONS\n#endif\n\nCamera::Camera(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::Camera),\n camera(0),\n imageCapture(0),\n mediaRecorder(0)\n{\n ui->setupUi(this);\n\n \/\/Camera devices:\n QByteArray cameraDevice;\n\n QActionGroup *videoDevicesGroup = new QActionGroup(this);\n videoDevicesGroup->setExclusive(true);\n foreach(const QByteArray &deviceName, QCamera::availableDevices()) {\n QString description = camera->deviceDescription(deviceName);\n QAction *videoDeviceAction = new QAction(description, videoDevicesGroup);\n videoDeviceAction->setCheckable(true);\n videoDeviceAction->setData(QVariant(deviceName));\n if (cameraDevice.isEmpty()) {\n cameraDevice = deviceName;\n videoDeviceAction->setChecked(true);\n }\n ui->menuDevices->addAction(videoDeviceAction);\n }\n\n connect(videoDevicesGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateCameraDevice(QAction*)));\n connect(ui->captureWidget, SIGNAL(currentChanged(int)), SLOT(updateCaptureMode()));\n\n#ifdef HAVE_CAMERA_BUTTONS\n ui->lockButton->hide();\n#endif\n\n setCamera(cameraDevice);\n}\n\nCamera::~Camera()\n{\n delete mediaRecorder;\n delete imageCapture;\n delete camera;\n}\n\nvoid Camera::setCamera(const QByteArray &cameraDevice)\n{\n delete imageCapture;\n delete mediaRecorder;\n delete camera;\n\n if (cameraDevice.isEmpty())\n camera = new QCamera;\n else\n camera = new QCamera(cameraDevice);\n\n connect(camera, SIGNAL(stateChanged(QCamera::State)), this, SLOT(updateCameraState(QCamera::State)));\n connect(camera, SIGNAL(error(QCamera::Error)), this, SLOT(displayCameraError()));\n\n mediaRecorder = new QMediaRecorder(camera);\n connect(mediaRecorder, SIGNAL(stateChanged(QMediaRecorder::State)), this, SLOT(updateRecorderState(QMediaRecorder::State)));\n\n imageCapture = new QCameraImageCapture(camera);\n\n connect(mediaRecorder, SIGNAL(durationChanged(qint64)), this, SLOT(updateRecordTime()));\n connect(mediaRecorder, SIGNAL(error(QMediaRecorder::Error)), this, SLOT(displayRecorderError()));\n\n mediaRecorder->setMetaData(QtMultimediaKit::Title, QVariant(QLatin1String(\"Test Title\")));\n\n connect(ui->exposureCompensation, SIGNAL(valueChanged(int)), SLOT(setExposureCompensation(int)));\n\n camera->setViewfinder(ui->viewfinder);\n\n updateCameraState(camera->state());\n updateLockStatus(camera->lockStatus(), QCamera::UserRequest);\n updateRecorderState(mediaRecorder->state());\n\n connect(imageCapture, SIGNAL(readyForCaptureChanged(bool)), ui->takeImageButton, SLOT(setEnabled(bool)));\n connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(processCapturedImage(int,QImage)));\n\n connect(camera, SIGNAL(lockStatusChanged(QCamera::LockStatus, QCamera::LockChangeReason)),\n this, SLOT(updateLockStatus(QCamera::LockStatus, QCamera::LockChangeReason)));\n\n updateCaptureMode();\n camera->start();\n}\n\nvoid Camera::keyPressEvent(QKeyEvent * event)\n{\n switch (event->key()) {\n#if QT_VERSION >= 0x040700\n case Qt::Key_CameraFocus:\n camera->searchAndLock();\n break;\n case Qt::Key_Camera:\n if (camera->captureMode() == QCamera::CaptureStillImage)\n takeImage();\n else\n record();\n break;\n#endif\n default:\n QMainWindow::keyPressEvent(event);\n }\n}\n\nvoid Camera::keyReleaseEvent(QKeyEvent * event)\n{\n switch (event->key()) {\n#if QT_VERSION >= 0x040700\n case Qt::Key_CameraFocus:\n camera->unlock();\n break;\n case Qt::Key_Camera:\n if (camera->captureMode() == QCamera::CaptureVideo)\n stop();\n break;\n#endif\n default:\n QMainWindow::keyReleaseEvent(event);\n }\n}\n\nvoid Camera::updateRecordTime()\n{\n QString str = QString(\"Recorded %1 sec\").arg(mediaRecorder->duration()\/1000);\n ui->statusbar->showMessage(str);\n}\n\nvoid Camera::processCapturedImage(int requestId, const QImage& img)\n{\n Q_UNUSED(requestId);\n QImage scaledImage = img.scaled(ui->viewfinder->size(),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n ui->lastImagePreviewLabel->setPixmap(QPixmap::fromImage(scaledImage));\n\n \/\/display captured image for 4 seconds\n displayCapturedImage();\n QTimer::singleShot(4000, this, SLOT(displayViewfinder()));\n}\n\nvoid Camera::configureCaptureSettings()\n{\n switch (camera->captureMode()) {\n case QCamera::CaptureStillImage:\n configureImageSettings();\n break;\n case QCamera::CaptureVideo:\n configureVideoSettings();\n break;\n default:\n break;\n }\n}\n\nvoid Camera::configureVideoSettings()\n{\n VideoSettings settingsDialog(mediaRecorder);\n\n settingsDialog.setAudioSettings(audioSettings);\n settingsDialog.setVideoSettings(videoSettings);\n settingsDialog.setFormat(videoContainerFormat);\n\n if (settingsDialog.exec()) {\n audioSettings = settingsDialog.audioSettings();\n videoSettings = settingsDialog.videoSettings();\n videoContainerFormat = settingsDialog.format();\n\n mediaRecorder->setEncodingSettings(\n audioSettings,\n videoSettings,\n videoContainerFormat);\n }\n}\n\nvoid Camera::configureImageSettings()\n{\n ImageSettings settingsDialog(imageCapture);\n\n settingsDialog.setImageSettings(imageSettings);\n\n if (settingsDialog.exec()) {\n imageSettings = settingsDialog.imageSettings();\n imageCapture->setEncodingSettings(imageSettings);\n }\n}\n\nvoid Camera::record()\n{\n mediaRecorder->record();\n updateRecordTime();\n}\n\nvoid Camera::pause()\n{\n mediaRecorder->pause();\n}\n\nvoid Camera::stop()\n{\n mediaRecorder->stop();\n}\n\nvoid Camera::setMuted(bool muted)\n{\n mediaRecorder->setMuted(muted);\n}\n\nvoid Camera::toggleLock()\n{\n switch (camera->lockStatus()) {\n case QCamera::Searching:\n case QCamera::Locked:\n camera->unlock();\n break;\n case QCamera::Unlocked:\n camera->searchAndLock();\n }\n}\n\nvoid Camera::updateLockStatus(QCamera::LockStatus status, QCamera::LockChangeReason reason)\n{\n QColor indicationColor = Qt::black;\n\n switch (status) {\n case QCamera::Searching:\n indicationColor = Qt::yellow;\n ui->statusbar->showMessage(tr(\"Focusing...\"));\n ui->lockButton->setText(tr(\"Focusing...\"));\n break;\n case QCamera::Locked:\n indicationColor = Qt::darkGreen; \n ui->lockButton->setText(tr(\"Unlock\"));\n ui->statusbar->showMessage(tr(\"Focused\"), 2000);\n break;\n case QCamera::Unlocked:\n indicationColor = reason == QCamera::LockFailed ? Qt::red : Qt::black;\n ui->lockButton->setText(tr(\"Focus\"));\n if (reason == QCamera::LockFailed)\n ui->statusbar->showMessage(tr(\"Focus Failed\"), 2000);\n }\n\n QPalette palette = ui->lockButton->palette();\n palette.setColor(QPalette::ButtonText, indicationColor);\n ui->lockButton->setPalette(palette);\n}\n\nvoid Camera::takeImage()\n{\n imageCapture->capture();\n}\n\nvoid Camera::startCamera()\n{\n camera->start();\n}\n\nvoid Camera::stopCamera()\n{\n camera->stop();\n}\n\nvoid Camera::updateCaptureMode()\n{\n int tabIndex = ui->captureWidget->currentIndex();\n QCamera::CaptureMode captureMode = tabIndex == 0 ? QCamera::CaptureStillImage : QCamera::CaptureVideo;\n camera->setCaptureMode(captureMode);\n}\n\nvoid Camera::updateCameraState(QCamera::State state)\n{\n switch (state) { \n case QCamera::ActiveState:\n ui->actionStartCamera->setEnabled(false);\n ui->actionStopCamera->setEnabled(true);\n ui->captureWidget->setEnabled(true);\n ui->actionSettings->setEnabled(true);\n break;\n case QCamera::UnloadedState:\n case QCamera::LoadedState:\n ui->actionStartCamera->setEnabled(true);\n ui->actionStopCamera->setEnabled(false);\n ui->captureWidget->setEnabled(false);\n ui->actionSettings->setEnabled(false);\n }\n}\n\nvoid Camera::updateRecorderState(QMediaRecorder::State state)\n{\n switch (state) {\n case QMediaRecorder::StoppedState:\n ui->recordButton->setEnabled(true);\n ui->pauseButton->setEnabled(true);\n ui->stopButton->setEnabled(false);\n break;\n case QMediaRecorder::PausedState:\n ui->recordButton->setEnabled(true);\n ui->pauseButton->setEnabled(false);\n ui->stopButton->setEnabled(true);\n break;\n case QMediaRecorder::RecordingState:\n ui->recordButton->setEnabled(false);\n ui->pauseButton->setEnabled(true);\n ui->stopButton->setEnabled(true);\n break;\n }\n}\n\nvoid Camera::setExposureCompensation(int index)\n{\n camera->exposure()->setExposureCompensation(index*0.5);\n}\n\nvoid Camera::displayRecorderError()\n{\n QMessageBox::warning(this, tr(\"Capture error\"), mediaRecorder->errorString());\n}\n\nvoid Camera::displayCameraError()\n{\n QMessageBox::warning(this, tr(\"Camera error\"), camera->errorString());\n}\n\nvoid Camera::updateCameraDevice(QAction *action)\n{\n setCamera(action->data().toByteArray());\n}\n\nvoid Camera::displayViewfinder()\n{\n ui->stackedWidget->setCurrentIndex(0);\n}\n\nvoid Camera::displayCapturedImage()\n{\n ui->stackedWidget->setCurrentIndex(1);\n}\nCamera example: toggle recording when the camera button is pressed instead of recording while the button is pressed.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"camera.h\"\n#include \"ui_camera.h\"\n#include \"videosettings.h\"\n#include \"imagesettings.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#if (defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)) && QT_VERSION >= 0x040700\n#define HAVE_CAMERA_BUTTONS\n#endif\n\nCamera::Camera(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::Camera),\n camera(0),\n imageCapture(0),\n mediaRecorder(0)\n{\n ui->setupUi(this);\n\n \/\/Camera devices:\n QByteArray cameraDevice;\n\n QActionGroup *videoDevicesGroup = new QActionGroup(this);\n videoDevicesGroup->setExclusive(true);\n foreach(const QByteArray &deviceName, QCamera::availableDevices()) {\n QString description = camera->deviceDescription(deviceName);\n QAction *videoDeviceAction = new QAction(description, videoDevicesGroup);\n videoDeviceAction->setCheckable(true);\n videoDeviceAction->setData(QVariant(deviceName));\n if (cameraDevice.isEmpty()) {\n cameraDevice = deviceName;\n videoDeviceAction->setChecked(true);\n }\n ui->menuDevices->addAction(videoDeviceAction);\n }\n\n connect(videoDevicesGroup, SIGNAL(triggered(QAction*)), this, SLOT(updateCameraDevice(QAction*)));\n connect(ui->captureWidget, SIGNAL(currentChanged(int)), SLOT(updateCaptureMode()));\n\n#ifdef HAVE_CAMERA_BUTTONS\n ui->lockButton->hide();\n#endif\n\n setCamera(cameraDevice);\n}\n\nCamera::~Camera()\n{\n delete mediaRecorder;\n delete imageCapture;\n delete camera;\n}\n\nvoid Camera::setCamera(const QByteArray &cameraDevice)\n{\n delete imageCapture;\n delete mediaRecorder;\n delete camera;\n\n if (cameraDevice.isEmpty())\n camera = new QCamera;\n else\n camera = new QCamera(cameraDevice);\n\n connect(camera, SIGNAL(stateChanged(QCamera::State)), this, SLOT(updateCameraState(QCamera::State)));\n connect(camera, SIGNAL(error(QCamera::Error)), this, SLOT(displayCameraError()));\n\n mediaRecorder = new QMediaRecorder(camera);\n connect(mediaRecorder, SIGNAL(stateChanged(QMediaRecorder::State)), this, SLOT(updateRecorderState(QMediaRecorder::State)));\n\n imageCapture = new QCameraImageCapture(camera);\n\n connect(mediaRecorder, SIGNAL(durationChanged(qint64)), this, SLOT(updateRecordTime()));\n connect(mediaRecorder, SIGNAL(error(QMediaRecorder::Error)), this, SLOT(displayRecorderError()));\n\n mediaRecorder->setMetaData(QtMultimediaKit::Title, QVariant(QLatin1String(\"Test Title\")));\n\n connect(ui->exposureCompensation, SIGNAL(valueChanged(int)), SLOT(setExposureCompensation(int)));\n\n camera->setViewfinder(ui->viewfinder);\n\n updateCameraState(camera->state());\n updateLockStatus(camera->lockStatus(), QCamera::UserRequest);\n updateRecorderState(mediaRecorder->state());\n\n connect(imageCapture, SIGNAL(readyForCaptureChanged(bool)), ui->takeImageButton, SLOT(setEnabled(bool)));\n connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(processCapturedImage(int,QImage)));\n\n connect(camera, SIGNAL(lockStatusChanged(QCamera::LockStatus, QCamera::LockChangeReason)),\n this, SLOT(updateLockStatus(QCamera::LockStatus, QCamera::LockChangeReason)));\n\n updateCaptureMode();\n camera->start();\n}\n\nvoid Camera::keyPressEvent(QKeyEvent * event)\n{\n switch (event->key()) {\n#if QT_VERSION >= 0x040700\n case Qt::Key_CameraFocus:\n camera->searchAndLock();\n break;\n case Qt::Key_Camera:\n if (camera->captureMode() == QCamera::CaptureStillImage) {\n takeImage();\n } else {\n if (mediaRecorder->state() == QMediaRecorder::RecordingState)\n stop();\n else\n record();\n }\n break;\n#endif\n default:\n QMainWindow::keyPressEvent(event);\n }\n}\n\nvoid Camera::keyReleaseEvent(QKeyEvent * event)\n{\n switch (event->key()) {\n#if QT_VERSION >= 0x040700\n case Qt::Key_CameraFocus:\n camera->unlock();\n break;\n#endif\n default:\n QMainWindow::keyReleaseEvent(event);\n }\n}\n\nvoid Camera::updateRecordTime()\n{\n QString str = QString(\"Recorded %1 sec\").arg(mediaRecorder->duration()\/1000);\n ui->statusbar->showMessage(str);\n}\n\nvoid Camera::processCapturedImage(int requestId, const QImage& img)\n{\n Q_UNUSED(requestId);\n QImage scaledImage = img.scaled(ui->viewfinder->size(),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n ui->lastImagePreviewLabel->setPixmap(QPixmap::fromImage(scaledImage));\n\n \/\/display captured image for 4 seconds\n displayCapturedImage();\n QTimer::singleShot(4000, this, SLOT(displayViewfinder()));\n}\n\nvoid Camera::configureCaptureSettings()\n{\n switch (camera->captureMode()) {\n case QCamera::CaptureStillImage:\n configureImageSettings();\n break;\n case QCamera::CaptureVideo:\n configureVideoSettings();\n break;\n default:\n break;\n }\n}\n\nvoid Camera::configureVideoSettings()\n{\n VideoSettings settingsDialog(mediaRecorder);\n\n settingsDialog.setAudioSettings(audioSettings);\n settingsDialog.setVideoSettings(videoSettings);\n settingsDialog.setFormat(videoContainerFormat);\n\n if (settingsDialog.exec()) {\n audioSettings = settingsDialog.audioSettings();\n videoSettings = settingsDialog.videoSettings();\n videoContainerFormat = settingsDialog.format();\n\n mediaRecorder->setEncodingSettings(\n audioSettings,\n videoSettings,\n videoContainerFormat);\n }\n}\n\nvoid Camera::configureImageSettings()\n{\n ImageSettings settingsDialog(imageCapture);\n\n settingsDialog.setImageSettings(imageSettings);\n\n if (settingsDialog.exec()) {\n imageSettings = settingsDialog.imageSettings();\n imageCapture->setEncodingSettings(imageSettings);\n }\n}\n\nvoid Camera::record()\n{\n mediaRecorder->record();\n updateRecordTime();\n}\n\nvoid Camera::pause()\n{\n mediaRecorder->pause();\n}\n\nvoid Camera::stop()\n{\n mediaRecorder->stop();\n}\n\nvoid Camera::setMuted(bool muted)\n{\n mediaRecorder->setMuted(muted);\n}\n\nvoid Camera::toggleLock()\n{\n switch (camera->lockStatus()) {\n case QCamera::Searching:\n case QCamera::Locked:\n camera->unlock();\n break;\n case QCamera::Unlocked:\n camera->searchAndLock();\n }\n}\n\nvoid Camera::updateLockStatus(QCamera::LockStatus status, QCamera::LockChangeReason reason)\n{\n QColor indicationColor = Qt::black;\n\n switch (status) {\n case QCamera::Searching:\n indicationColor = Qt::yellow;\n ui->statusbar->showMessage(tr(\"Focusing...\"));\n ui->lockButton->setText(tr(\"Focusing...\"));\n break;\n case QCamera::Locked:\n indicationColor = Qt::darkGreen; \n ui->lockButton->setText(tr(\"Unlock\"));\n ui->statusbar->showMessage(tr(\"Focused\"), 2000);\n break;\n case QCamera::Unlocked:\n indicationColor = reason == QCamera::LockFailed ? Qt::red : Qt::black;\n ui->lockButton->setText(tr(\"Focus\"));\n if (reason == QCamera::LockFailed)\n ui->statusbar->showMessage(tr(\"Focus Failed\"), 2000);\n }\n\n QPalette palette = ui->lockButton->palette();\n palette.setColor(QPalette::ButtonText, indicationColor);\n ui->lockButton->setPalette(palette);\n}\n\nvoid Camera::takeImage()\n{\n imageCapture->capture();\n}\n\nvoid Camera::startCamera()\n{\n camera->start();\n}\n\nvoid Camera::stopCamera()\n{\n camera->stop();\n}\n\nvoid Camera::updateCaptureMode()\n{\n int tabIndex = ui->captureWidget->currentIndex();\n QCamera::CaptureMode captureMode = tabIndex == 0 ? QCamera::CaptureStillImage : QCamera::CaptureVideo;\n camera->setCaptureMode(captureMode);\n}\n\nvoid Camera::updateCameraState(QCamera::State state)\n{\n switch (state) { \n case QCamera::ActiveState:\n ui->actionStartCamera->setEnabled(false);\n ui->actionStopCamera->setEnabled(true);\n ui->captureWidget->setEnabled(true);\n ui->actionSettings->setEnabled(true);\n break;\n case QCamera::UnloadedState:\n case QCamera::LoadedState:\n ui->actionStartCamera->setEnabled(true);\n ui->actionStopCamera->setEnabled(false);\n ui->captureWidget->setEnabled(false);\n ui->actionSettings->setEnabled(false);\n }\n}\n\nvoid Camera::updateRecorderState(QMediaRecorder::State state)\n{\n switch (state) {\n case QMediaRecorder::StoppedState:\n ui->recordButton->setEnabled(true);\n ui->pauseButton->setEnabled(true);\n ui->stopButton->setEnabled(false);\n break;\n case QMediaRecorder::PausedState:\n ui->recordButton->setEnabled(true);\n ui->pauseButton->setEnabled(false);\n ui->stopButton->setEnabled(true);\n break;\n case QMediaRecorder::RecordingState:\n ui->recordButton->setEnabled(false);\n ui->pauseButton->setEnabled(true);\n ui->stopButton->setEnabled(true);\n break;\n }\n}\n\nvoid Camera::setExposureCompensation(int index)\n{\n camera->exposure()->setExposureCompensation(index*0.5);\n}\n\nvoid Camera::displayRecorderError()\n{\n QMessageBox::warning(this, tr(\"Capture error\"), mediaRecorder->errorString());\n}\n\nvoid Camera::displayCameraError()\n{\n QMessageBox::warning(this, tr(\"Camera error\"), camera->errorString());\n}\n\nvoid Camera::updateCameraDevice(QAction *action)\n{\n setCamera(action->data().toByteArray());\n}\n\nvoid Camera::displayViewfinder()\n{\n ui->stackedWidget->setCurrentIndex(0);\n}\n\nvoid Camera::displayCapturedImage()\n{\n ui->stackedWidget->setCurrentIndex(1);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"gpu_surface_gl.h\"\n\n#if OS_IOS\n#include \n#include \n#elif OS_MACOSX\n#include \n#else\n#include \n#include \n#endif\n\n#include \"flutter\/glue\/trace_event.h\"\n#include \"lib\/fxl\/arraysize.h\"\n#include \"lib\/fxl\/logging.h\"\n#include \"third_party\/skia\/include\/core\/SkColorFilter.h\"\n#include \"third_party\/skia\/include\/core\/SkSurface.h\"\n#include \"third_party\/skia\/include\/gpu\/GrBackendSurface.h\"\n#include \"third_party\/skia\/include\/gpu\/GrContextOptions.h\"\n#include \"third_party\/skia\/include\/gpu\/gl\/GrGLInterface.h\"\n\nnamespace shell {\n\n\/\/ Default maximum number of budgeted resources in the cache.\nstatic const int kGrCacheMaxCount = 8192;\n\n\/\/ Default maximum number of bytes of GPU memory of budgeted resources in the\n\/\/ cache.\nstatic const size_t kGrCacheMaxByteSize = 512 * (1 << 20);\n\nGPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate)\n : delegate_(delegate), weak_factory_(this) {\n if (!delegate_->GLContextMakeCurrent()) {\n FXL_LOG(ERROR)\n << \"Could not make the context current to setup the gr context.\";\n return;\n }\n\n GrContextOptions options;\n options.fAvoidStencilBuffers = true;\n\n auto context = GrContext::MakeGL(GrGLMakeNativeInterface(), options);\n\n if (context == nullptr) {\n FXL_LOG(ERROR) << \"Failed to setup Skia Gr context.\";\n return;\n }\n\n context_ = std::move(context);\n\n context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize);\n\n delegate_->GLContextClearCurrent();\n\n valid_ = true;\n}\n\nGPUSurfaceGL::~GPUSurfaceGL() {\n if (!valid_) {\n return;\n }\n\n if (!delegate_->GLContextMakeCurrent()) {\n FXL_LOG(ERROR) << \"Could not make the context current to destroy the \"\n \"GrContext resources.\";\n return;\n }\n\n onscreen_surface_ = nullptr;\n context_->releaseResourcesAndAbandonContext();\n context_ = nullptr;\n\n delegate_->GLContextClearCurrent();\n}\n\nbool GPUSurfaceGL::IsValid() {\n return valid_;\n}\n\nstatic SkColorType FirstSupportedColorType(GrContext* context, GLenum* format) {\n#define RETURN_IF_RENDERABLE(x, y) \\\n if (context->colorTypeSupportedAsSurface((x))) { \\\n *format = (y); \\\n return (x); \\\n }\n#if OS_MACOSX\n RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8);\n#else\n RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8_OES);\n#endif\n RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GL_RGBA4);\n RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GL_RGB565);\n return kUnknown_SkColorType;\n}\n\nstatic sk_sp WrapOnscreenSurface(GrContext* context,\n const SkISize& size,\n intptr_t fbo) {\n\n GLenum format;\n const SkColorType color_type = FirstSupportedColorType(context, &format);\n\n const GrGLFramebufferInfo framebuffer_info = {\n .fFBOID = static_cast(fbo),\n .fFormat = format,\n };\n\n\n GrBackendRenderTarget render_target(size.fWidth, \/\/ width\n size.fHeight, \/\/ height\n 0, \/\/ sample count\n 0, \/\/ stencil bits (TODO)\n framebuffer_info \/\/ framebuffer info\n );\n\n sk_sp colorspace = nullptr;\n\n SkSurfaceProps surface_props(\n SkSurfaceProps::InitType::kLegacyFontHost_InitType);\n\n return SkSurface::MakeFromBackendRenderTarget(\n context, \/\/ gr context\n render_target, \/\/ render target\n GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, \/\/ origin\n color_type, \/\/ color type\n colorspace, \/\/ colorspace\n &surface_props \/\/ surface properties\n );\n}\n\nstatic sk_sp CreateOffscreenSurface(GrContext* context,\n const SkISize& size) {\n const SkImageInfo image_info =\n SkImageInfo::MakeN32(size.fWidth, size.fHeight, kOpaque_SkAlphaType);\n\n const SkSurfaceProps surface_props(\n SkSurfaceProps::InitType::kLegacyFontHost_InitType);\n\n return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, image_info, 0,\n kBottomLeft_GrSurfaceOrigin,\n &surface_props);\n}\n\nbool GPUSurfaceGL::CreateOrUpdateSurfaces(const SkISize& size) {\n if (onscreen_surface_ != nullptr &&\n size == SkISize::Make(onscreen_surface_->width(),\n onscreen_surface_->height())) {\n \/\/ Surface size appears unchanged. So bail.\n return true;\n }\n\n \/\/ We need to do some updates.\n TRACE_EVENT0(\"flutter\", \"UpdateSurfacesSize\");\n\n \/\/ Either way, we need to get rid of previous surface.\n onscreen_surface_ = nullptr;\n offscreen_surface_ = nullptr;\n\n if (size.isEmpty()) {\n FXL_LOG(ERROR) << \"Cannot create surfaces of empty size.\";\n return false;\n }\n\n sk_sp onscreen_surface, offscreen_surface;\n\n onscreen_surface =\n WrapOnscreenSurface(context_.get(), size, delegate_->GLContextFBO());\n\n if (onscreen_surface == nullptr) {\n \/\/ If the onscreen surface could not be wrapped. There is absolutely no\n \/\/ point in moving forward.\n FXL_LOG(ERROR) << \"Could not wrap onscreen surface.\";\n return false;\n }\n\n if (delegate_->UseOffscreenSurface()) {\n offscreen_surface = CreateOffscreenSurface(context_.get(), size);\n if (offscreen_surface == nullptr) {\n FXL_LOG(ERROR) << \"Could not create offscreen surface.\";\n return false;\n }\n }\n\n onscreen_surface_ = std::move(onscreen_surface);\n offscreen_surface_ = std::move(offscreen_surface);\n\n return true;\n}\n\nstd::unique_ptr GPUSurfaceGL::AcquireFrame(const SkISize& size) {\n if (delegate_ == nullptr) {\n return nullptr;\n }\n\n if (!delegate_->GLContextMakeCurrent()) {\n FXL_LOG(ERROR)\n << \"Could not make the context current to acquire the frame.\";\n return nullptr;\n }\n\n sk_sp surface = AcquireRenderSurface(size);\n\n if (surface == nullptr) {\n return nullptr;\n }\n\n auto weak_this = weak_factory_.GetWeakPtr();\n\n SurfaceFrame::SubmitCallback submit_callback =\n [weak_this](const SurfaceFrame& surface_frame, SkCanvas* canvas) {\n return weak_this ? weak_this->PresentSurface(canvas) : false;\n };\n\n return std::make_unique(surface, submit_callback);\n}\n\nbool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) {\n if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) {\n return false;\n }\n\n if (offscreen_surface_ != nullptr) {\n TRACE_EVENT0(\"flutter\", \"CopyTextureOnscreen\");\n SkPaint paint;\n onscreen_surface_->getCanvas()->drawImage(\n offscreen_surface_->makeImageSnapshot(), 0, 0, &paint);\n }\n\n {\n TRACE_EVENT0(\"flutter\", \"SkCanvas::Flush\");\n onscreen_surface_->getCanvas()->flush();\n }\n\n delegate_->GLContextPresent();\n\n return true;\n}\n\nsk_sp GPUSurfaceGL::AcquireRenderSurface(const SkISize& size) {\n if (!CreateOrUpdateSurfaces(size)) {\n return nullptr;\n }\n\n return offscreen_surface_ != nullptr ? offscreen_surface_ : onscreen_surface_;\n}\n\nGrContext* GPUSurfaceGL::GetContext() {\n return context_.get();\n}\n\n} \/\/ namespace shell\nFix supported color type check on iOS simulators (#4846)\/\/ Copyright 2016 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"gpu_surface_gl.h\"\n\n#if OS_IOS\n#include \n#include \n#elif OS_MACOSX\n#include \n#else\n#include \n#include \n#endif\n\n#include \"flutter\/glue\/trace_event.h\"\n#include \"lib\/fxl\/arraysize.h\"\n#include \"lib\/fxl\/logging.h\"\n#include \"third_party\/skia\/include\/core\/SkColorFilter.h\"\n#include \"third_party\/skia\/include\/core\/SkSurface.h\"\n#include \"third_party\/skia\/include\/gpu\/GrBackendSurface.h\"\n#include \"third_party\/skia\/include\/gpu\/GrContextOptions.h\"\n#include \"third_party\/skia\/include\/gpu\/gl\/GrGLInterface.h\"\n\nnamespace shell {\n\n\/\/ Default maximum number of budgeted resources in the cache.\nstatic const int kGrCacheMaxCount = 8192;\n\n\/\/ Default maximum number of bytes of GPU memory of budgeted resources in the\n\/\/ cache.\nstatic const size_t kGrCacheMaxByteSize = 512 * (1 << 20);\n\nGPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate)\n : delegate_(delegate), weak_factory_(this) {\n if (!delegate_->GLContextMakeCurrent()) {\n FXL_LOG(ERROR)\n << \"Could not make the context current to setup the gr context.\";\n return;\n }\n\n GrContextOptions options;\n options.fAvoidStencilBuffers = true;\n\n auto context = GrContext::MakeGL(GrGLMakeNativeInterface(), options);\n\n if (context == nullptr) {\n FXL_LOG(ERROR) << \"Failed to setup Skia Gr context.\";\n return;\n }\n\n context_ = std::move(context);\n\n context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize);\n\n delegate_->GLContextClearCurrent();\n\n valid_ = true;\n}\n\nGPUSurfaceGL::~GPUSurfaceGL() {\n if (!valid_) {\n return;\n }\n\n if (!delegate_->GLContextMakeCurrent()) {\n FXL_LOG(ERROR) << \"Could not make the context current to destroy the \"\n \"GrContext resources.\";\n return;\n }\n\n onscreen_surface_ = nullptr;\n context_->releaseResourcesAndAbandonContext();\n context_ = nullptr;\n\n delegate_->GLContextClearCurrent();\n}\n\nbool GPUSurfaceGL::IsValid() {\n return valid_;\n}\n\nstatic SkColorType FirstSupportedColorType(GrContext* context, GLenum* format) {\n#define RETURN_IF_RENDERABLE(x, y) \\\n if (context->colorTypeSupportedAsSurface((x))) { \\\n *format = (y); \\\n return (x); \\\n }\n#if OS_MACOSX && !OS_IOS\n RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8);\n#else\n RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8_OES);\n#endif\n RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GL_RGBA4);\n RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GL_RGB565);\n return kUnknown_SkColorType;\n}\n\nstatic sk_sp WrapOnscreenSurface(GrContext* context,\n const SkISize& size,\n intptr_t fbo) {\n\n GLenum format;\n const SkColorType color_type = FirstSupportedColorType(context, &format);\n\n const GrGLFramebufferInfo framebuffer_info = {\n .fFBOID = static_cast(fbo),\n .fFormat = format,\n };\n\n\n GrBackendRenderTarget render_target(size.fWidth, \/\/ width\n size.fHeight, \/\/ height\n 0, \/\/ sample count\n 0, \/\/ stencil bits (TODO)\n framebuffer_info \/\/ framebuffer info\n );\n\n sk_sp colorspace = nullptr;\n\n SkSurfaceProps surface_props(\n SkSurfaceProps::InitType::kLegacyFontHost_InitType);\n\n return SkSurface::MakeFromBackendRenderTarget(\n context, \/\/ gr context\n render_target, \/\/ render target\n GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, \/\/ origin\n color_type, \/\/ color type\n colorspace, \/\/ colorspace\n &surface_props \/\/ surface properties\n );\n}\n\nstatic sk_sp CreateOffscreenSurface(GrContext* context,\n const SkISize& size) {\n const SkImageInfo image_info =\n SkImageInfo::MakeN32(size.fWidth, size.fHeight, kOpaque_SkAlphaType);\n\n const SkSurfaceProps surface_props(\n SkSurfaceProps::InitType::kLegacyFontHost_InitType);\n\n return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, image_info, 0,\n kBottomLeft_GrSurfaceOrigin,\n &surface_props);\n}\n\nbool GPUSurfaceGL::CreateOrUpdateSurfaces(const SkISize& size) {\n if (onscreen_surface_ != nullptr &&\n size == SkISize::Make(onscreen_surface_->width(),\n onscreen_surface_->height())) {\n \/\/ Surface size appears unchanged. So bail.\n return true;\n }\n\n \/\/ We need to do some updates.\n TRACE_EVENT0(\"flutter\", \"UpdateSurfacesSize\");\n\n \/\/ Either way, we need to get rid of previous surface.\n onscreen_surface_ = nullptr;\n offscreen_surface_ = nullptr;\n\n if (size.isEmpty()) {\n FXL_LOG(ERROR) << \"Cannot create surfaces of empty size.\";\n return false;\n }\n\n sk_sp onscreen_surface, offscreen_surface;\n\n onscreen_surface =\n WrapOnscreenSurface(context_.get(), size, delegate_->GLContextFBO());\n\n if (onscreen_surface == nullptr) {\n \/\/ If the onscreen surface could not be wrapped. There is absolutely no\n \/\/ point in moving forward.\n FXL_LOG(ERROR) << \"Could not wrap onscreen surface.\";\n return false;\n }\n\n if (delegate_->UseOffscreenSurface()) {\n offscreen_surface = CreateOffscreenSurface(context_.get(), size);\n if (offscreen_surface == nullptr) {\n FXL_LOG(ERROR) << \"Could not create offscreen surface.\";\n return false;\n }\n }\n\n onscreen_surface_ = std::move(onscreen_surface);\n offscreen_surface_ = std::move(offscreen_surface);\n\n return true;\n}\n\nstd::unique_ptr GPUSurfaceGL::AcquireFrame(const SkISize& size) {\n if (delegate_ == nullptr) {\n return nullptr;\n }\n\n if (!delegate_->GLContextMakeCurrent()) {\n FXL_LOG(ERROR)\n << \"Could not make the context current to acquire the frame.\";\n return nullptr;\n }\n\n sk_sp surface = AcquireRenderSurface(size);\n\n if (surface == nullptr) {\n return nullptr;\n }\n\n auto weak_this = weak_factory_.GetWeakPtr();\n\n SurfaceFrame::SubmitCallback submit_callback =\n [weak_this](const SurfaceFrame& surface_frame, SkCanvas* canvas) {\n return weak_this ? weak_this->PresentSurface(canvas) : false;\n };\n\n return std::make_unique(surface, submit_callback);\n}\n\nbool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) {\n if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) {\n return false;\n }\n\n if (offscreen_surface_ != nullptr) {\n TRACE_EVENT0(\"flutter\", \"CopyTextureOnscreen\");\n SkPaint paint;\n onscreen_surface_->getCanvas()->drawImage(\n offscreen_surface_->makeImageSnapshot(), 0, 0, &paint);\n }\n\n {\n TRACE_EVENT0(\"flutter\", \"SkCanvas::Flush\");\n onscreen_surface_->getCanvas()->flush();\n }\n\n delegate_->GLContextPresent();\n\n return true;\n}\n\nsk_sp GPUSurfaceGL::AcquireRenderSurface(const SkISize& size) {\n if (!CreateOrUpdateSurfaces(size)) {\n return nullptr;\n }\n\n return offscreen_surface_ != nullptr ? offscreen_surface_ : onscreen_surface_;\n}\n\nGrContext* GPUSurfaceGL::GetContext() {\n return context_.get();\n}\n\n} \/\/ namespace shell\n<|endoftext|>"} {"text":"\/*\n * Copyright 2003,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSIDCDefinition: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXSIDCDefinition::XSIDCDefinition(IdentityConstraint* const identityConstraint,\n XSIDCDefinition* const keyIC,\n XSAnnotation* const headAnnot,\n StringList* const stringList,\n XSModel* const xsModel,\n MemoryManager* const manager)\n : XSObject(XSConstants::IDENTITY_CONSTRAINT, xsModel, manager)\n , fIdentityConstraint(identityConstraint)\n , fKey(keyIC)\n , fStringList(stringList)\n , fXSAnnotationList(0)\n{\n if (headAnnot)\n { \n fXSAnnotationList = new (manager) RefVectorOf(1, false, manager);\n\n XSAnnotation* annot = headAnnot;\n do\n {\n fXSAnnotationList->addElement(annot);\n annot = annot->getNext(); \n } while (annot);\n }\n\n}\n\nXSIDCDefinition::~XSIDCDefinition()\n{\n if (fStringList)\n delete fStringList;\n\n \/\/ don't delete fKey - deleted by XSModel\n if (fXSAnnotationList)\n delete fXSAnnotationList;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSIDCDefinition: XSObject virtual methods\n\/\/ ---------------------------------------------------------------------------\nconst XMLCh *XSIDCDefinition::getName() \n{\n return fIdentityConstraint->getIdentityConstraintName();\n}\n\nconst XMLCh *XSIDCDefinition::getNamespace() \n{\n return fXSModel->getURIStringPool()->getValueForId(fIdentityConstraint->getNamespaceURI());\n}\n\nXSNamespaceItem *XSIDCDefinition::getNamespaceItem() \n{\n return fXSModel->getNamespaceItem(getNamespace());\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSIDCDefinition: access methods\n\/\/ ---------------------------------------------------------------------------\nXSIDCDefinition::IC_CATEGORY XSIDCDefinition::getCategory() const\n{\n switch(fIdentityConstraint->getType()) {\n case IdentityConstraint::UNIQUE:\n return IC_UNIQUE;\n case IdentityConstraint::KEY:\n return IC_KEY;\n case IdentityConstraint::KEYREF:\n return IC_KEYREF;\n default:\n \/\/ REVISIT:\n \/\/ should never really get here... IdentityConstraint::Unknown is the other\n \/\/ choice so need a default case for completeness; should issues error?\n return IC_KEY;\n }\n}\n\nconst XMLCh *XSIDCDefinition::getSelectorStr()\n{\n return fIdentityConstraint->getSelector()->getXPath()->getExpression();\n}\n\n\nXSAnnotationList *XSIDCDefinition::getAnnotations()\n{\n return fXSAnnotationList;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\nChange uppercase enums that were conflicting with other products.\/*\n * Copyright 2003,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSIDCDefinition: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXSIDCDefinition::XSIDCDefinition(IdentityConstraint* const identityConstraint,\n XSIDCDefinition* const keyIC,\n XSAnnotation* const headAnnot,\n StringList* const stringList,\n XSModel* const xsModel,\n MemoryManager* const manager)\n : XSObject(XSConstants::IDENTITY_CONSTRAINT, xsModel, manager)\n , fIdentityConstraint(identityConstraint)\n , fKey(keyIC)\n , fStringList(stringList)\n , fXSAnnotationList(0)\n{\n if (headAnnot)\n { \n fXSAnnotationList = new (manager) RefVectorOf(1, false, manager);\n\n XSAnnotation* annot = headAnnot;\n do\n {\n fXSAnnotationList->addElement(annot);\n annot = annot->getNext(); \n } while (annot);\n }\n\n}\n\nXSIDCDefinition::~XSIDCDefinition()\n{\n if (fStringList)\n delete fStringList;\n\n \/\/ don't delete fKey - deleted by XSModel\n if (fXSAnnotationList)\n delete fXSAnnotationList;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSIDCDefinition: XSObject virtual methods\n\/\/ ---------------------------------------------------------------------------\nconst XMLCh *XSIDCDefinition::getName() \n{\n return fIdentityConstraint->getIdentityConstraintName();\n}\n\nconst XMLCh *XSIDCDefinition::getNamespace() \n{\n return fXSModel->getURIStringPool()->getValueForId(fIdentityConstraint->getNamespaceURI());\n}\n\nXSNamespaceItem *XSIDCDefinition::getNamespaceItem() \n{\n return fXSModel->getNamespaceItem(getNamespace());\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XSIDCDefinition: access methods\n\/\/ ---------------------------------------------------------------------------\nXSIDCDefinition::IC_CATEGORY XSIDCDefinition::getCategory() const\n{\n switch(fIdentityConstraint->getType()) {\n case IdentityConstraint::ICType_UNIQUE:\n return IC_UNIQUE;\n case IdentityConstraint::ICType_KEY:\n return IC_KEY;\n case IdentityConstraint::ICType_KEYREF:\n return IC_KEYREF;\n default:\n \/\/ REVISIT:\n \/\/ should never really get here... IdentityConstraint::Unknown is the other\n \/\/ choice so need a default case for completeness; should issues error?\n return IC_KEY;\n }\n}\n\nconst XMLCh *XSIDCDefinition::getSelectorStr()\n{\n return fIdentityConstraint->getSelector()->getXPath()->getExpression();\n}\n\n\nXSAnnotationList *XSIDCDefinition::getAnnotations()\n{\n return fXSAnnotationList;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \n\n#include \"thrift_line\/TalkService.h\"\n\n#include \"constants.hpp\"\n#include \"linehttptransport.hpp\"\n\nLineHttpTransport::LineHttpTransport(\n PurpleAccount *acct,\n PurpleConnection *conn,\n std::string host,\n uint16_t port,\n bool ls_mode) :\n acct(acct),\n conn(conn),\n host(host),\n port(port),\n ls_mode(ls_mode),\n auth_token(\"\"),\n state(ConnectionState::DISCONNECTED),\n auto_reconnect(false),\n reconnect_timeout_handle(0),\n reconnect_timeout(0),\n ssl(NULL),\n input_handle(0),\n connection_id(0),\n request_written(0),\n keep_alive(false),\n status_code_(0),\n content_length_(0)\n{\n}\n\nLineHttpTransport::~LineHttpTransport() {\n close();\n}\n\nvoid LineHttpTransport::set_auto_reconnect(bool auto_reconnect) {\n if (state == ConnectionState::DISCONNECTED)\n this->auto_reconnect = auto_reconnect;\n}\n\nvoid LineHttpTransport::set_auth_token(std::string token) {\n this->auth_token = token;\n}\n\nint LineHttpTransport::status_code() {\n return status_code_;\n}\n\nint LineHttpTransport::content_length() {\n return content_length_;\n}\n\nvoid LineHttpTransport::open() {\n if (state != ConnectionState::DISCONNECTED)\n return;\n\n state = ConnectionState::CONNECTED;\n\n in_progress = false;\n\n connection_id++;\n ssl = purple_ssl_connect(\n acct,\n host.c_str(),\n port,\n WRAPPER(LineHttpTransport::ssl_connect),\n WRAPPER_TYPE(LineHttpTransport::ssl_error, end),\n (gpointer)this);\n}\n\nvoid LineHttpTransport::ssl_connect(PurpleSslConnection *, PurpleInputCondition) {\n reconnect_timeout = 0;\n\n send_next();\n}\n\nvoid LineHttpTransport::ssl_error(PurpleSslConnection *, PurpleSslErrorType err) {\n purple_debug_warning(\"line\", \"SSL error: %s\\n\", purple_ssl_strerror(err));\n\n ssl = nullptr;\n\n purple_connection_ssl_error(conn, err);\n}\n\nvoid LineHttpTransport::close() {\n if (state == ConnectionState::DISCONNECTED)\n return;\n\n state = ConnectionState::DISCONNECTED;\n\n if (reconnect_timeout_handle) {\n purple_timeout_remove(reconnect_timeout_handle);\n reconnect_timeout_handle = 0;\n }\n\n if (input_handle) {\n purple_input_remove(input_handle);\n input_handle = 0;\n }\n\n purple_ssl_close(ssl);\n ssl = NULL;\n connection_id++;\n\n x_ls = \"\";\n\n request_buf.str(\"\");\n\n response_str = \"\";\n response_buf.str(\"\");\n}\n\nuint32_t LineHttpTransport::read_virt(uint8_t *buf, uint32_t len) {\n return (uint32_t )response_buf.sgetn((char *)buf, len);\n}\n\nvoid LineHttpTransport::write_virt(const uint8_t *buf, uint32_t len) {\n request_buf.sputn((const char *)buf, len);\n}\n\nvoid LineHttpTransport::request(std::string method, std::string path, std::string content_type,\n std::function callback)\n{\n Request req;\n req.method = method;\n req.path = path;\n req.content_type = content_type;\n req.body = request_buf.str();\n req.callback = callback;\n request_queue.push(req);\n\n request_buf.str(\"\");\n\n send_next();\n}\n\nvoid LineHttpTransport::send_next() {\n if (state != ConnectionState::CONNECTED) {\n open();\n return;\n }\n\n if (in_progress || request_queue.empty())\n return;\n\n keep_alive = false;\n status_code_ = -1;\n content_length_ = -1;\n\n Request &next_req = request_queue.front();\n\n std::ostringstream data;\n\n data\n << next_req.method << \" \" << next_req.path << \" HTTP\/1.1\" \"\\r\\n\";\n\n if (ls_mode && x_ls != \"\") {\n data << \"X-LS: \" << x_ls << \"\\r\\n\";\n } else {\n data\n << \"Connection: Keep-Alive\\r\\n\"\n << \"Content-Type: \" << next_req.content_type << \"\\r\\n\"\n << \"Host: \" << host << \":\" << port << \"\\r\\n\"\n << \"User-Agent: \" LINE_USER_AGENT \"\\r\\n\"\n << \"X-Line-Application: \" LINE_APPLICATION \"\\r\\n\";\n\n if (auth_token != \"\")\n data << \"X-Line-Access: \" << auth_token << \"\\r\\n\";\n }\n\n if (next_req.method == \"POST\")\n data << \"Content-Length: \" << next_req.body.size() << \"\\r\\n\";\n\n data\n << \"\\r\\n\"\n << next_req.body;\n\n request_data = data.str();\n request_written = 0;\n in_progress = true;\n\n input_handle = purple_input_add(ssl->fd, PURPLE_INPUT_WRITE,\n WRAPPER(LineHttpTransport::ssl_write), (gpointer)this);\n ssl_write(ssl->fd, PURPLE_INPUT_WRITE);\n}\n\nint LineHttpTransport::reconnect_timeout_cb() {\n reconnect_timeout = reconnect_timeout ? 10 : 60;\n\n state = ConnectionState::DISCONNECTED;\n\n open();\n\n return FALSE;\n}\n\nvoid LineHttpTransport::write_request() {\n if (request_written < request_data.size()) {\n size_t r = purple_ssl_write(ssl,\n request_data.c_str() + request_written, request_data.size() - request_written);\n\n request_written += r;\n\n purple_debug_info(\"line\", \"Wrote: %d, %d out of %d!\\n\",\n (int)r, (int)request_written, (int)request_data.size());\n }\n}\n\nvoid LineHttpTransport::ssl_write(gint, PurpleInputCondition) {\n if (state != ConnectionState::CONNECTED) {\n if (input_handle) {\n purple_input_remove(input_handle);\n input_handle = 0;\n }\n\n return;\n }\n\n if (request_written < request_data.size()) {\n request_written += purple_ssl_write(ssl,\n request_data.c_str() + request_written, request_data.size() - request_written);\n }\n\n if (request_written >= request_data.size()) {\n purple_input_remove(input_handle);\n\n input_handle = purple_input_add(ssl->fd, PURPLE_INPUT_READ,\n WRAPPER(LineHttpTransport::ssl_read), (gpointer)this);\n }\n}\n\nvoid LineHttpTransport::ssl_read(gint, PurpleInputCondition) {\n if (state != ConnectionState::CONNECTED) {\n purple_input_remove(input_handle);\n input_handle = 0;\n return;\n }\n\n bool any = false;\n\n while (true) {\n size_t count = purple_ssl_read(ssl, (void *)buf, BUFFER_SIZE);\n\n if (count == 0) {\n if (any)\n break;\n\n purple_debug_info(\"line\", \"Connection lost.\\n\");\n\n close();\n\n if (in_progress) {\n if (auto_reconnect) {\n purple_debug_info(\"line\", \"Reconnecting in %ds...\\n\",\n reconnect_timeout);\n\n state = ConnectionState::RECONNECTING;\n\n purple_timeout_add_seconds(\n reconnect_timeout,\n WRAPPER(LineHttpTransport::reconnect_timeout_cb),\n (gpointer)this);\n } else {\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, \"LINE: Could not connect to server.\");\n }\n }\n\n return;\n }\n\n if (count == (size_t)-1)\n break;\n\n any = true;\n\n response_str.append((const char *)buf, count);\n\n try_parse_response_header();\n\n if (content_length_ >= 0 && response_str.size() >= (size_t)content_length_) {\n purple_input_remove(input_handle);\n\n if (status_code_ == 403) {\n \/\/ Don't try to reconnect because this usually means the user has logged in from\n \/\/ elsewhere.\n\n \/\/ TODO: Check actual reason\n\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, \"Session died.\");\n return;\n }\n\n response_buf.str(response_str.substr(0, content_length_));\n response_str.erase(0, content_length_);\n\n int connection_id_before = connection_id;\n\n try {\n request_queue.front().callback();\n } catch (line::TalkException &err) {\n std::string msg = \"LINE: TalkException: \";\n msg += err.reason;\n\n if (err.code == line::ErrorCode::NOT_AUTHORIZED_DEVICE) {\n purple_account_remove_setting(acct, LINE_ACCOUNT_AUTH_TOKEN);\n\n if (err.reason == \"AUTHENTICATION_DIVESTED_BY_OTHER_DEVICE\") {\n msg = \"LINE: You have been logged out because \"\n \"you logged in from another device.\";\n } else if (err.reason == \"REVOKE\") {\n msg = \"LINE: This device was logged out via the mobile app.\";\n }\n }\n\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, msg.c_str());\n return;\n } catch (apache::thrift::TApplicationException &err) {\n std::string msg = \"LINE: Application error: \";\n msg += err.what();\n\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, msg.c_str());\n return;\n } catch (apache::thrift::transport::TTransportException &err) {\n std::string msg = \"LINE: Transport error: \";\n msg += err.what();\n\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, msg.c_str());\n return;\n }\n\n request_queue.pop();\n\n in_progress = false;\n\n if (connection_id != connection_id_before)\n break; \/\/ Callback closed connection, don't try to continue reading\n\n if (!keep_alive) {\n close();\n send_next();\n break;\n }\n\n send_next();\n }\n }\n}\n\nvoid LineHttpTransport::try_parse_response_header() {\n size_t header_end = response_str.find(\"\\r\\n\\r\\n\");\n if (header_end == std::string::npos)\n return;\n\n std::istringstream stream(response_str.substr(0, header_end));\n\n stream.ignore(256, ' ');\n stream >> status_code_;\n stream.ignore(256, '\\n');\n\n while (stream) {\n std::string name, value;\n\n std::getline(stream, name, ':');\n stream.ignore(256, ' ');\n\n if (name == \"Content-Length\")\n stream >> content_length_;\n\n if (name == \"X-LS\")\n std::getline(stream, x_ls, '\\r');\n\n if (name == \"Connection\") {\n std::string value;\n std::getline(stream, value, '\\r');\n\n if (value == \"Keep-Alive\" || value == \"Keep-alive\" || value == \"keep-alive\")\n keep_alive = true;\n }\n\n stream.ignore(256, '\\n');\n }\n\n response_str.erase(0, header_end + 4);\n}\nReconnect automatically in more error situations.#include \n#include \n\n#include \n\n#include \n\n#include \"thrift_line\/TalkService.h\"\n\n#include \"constants.hpp\"\n#include \"linehttptransport.hpp\"\n\nLineHttpTransport::LineHttpTransport(\n PurpleAccount *acct,\n PurpleConnection *conn,\n std::string host,\n uint16_t port,\n bool ls_mode) :\n acct(acct),\n conn(conn),\n host(host),\n port(port),\n ls_mode(ls_mode),\n auth_token(\"\"),\n state(ConnectionState::DISCONNECTED),\n auto_reconnect(false),\n reconnect_timeout_handle(0),\n reconnect_timeout(0),\n ssl(NULL),\n input_handle(0),\n connection_id(0),\n request_written(0),\n keep_alive(false),\n status_code_(0),\n content_length_(0)\n{\n}\n\nLineHttpTransport::~LineHttpTransport() {\n close();\n}\n\nvoid LineHttpTransport::set_auto_reconnect(bool auto_reconnect) {\n if (state == ConnectionState::DISCONNECTED)\n this->auto_reconnect = auto_reconnect;\n}\n\nvoid LineHttpTransport::set_auth_token(std::string token) {\n this->auth_token = token;\n}\n\nint LineHttpTransport::status_code() {\n return status_code_;\n}\n\nint LineHttpTransport::content_length() {\n return content_length_;\n}\n\nvoid LineHttpTransport::open() {\n if (state != ConnectionState::DISCONNECTED)\n return;\n\n state = ConnectionState::CONNECTED;\n\n in_progress = false;\n\n connection_id++;\n ssl = purple_ssl_connect(\n acct,\n host.c_str(),\n port,\n WRAPPER(LineHttpTransport::ssl_connect),\n WRAPPER_TYPE(LineHttpTransport::ssl_error, end),\n (gpointer)this);\n}\n\nvoid LineHttpTransport::ssl_connect(PurpleSslConnection *, PurpleInputCondition) {\n reconnect_timeout = 0;\n\n send_next();\n}\n\nvoid LineHttpTransport::ssl_error(PurpleSslConnection *, PurpleSslErrorType err) {\n purple_debug_warning(\"line\", \"SSL error: %s\\n\", purple_ssl_strerror(err));\n\n ssl = nullptr;\n\n purple_connection_ssl_error(conn, err);\n}\n\nvoid LineHttpTransport::close() {\n if (state == ConnectionState::DISCONNECTED)\n return;\n\n state = ConnectionState::DISCONNECTED;\n\n if (reconnect_timeout_handle) {\n purple_timeout_remove(reconnect_timeout_handle);\n reconnect_timeout_handle = 0;\n }\n\n if (input_handle) {\n purple_input_remove(input_handle);\n input_handle = 0;\n }\n\n purple_ssl_close(ssl);\n ssl = NULL;\n connection_id++;\n\n x_ls = \"\";\n\n request_buf.str(\"\");\n\n response_str = \"\";\n response_buf.str(\"\");\n}\n\nuint32_t LineHttpTransport::read_virt(uint8_t *buf, uint32_t len) {\n return (uint32_t )response_buf.sgetn((char *)buf, len);\n}\n\nvoid LineHttpTransport::write_virt(const uint8_t *buf, uint32_t len) {\n request_buf.sputn((const char *)buf, len);\n}\n\nvoid LineHttpTransport::request(std::string method, std::string path, std::string content_type,\n std::function callback)\n{\n Request req;\n req.method = method;\n req.path = path;\n req.content_type = content_type;\n req.body = request_buf.str();\n req.callback = callback;\n request_queue.push(req);\n\n request_buf.str(\"\");\n\n send_next();\n}\n\nvoid LineHttpTransport::send_next() {\n if (state != ConnectionState::CONNECTED) {\n open();\n return;\n }\n\n if (in_progress || request_queue.empty())\n return;\n\n keep_alive = false;\n status_code_ = -1;\n content_length_ = -1;\n\n Request &next_req = request_queue.front();\n\n std::ostringstream data;\n\n data\n << next_req.method << \" \" << next_req.path << \" HTTP\/1.1\" \"\\r\\n\";\n\n if (ls_mode && x_ls != \"\") {\n data << \"X-LS: \" << x_ls << \"\\r\\n\";\n } else {\n data\n << \"Connection: Keep-Alive\\r\\n\"\n << \"Content-Type: \" << next_req.content_type << \"\\r\\n\"\n << \"Host: \" << host << \":\" << port << \"\\r\\n\"\n << \"User-Agent: \" LINE_USER_AGENT \"\\r\\n\"\n << \"X-Line-Application: \" LINE_APPLICATION \"\\r\\n\";\n\n if (auth_token != \"\")\n data << \"X-Line-Access: \" << auth_token << \"\\r\\n\";\n }\n\n if (next_req.method == \"POST\")\n data << \"Content-Length: \" << next_req.body.size() << \"\\r\\n\";\n\n data\n << \"\\r\\n\"\n << next_req.body;\n\n request_data = data.str();\n request_written = 0;\n in_progress = true;\n\n input_handle = purple_input_add(ssl->fd, PURPLE_INPUT_WRITE,\n WRAPPER(LineHttpTransport::ssl_write), (gpointer)this);\n ssl_write(ssl->fd, PURPLE_INPUT_WRITE);\n}\n\nint LineHttpTransport::reconnect_timeout_cb() {\n reconnect_timeout = reconnect_timeout ? 10 : 60;\n\n state = ConnectionState::DISCONNECTED;\n\n open();\n\n return FALSE;\n}\n\nvoid LineHttpTransport::write_request() {\n if (request_written < request_data.size()) {\n size_t r = purple_ssl_write(ssl,\n request_data.c_str() + request_written, request_data.size() - request_written);\n\n request_written += r;\n\n purple_debug_info(\"line\", \"Wrote: %d, %d out of %d!\\n\",\n (int)r, (int)request_written, (int)request_data.size());\n }\n}\n\nvoid LineHttpTransport::ssl_write(gint, PurpleInputCondition) {\n if (state != ConnectionState::CONNECTED) {\n if (input_handle) {\n purple_input_remove(input_handle);\n input_handle = 0;\n }\n\n return;\n }\n\n if (request_written < request_data.size()) {\n request_written += purple_ssl_write(ssl,\n request_data.c_str() + request_written, request_data.size() - request_written);\n }\n\n if (request_written >= request_data.size()) {\n purple_input_remove(input_handle);\n\n input_handle = purple_input_add(ssl->fd, PURPLE_INPUT_READ,\n WRAPPER(LineHttpTransport::ssl_read), (gpointer)this);\n }\n}\n\nvoid LineHttpTransport::ssl_read(gint, PurpleInputCondition) {\n if (state != ConnectionState::CONNECTED) {\n purple_input_remove(input_handle);\n input_handle = 0;\n return;\n }\n\n bool any = false;\n\n while (true) {\n size_t count = purple_ssl_read(ssl, (void *)buf, BUFFER_SIZE);\n\n if (count == 0) {\n if (any)\n break;\n\n purple_debug_info(\"line\", \"Connection lost.\\n\");\n\n close();\n\n if (in_progress) {\n if (auto_reconnect) {\n purple_debug_info(\"line\", \"Reconnecting in %ds...\\n\",\n reconnect_timeout);\n\n state = ConnectionState::RECONNECTING;\n\n purple_timeout_add_seconds(\n reconnect_timeout,\n WRAPPER(LineHttpTransport::reconnect_timeout_cb),\n (gpointer)this);\n } else {\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, \"LINE: Could not connect to server.\");\n }\n }\n\n return;\n }\n\n if (count == (size_t)-1)\n break;\n\n any = true;\n\n response_str.append((const char *)buf, count);\n\n try_parse_response_header();\n\n if (content_length_ >= 0 && response_str.size() >= (size_t)content_length_) {\n purple_input_remove(input_handle);\n\n if (status_code_ == 403) {\n \/\/ Don't try to reconnect because this usually means the user has logged in from\n \/\/ elsewhere.\n\n \/\/ TODO: Check actual reason\n\n conn->wants_to_die = TRUE;\n purple_connection_error(conn, \"Session died.\");\n return;\n }\n\n response_buf.str(response_str.substr(0, content_length_));\n response_str.erase(0, content_length_);\n\n int connection_id_before = connection_id;\n\n try {\n request_queue.front().callback();\n } catch (line::TalkException &err) {\n std::string msg = \"LINE: TalkException: \";\n msg += err.reason;\n\n if (err.code == line::ErrorCode::NOT_AUTHORIZED_DEVICE) {\n purple_account_remove_setting(acct, LINE_ACCOUNT_AUTH_TOKEN);\n\n if (err.reason == \"AUTHENTICATION_DIVESTED_BY_OTHER_DEVICE\") {\n msg = \"LINE: You have been logged out because \"\n \"you logged in from another device.\";\n } else if (err.reason == \"REVOKE\") {\n msg = \"LINE: This device was logged out via the mobile app.\";\n }\n\n conn->wants_to_die = TRUE;\n }\n\n purple_connection_error(conn, msg.c_str());\n return;\n } catch (apache::thrift::TApplicationException &err) {\n std::string msg = \"LINE: Application error: \";\n msg += err.what();\n\n purple_connection_error(conn, msg.c_str());\n return;\n } catch (apache::thrift::transport::TTransportException &err) {\n std::string msg = \"LINE: Transport error: \";\n msg += err.what();\n\n purple_connection_error(conn, msg.c_str());\n return;\n }\n\n request_queue.pop();\n\n in_progress = false;\n\n if (connection_id != connection_id_before)\n break; \/\/ Callback closed connection, don't try to continue reading\n\n if (!keep_alive) {\n close();\n send_next();\n break;\n }\n\n send_next();\n }\n }\n}\n\nvoid LineHttpTransport::try_parse_response_header() {\n size_t header_end = response_str.find(\"\\r\\n\\r\\n\");\n if (header_end == std::string::npos)\n return;\n\n std::istringstream stream(response_str.substr(0, header_end));\n\n stream.ignore(256, ' ');\n stream >> status_code_;\n stream.ignore(256, '\\n');\n\n while (stream) {\n std::string name, value;\n\n std::getline(stream, name, ':');\n stream.ignore(256, ' ');\n\n if (name == \"Content-Length\")\n stream >> content_length_;\n\n if (name == \"X-LS\")\n std::getline(stream, x_ls, '\\r');\n\n if (name == \"Connection\") {\n std::string value;\n std::getline(stream, value, '\\r');\n\n if (value == \"Keep-Alive\" || value == \"Keep-alive\" || value == \"keep-alive\")\n keep_alive = true;\n }\n\n stream.ignore(256, '\\n');\n }\n\n response_str.erase(0, header_end + 4);\n}\n<|endoftext|>"} {"text":"\/*! \\file MemoryChecker.cpp\n\t\\date Wednesday March 17, 2010\n\t\\author Gregory Diamos \n\t\\brief The source file for the MemoryChecker class.\n*\/\n\n#ifndef MEMORY_CHECKER_CPP_INCLUDED\n#define MEMORY_CHECKER_CPP_INCLUDED\n\n\/\/ Ocelot includes\n#include \n#include \n#include \n#include \n\n\/\/ hydrazine includes\n#include \n\nnamespace trace\n{\n\tMemoryChecker::Allocation::Allocation( bool v, ir::PTXU64 b, ir::PTXU64 e )\n\t\t: valid( v ), base( b ), extent( e )\n\t{\n\t\n\t}\n\t\n\tstatic std::string prefix( unsigned int thread, const ir::Dim3& dim, \n\t\tconst TraceEvent& e )\n\t{\n\t\tconst unsigned int cta = e.blockId.x + e.blockId.y * dim.x \n\t\t\t+ dim.x * dim.y * e.blockId.z;\n\t\t\n\t\tstd::stringstream stream;\n\t\tstream << \"[PC \" << e.PC << \"] \";\n\t\tstream << \"[thread \" << thread << \"] \";\n\t\tstream << \"[cta \" << cta << \"] \";\n\t\tstream << e.instruction->toString() << \" - \";\n\t\t\n\t\treturn stream.str();\n\t}\n\t\n\tstatic void alignmentError( const executive::EmulatedKernel* kernel, \n\t\tconst ir::Dim3& dim, const TraceEvent& e, unsigned int thread, \n\t\tir::PTXU64 address, unsigned int size )\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << prefix( thread, dim, e );\n\t\tstream << \"Memory access \" << (void*)address \n\t\t\t<< \" is not aligned to the access size ( \" << size << \" bytes )\";\n\t\tstream << \"\\n\";\n\t\tstream << \"Near \" << kernel->location( e.PC ) << \"\\n\";\n\t\tthrow hydrazine::Exception( stream.str() );\n\t}\n\t\n\ttemplate< unsigned int size >\n\tstatic void checkAlignment( const executive::EmulatedKernel* kernel, \n\t\tconst ir::Dim3& dim, const TraceEvent& e )\n\t{\n\t\tTraceEvent::U64Vector::const_iterator \n\t\t\taddress = e.memory_addresses.begin();\n\t\tunsigned int threads = e.active.size();\n\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t{\n\t\t\tif( !e.active[ thread ] ) continue;\n\t\t\tif( *address & ( size - 1 ) )\n\t\t\t{\n\t\t\t\talignmentError( kernel, dim, e, thread, *address, size );\n\t\t\t}\n\t\t\t++address;\n\t\t}\n\t}\n\t\n\tvoid MemoryChecker::_checkAlignment( const TraceEvent& e )\n\t{\t\t\n\t\tswitch(e.memory_size)\n\t\t{\n\t\t\tcase 1: return;\n\t\t\tcase 2: checkAlignment< 2 >( _kernel, _dim, e ); break;\n\t\t\tcase 4: checkAlignment< 4 >( _kernel, _dim, e ); break;\n\t\t\tcase 8: checkAlignment< 8 >( _kernel, _dim, e ); break;\n\t\t\tcase 16: checkAlignment< 16 >( _kernel, _dim, e ); break;\n\t\t\tcase 32: checkAlignment< 32 >( _kernel, _dim, e ); break;\n\t\t\tdefault: break;\n\t\t}\n\t}\n\n\tstatic void memoryError( const std::string& space, const ir::Dim3& dim, \n\t\tunsigned int thread, ir::PTXU64 address, unsigned int size, \n\t\tconst TraceEvent& e, const executive::EmulatedKernel* kernel, \n\t\tconst MemoryChecker::Allocation& allocation )\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << prefix( thread, dim, e );\n\t\tstream << space << \" memory access \" << (void*) address \n\t\t\t<< \" (\" << size << \" bytes) is beyond allocated block size \" \n\t\t\t<< allocation.extent;\n\t\tstream << \"\\n\";\n\t\tstream << \"Near \" << kernel->location( e.PC ) << \"\\n\";\n\t\tthrow hydrazine::Exception( stream.str() );\n\t}\n\n\tstatic void globalMemoryError(const executive::Device* device, \n\t\tconst ir::Dim3& dim, unsigned int thread, ir::PTXU64 address, \n\t\tunsigned int size, const TraceEvent& event, \n\t\tconst executive::EmulatedKernel* kernel)\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << prefix( thread, dim, event );\n\t\tstream << \"Global memory access \" << (void*)address \n\t\t\t<< \" is not within any allocated or mapped range.\\n\\n\";\n\t\tstream << \"Nearby Device Allocations\\n\";\n\t\tstream << device->nearbyAllocationsToString( (void*)address );\n\t\tstream << \"\\n\";\n\t\tstream << \"Near \" << kernel->location( event.PC ) << \"\\n\";\n\t\tthrow hydrazine::Exception( stream.str() );\n\t}\n\n\tstatic void checkLocalAccess( const std::string& space, const ir::Dim3& dim,\n\t\tconst MemoryChecker::Allocation& allocation, const TraceEvent& event, \n\t\tconst executive::EmulatedKernel* kernel )\n\t{\n\t\tTraceEvent::U64Vector::const_iterator \n\t\t\taddress = event.memory_addresses.begin();\n\n\t\tunsigned int threads = event.active.size();\n\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t{\n\t\t\tif( !event.active[ thread ] ) continue;\n\t\t\tif( allocation.base > *address \n\t\t\t\t|| *address >= allocation.base + allocation.extent )\n\t\t\t{\n\t\t\t\tmemoryError( space, dim, thread, \n\t\t\t\t\t*address, event.memory_size, event, kernel, allocation );\n\t\t\t}\n\t\t\t++address;\n\t\t}\n\t}\n\n\tvoid MemoryChecker::_checkValidity( const TraceEvent& e )\n\t{\n\t\tswitch( e.instruction->addressSpace )\n\t\t{\n\t\t\tcase ir::PTXInstruction::Global:\n\t\t\t{\n\t\t\t\tTraceEvent::U64Vector::const_iterator \n\t\t\t\t\taddress = e.memory_addresses.begin();\n\n\t\t\t\tunsigned int threads = e.active.size();\n\t\t\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t\t\t{\n\t\t\t\t\tif( !e.active[ thread ] ) continue;\n\t\t\t\t\tif( _cache.base > *address \n\t\t\t\t\t\t|| *address >= _cache.base + _cache.extent\n\t\t\t\t\t\t|| !_cache.valid )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst executive::Device::MemoryAllocation* allocation = \n\t\t\t\t\t\t\t_device->getMemoryAllocation( (void*)*address, \n\t\t\t\t\t\t\t\texecutive::Device::AnyAllocation );\n\t\t\t\t\t\tif( allocation == 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tglobalMemoryError( _device, _dim,\n\t\t\t\t\t\t\t\tthread, *address, e.memory_size, e, _kernel );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_cache.base = ( ir::PTXU64 ) allocation->pointer();\n\t\t\t\t\t\t_cache.extent = allocation->size();\n\t\t\t\t\t\tif( *address >= _cache.base + _cache.extent )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tglobalMemoryError( _device, _dim,\n\t\t\t\t\t\t\t\tthread, *address, e.memory_size, e, _kernel );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t++address;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ir::PTXInstruction::Local: checkLocalAccess( \"Local\", _dim,\n\t\t\t\t_local, e, _kernel ); break;\n\t\t\tcase ir::PTXInstruction::Param: checkLocalAccess( \"Parameter\", _dim, \n\t\t\t\t_parameter, e, _kernel ); break;\n\t\t\tcase ir::PTXInstruction::Shared: checkLocalAccess( \"Shared\", _dim, \t\n\t\t\t\t_shared, e, _kernel ); break;\n\t\t\tcase ir::PTXInstruction::Const: checkLocalAccess( \"Constant\", _dim, \n\t\t\t\t_constant, e, _kernel ); break;\n\t\t\tdefault: break;\n\t\t}\n\t}\n\t\n\tvoid MemoryChecker::_checkInitialized( const TraceEvent& e )\n\t{\n\t\t\/\/ TODO: implement this\n\t}\n\t\n\tMemoryChecker::MemoryChecker() : _cache( false ), _parameter( true ), \n\t\t_shared( true ), _local( true ), _constant( true )\n\t{\n\t\n\t}\t\n\t\n\tvoid MemoryChecker::initialize( const executive::ExecutableKernel& kernel )\n\t{\n\t\t_dim = kernel.blockDim();\n\t\n\t\t_device = kernel.device;\n\t\t\n\t\t_cache.valid = false;\n\n\t\t_parameter.base = 0;\n\t\t_parameter.extent = kernel.parameterMemorySize();\n\n\t\t_constant.base = 0;\n\t\t_constant.extent = kernel.constMemorySize();\n\t\t\n\t\t_shared.base = 0;\n\t\t_shared.extent = kernel.totalSharedMemorySize();\n\t\t\n\t\t_local.base = 0;\n\t\t_local.extent = kernel.localMemorySize();\n\t\t\n\t\t_kernel = static_cast< const executive::EmulatedKernel* >( &kernel );\n\t}\n\n\tvoid MemoryChecker::event(const TraceEvent& event)\n\t{\n\t\tconst bool isMemoryOperation = \n\t\t\tevent.instruction->opcode == ir::PTXInstruction::Ld\n\t\t\t|| event.instruction->opcode == ir::PTXInstruction::St\n\t\t\t|| event.instruction->opcode == ir::PTXInstruction::Atom;\n\t\t\n\t\tif( !isMemoryOperation ) return;\n\t\t\n\t\t_checkAlignment( event );\n\t\t_checkValidity( event );\n\t\t_checkInitialized( event );\n\t}\n\t\n\tvoid MemoryChecker::finish()\n\t{\n\n\t}\n}\n\n#endif\n\nBUG: Memory checker should ignore the top 32-bits of shared accesses. These are actually application bugs, but we are not treating them as such until 2.x\/*! \\file MemoryChecker.cpp\n\t\\date Wednesday March 17, 2010\n\t\\author Gregory Diamos \n\t\\brief The source file for the MemoryChecker class.\n*\/\n\n#ifndef MEMORY_CHECKER_CPP_INCLUDED\n#define MEMORY_CHECKER_CPP_INCLUDED\n\n\/\/ Ocelot includes\n#include \n#include \n#include \n#include \n\n\/\/ hydrazine includes\n#include \n\nnamespace trace\n{\n\tMemoryChecker::Allocation::Allocation( bool v, ir::PTXU64 b, ir::PTXU64 e )\n\t\t: valid( v ), base( b ), extent( e )\n\t{\n\t\n\t}\n\t\n\tstatic std::string prefix( unsigned int thread, const ir::Dim3& dim, \n\t\tconst TraceEvent& e )\n\t{\n\t\tconst unsigned int cta = e.blockId.x + e.blockId.y * dim.x \n\t\t\t+ dim.x * dim.y * e.blockId.z;\n\t\t\n\t\tstd::stringstream stream;\n\t\tstream << \"[PC \" << e.PC << \"] \";\n\t\tstream << \"[thread \" << thread << \"] \";\n\t\tstream << \"[cta \" << cta << \"] \";\n\t\tstream << e.instruction->toString() << \" - \";\n\t\t\n\t\treturn stream.str();\n\t}\n\t\n\tstatic void alignmentError( const executive::EmulatedKernel* kernel, \n\t\tconst ir::Dim3& dim, const TraceEvent& e, unsigned int thread, \n\t\tir::PTXU64 address, unsigned int size )\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << prefix( thread, dim, e );\n\t\tstream << \"Memory access \" << (void*)address \n\t\t\t<< \" is not aligned to the access size ( \" << size << \" bytes )\";\n\t\tstream << \"\\n\";\n\t\tstream << \"Near \" << kernel->location( e.PC ) << \"\\n\";\n\t\tthrow hydrazine::Exception( stream.str() );\n\t}\n\t\n\ttemplate< unsigned int size >\n\tstatic void checkAlignment( const executive::EmulatedKernel* kernel, \n\t\tconst ir::Dim3& dim, const TraceEvent& e )\n\t{\n\t\tTraceEvent::U64Vector::const_iterator \n\t\t\taddress = e.memory_addresses.begin();\n\t\tunsigned int threads = e.active.size();\n\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t{\n\t\t\tif( !e.active[ thread ] ) continue;\n\t\t\tif( *address & ( size - 1 ) )\n\t\t\t{\n\t\t\t\talignmentError( kernel, dim, e, thread, *address, size );\n\t\t\t}\n\t\t\t++address;\n\t\t}\n\t}\n\t\n\tvoid MemoryChecker::_checkAlignment( const TraceEvent& e )\n\t{\t\t\n\t\tswitch(e.memory_size)\n\t\t{\n\t\t\tcase 1: return;\n\t\t\tcase 2: checkAlignment< 2 >( _kernel, _dim, e ); break;\n\t\t\tcase 4: checkAlignment< 4 >( _kernel, _dim, e ); break;\n\t\t\tcase 8: checkAlignment< 8 >( _kernel, _dim, e ); break;\n\t\t\tcase 16: checkAlignment< 16 >( _kernel, _dim, e ); break;\n\t\t\tcase 32: checkAlignment< 32 >( _kernel, _dim, e ); break;\n\t\t\tdefault: break;\n\t\t}\n\t}\n\n\tstatic void memoryError( const std::string& space, const ir::Dim3& dim, \n\t\tunsigned int thread, ir::PTXU64 address, unsigned int size, \n\t\tconst TraceEvent& e, const executive::EmulatedKernel* kernel, \n\t\tconst MemoryChecker::Allocation& allocation )\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << prefix( thread, dim, e );\n\t\tstream << space << \" memory access \" << (void*) address \n\t\t\t<< \" (\" << size << \" bytes) is beyond allocated block size \" \n\t\t\t<< allocation.extent;\n\t\tstream << \"\\n\";\n\t\tstream << \"Near \" << kernel->location( e.PC ) << \"\\n\";\n\t\tthrow hydrazine::Exception( stream.str() );\n\t}\n\n\tstatic void globalMemoryError(const executive::Device* device, \n\t\tconst ir::Dim3& dim, unsigned int thread, ir::PTXU64 address, \n\t\tunsigned int size, const TraceEvent& event, \n\t\tconst executive::EmulatedKernel* kernel)\n\t{\n\t\tstd::stringstream stream;\n\t\tstream << prefix( thread, dim, event );\n\t\tstream << \"Global memory access \" << (void*)address \n\t\t\t<< \" is not within any allocated or mapped range.\\n\\n\";\n\t\tstream << \"Nearby Device Allocations\\n\";\n\t\tstream << device->nearbyAllocationsToString( (void*)address );\n\t\tstream << \"\\n\";\n\t\tstream << \"Near \" << kernel->location( event.PC ) << \"\\n\";\n\t\tthrow hydrazine::Exception( stream.str() );\n\t}\n\n\tstatic void checkLocalAccess( const std::string& space, const ir::Dim3& dim,\n\t\tconst MemoryChecker::Allocation& allocation, const TraceEvent& event, \n\t\tconst executive::EmulatedKernel* kernel )\n\t{\n\t\tTraceEvent::U64Vector::const_iterator \n\t\t\taddress = event.memory_addresses.begin();\n\n\t\tunsigned int threads = event.active.size();\n\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t{\n\t\t\tif( !event.active[ thread ] ) continue;\n\t\t\tif( allocation.base > *address \n\t\t\t\t|| *address >= allocation.base + allocation.extent )\n\t\t\t{\n\t\t\t\tmemoryError( space, dim, thread, \n\t\t\t\t\t*address, event.memory_size, event, kernel, allocation );\n\t\t\t}\n\t\t\t++address;\n\t\t}\n\t}\n\n\tvoid MemoryChecker::_checkValidity( const TraceEvent& e )\n\t{\n\t\tswitch( e.instruction->addressSpace )\n\t\t{\n\t\t\tcase ir::PTXInstruction::Global:\n\t\t\t{\n\t\t\t\tTraceEvent::U64Vector::const_iterator \n\t\t\t\t\taddress = e.memory_addresses.begin();\n\n\t\t\t\tunsigned int threads = e.active.size();\n\t\t\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t\t\t{\n\t\t\t\t\tif( !e.active[ thread ] ) continue;\n\t\t\t\t\tif( _cache.base > *address \n\t\t\t\t\t\t|| *address >= _cache.base + _cache.extent\n\t\t\t\t\t\t|| !_cache.valid )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst executive::Device::MemoryAllocation* allocation = \n\t\t\t\t\t\t\t_device->getMemoryAllocation( (void*)*address, \n\t\t\t\t\t\t\t\texecutive::Device::AnyAllocation );\n\t\t\t\t\t\tif( allocation == 0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tglobalMemoryError( _device, _dim,\n\t\t\t\t\t\t\t\tthread, *address, e.memory_size, e, _kernel );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_cache.base = ( ir::PTXU64 ) allocation->pointer();\n\t\t\t\t\t\t_cache.extent = allocation->size();\n\t\t\t\t\t\tif( *address >= _cache.base + _cache.extent )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tglobalMemoryError( _device, _dim,\n\t\t\t\t\t\t\t\tthread, *address, e.memory_size, e, _kernel );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t++address;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ir::PTXInstruction::Local: checkLocalAccess( \"Local\", _dim,\n\t\t\t\t_local, e, _kernel ); break;\n\t\t\tcase ir::PTXInstruction::Param: checkLocalAccess( \"Parameter\", _dim, \n\t\t\t\t_parameter, e, _kernel ); break;\n\t\t\tcase ir::PTXInstruction::Shared: {\n\t\t\t\tTraceEvent::U64Vector::const_iterator \n\t\t\t\t\taddress = e.memory_addresses.begin();\n\n\t\t\t\tunsigned int threads = e.active.size();\n\t\t\t\tfor( unsigned int thread = 0; thread < threads; ++thread )\n\t\t\t\t{\n\t\t\t\t\tif( !e.active[ thread ] ) continue;\n\t\t\t\t\t\n\t\t\t\t\tir::PTXU64 a = *address & 0xffffffff;\n\t\t\t\t\tif( _shared.base > a \n\t\t\t\t\t\t|| a >= _shared.base + _shared.extent )\n\t\t\t\t\t{\n\t\t\t\t\t\tmemoryError( \"Shared\", _dim, thread, \n\t\t\t\t\t\t\ta, e.memory_size, e, _kernel, _shared );\n\t\t\t\t\t}\n\t\t\t\t\t++address;\n\t\t\t\t}\n\t\t\t}; break;\n\t\t\tcase ir::PTXInstruction::Const: checkLocalAccess( \"Constant\", _dim, \n\t\t\t\t_constant, e, _kernel ); break;\n\t\t\tdefault: break;\n\t\t}\n\t}\n\t\n\tvoid MemoryChecker::_checkInitialized( const TraceEvent& e )\n\t{\n\t\t\/\/ TODO: implement this\n\t}\n\t\n\tMemoryChecker::MemoryChecker() : _cache( false ), _parameter( true ), \n\t\t_shared( true ), _local( true ), _constant( true )\n\t{\n\t\n\t}\t\n\t\n\tvoid MemoryChecker::initialize( const executive::ExecutableKernel& kernel )\n\t{\n\t\t_dim = kernel.blockDim();\n\t\n\t\t_device = kernel.device;\n\t\t\n\t\t_cache.valid = false;\n\n\t\t_parameter.base = 0;\n\t\t_parameter.extent = kernel.parameterMemorySize();\n\n\t\t_constant.base = 0;\n\t\t_constant.extent = kernel.constMemorySize();\n\t\t\n\t\t_shared.base = 0;\n\t\t_shared.extent = kernel.totalSharedMemorySize();\n\t\t\n\t\t_local.base = 0;\n\t\t_local.extent = kernel.localMemorySize();\n\t\t\n\t\t_kernel = static_cast< const executive::EmulatedKernel* >( &kernel );\n\t}\n\n\tvoid MemoryChecker::event(const TraceEvent& event)\n\t{\n\t\tconst bool isMemoryOperation = \n\t\t\tevent.instruction->opcode == ir::PTXInstruction::Ld\n\t\t\t|| event.instruction->opcode == ir::PTXInstruction::St\n\t\t\t|| event.instruction->opcode == ir::PTXInstruction::Atom;\n\t\t\n\t\tif( !isMemoryOperation ) return;\n\t\t\n\t\t_checkAlignment( event );\n\t\t_checkValidity( event );\n\t\t_checkInitialized( event );\n\t}\n\t\n\tvoid MemoryChecker::finish()\n\t{\n\n\t}\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/* Copyright 2021 David M. Rogers\n *\n * This file is part of Alpaka.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n\/\/#############################################################################\nclass ShflSingleThreadWarpTestKernel\n{\npublic:\n \/\/-------------------------------------------------------------------------\n ALPAKA_NO_HOST_ACC_WARNING\n template\n ALPAKA_FN_ACC auto operator()(TAcc const& acc, bool* success) const -> void\n {\n std::int32_t const warpExtent = alpaka::warp::getSize(acc);\n ALPAKA_CHECK(*success, warpExtent == 1);\n\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 12, 0) == 12);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 42, -1) == 42);\n float ans = alpaka::warp::shfl(acc, 3.3f, 0);\n ALPAKA_CHECK(*success, alpaka::math::abs(acc, ans - 3.3f) < 1e-8f);\n }\n};\n\n\/\/#############################################################################\nclass ShflMultipleThreadWarpTestKernel\n{\npublic:\n \/\/-----------------------------------------------------------------------------\n ALPAKA_NO_HOST_ACC_WARNING\n template\n ALPAKA_FN_ACC auto operator()(TAcc const& acc, bool* success) const -> void\n {\n auto const localThreadIdx = alpaka::getIdx(acc);\n auto const blockExtent = alpaka::getWorkDiv(acc);\n std::int32_t const warpExtent = alpaka::warp::getSize(acc);\n \/\/ Test relies on having a single warp per thread block\n ALPAKA_CHECK(*success, static_cast(blockExtent.prod()) == warpExtent);\n auto const threadIdxInWarp = std::int32_t(alpaka::mapIdx<1u>(localThreadIdx, blockExtent)[0]);\n\n ALPAKA_CHECK(*success, warpExtent > 1);\n\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 42, 0) == 42);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, 0) == 0);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, 1) == 1);\n \/\/ Note the CUDA and HIP API-s differ on lane wrapping, but both agree it should not segfault\n \/\/ https:\/\/github.com\/ROCm-Developer-Tools\/HIP-CPU\/issues\/14\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 5, -1) == 5);\n\n \/\/ Test various widths\n for(int width = 1; width < warpExtent; width *= 2)\n {\n for(int idx = 0; idx < width; idx++)\n {\n int off = width * (threadIdxInWarp \/ width);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, idx, width) == idx + off);\n float ans = alpaka::warp::shfl(acc, 4.0f - float(threadIdxInWarp), idx, width);\n float expect = 4.0f - float(idx + off);\n ALPAKA_CHECK(*success, alpaka::math::abs(acc, ans - expect) < 1e-8f);\n }\n }\n\n \/\/ Some threads quit the kernel to test that the warp operations\n \/\/ properly operate on the active threads only\n if(threadIdxInWarp >= warpExtent \/ 2)\n return;\n\n for(int idx = 0; idx < warpExtent \/ 2; idx++)\n {\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, idx) == idx);\n float ans = alpaka::warp::shfl(acc, 4.0f - float(threadIdxInWarp), idx);\n float expect = 4.0f - float(idx);\n ALPAKA_CHECK(*success, alpaka::math::abs(acc, ans - expect) < 1e-8f);\n }\n }\n};\n\n\/\/-----------------------------------------------------------------------------\nTEMPLATE_LIST_TEST_CASE(\"shfl\", \"[warp]\", alpaka::test::TestAccs)\n{\n using Acc = TestType;\n using Dev = alpaka::Dev;\n using Pltf = alpaka::Pltf;\n using Dim = alpaka::Dim;\n using Idx = alpaka::Idx;\n\n Dev const dev(alpaka::getDevByIdx(0u));\n auto const warpExtent = alpaka::getWarpSize(dev);\n if(warpExtent == 1)\n {\n Idx const gridThreadExtentPerDim = 4;\n alpaka::test::KernelExecutionFixture fixture(alpaka::Vec::all(gridThreadExtentPerDim));\n ShflSingleThreadWarpTestKernel kernel;\n REQUIRE(fixture(kernel));\n }\n else\n {\n \/\/ Work around gcc 7.5 trying and failing to offload for OpenMP 4.0\n#if BOOST_COMP_GNUC && (BOOST_COMP_GNUC == BOOST_VERSION_NUMBER(7, 5, 0)) && defined ALPAKA_ACC_ANY_BT_OMP5_ENABLED\n return;\n#else\n using ExecutionFixture = alpaka::test::KernelExecutionFixture;\n auto const gridBlockExtent = alpaka::Vec::all(2);\n \/\/ Enforce one warp per thread block\n auto blockThreadExtent = alpaka::Vec::ones();\n blockThreadExtent[0] = static_cast(warpExtent);\n auto const threadElementExtent = alpaka::Vec::ones();\n auto workDiv = typename ExecutionFixture::WorkDiv{gridBlockExtent, blockThreadExtent, threadElementExtent};\n auto fixture = ExecutionFixture{workDiv};\n ShflMultipleThreadWarpTestKernel kernel;\n REQUIRE(fixture(kernel));\n#endif\n }\n}\nremove magic number\/* Copyright 2021 David M. Rogers\n *\n * This file is part of Alpaka.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n\/\/#############################################################################\nclass ShflSingleThreadWarpTestKernel\n{\npublic:\n \/\/-------------------------------------------------------------------------\n ALPAKA_NO_HOST_ACC_WARNING\n template\n ALPAKA_FN_ACC auto operator()(TAcc const& acc, bool* success) const -> void\n {\n std::int32_t const warpExtent = alpaka::warp::getSize(acc);\n ALPAKA_CHECK(*success, warpExtent == 1);\n\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 12, 0) == 12);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 42, -1) == 42);\n float ans = alpaka::warp::shfl(acc, 3.3f, 0);\n ALPAKA_CHECK(*success, alpaka::math::abs(acc, ans - 3.3f) < 1e-8f);\n }\n};\n\n\/\/#############################################################################\nclass ShflMultipleThreadWarpTestKernel\n{\npublic:\n \/\/-----------------------------------------------------------------------------\n ALPAKA_NO_HOST_ACC_WARNING\n template\n ALPAKA_FN_ACC auto operator()(TAcc const& acc, bool* success) const -> void\n {\n auto const localThreadIdx = alpaka::getIdx(acc);\n auto const blockExtent = alpaka::getWorkDiv(acc);\n std::int32_t const warpExtent = alpaka::warp::getSize(acc);\n \/\/ Test relies on having a single warp per thread block\n ALPAKA_CHECK(*success, static_cast(blockExtent.prod()) == warpExtent);\n auto const threadIdxInWarp = std::int32_t(alpaka::mapIdx<1u>(localThreadIdx, blockExtent)[0]);\n\n ALPAKA_CHECK(*success, warpExtent > 1);\n\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 42, 0) == 42);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, 0) == 0);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, 1) == 1);\n \/\/ Note the CUDA and HIP API-s differ on lane wrapping, but both agree it should not segfault\n \/\/ https:\/\/github.com\/ROCm-Developer-Tools\/HIP-CPU\/issues\/14\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, 5, -1) == 5);\n\n auto const epsilon = std::numeric_limits::epsilon();\n\n \/\/ Test various widths\n for(int width = 1; width < warpExtent; width *= 2)\n {\n for(int idx = 0; idx < width; idx++)\n {\n int const off = width * (threadIdxInWarp \/ width);\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, idx, width) == idx + off);\n float const ans = alpaka::warp::shfl(acc, 4.0f - float(threadIdxInWarp), idx, width);\n float const expect = 4.0f - float(idx + off);\n ALPAKA_CHECK(*success, alpaka::math::abs(acc, ans - expect) < epsilon);\n }\n }\n\n \/\/ Some threads quit the kernel to test that the warp operations\n \/\/ properly operate on the active threads only\n if(threadIdxInWarp >= warpExtent \/ 2)\n return;\n\n for(int idx = 0; idx < warpExtent \/ 2; idx++)\n {\n ALPAKA_CHECK(*success, alpaka::warp::shfl(acc, threadIdxInWarp, idx) == idx);\n float const ans = alpaka::warp::shfl(acc, 4.0f - float(threadIdxInWarp), idx);\n float const expect = 4.0f - float(idx);\n ALPAKA_CHECK(*success, alpaka::math::abs(acc, ans - expect) < epsilon);\n }\n }\n};\n\n\/\/-----------------------------------------------------------------------------\nTEMPLATE_LIST_TEST_CASE(\"shfl\", \"[warp]\", alpaka::test::TestAccs)\n{\n using Acc = TestType;\n using Dev = alpaka::Dev;\n using Pltf = alpaka::Pltf;\n using Dim = alpaka::Dim;\n using Idx = alpaka::Idx;\n\n Dev const dev(alpaka::getDevByIdx(0u));\n auto const warpExtent = alpaka::getWarpSize(dev);\n if(warpExtent == 1)\n {\n Idx const gridThreadExtentPerDim = 4;\n alpaka::test::KernelExecutionFixture fixture(alpaka::Vec::all(gridThreadExtentPerDim));\n ShflSingleThreadWarpTestKernel kernel;\n REQUIRE(fixture(kernel));\n }\n else\n {\n \/\/ Work around gcc 7.5 trying and failing to offload for OpenMP 4.0\n#if BOOST_COMP_GNUC && (BOOST_COMP_GNUC == BOOST_VERSION_NUMBER(7, 5, 0)) && defined ALPAKA_ACC_ANY_BT_OMP5_ENABLED\n return;\n#else\n using ExecutionFixture = alpaka::test::KernelExecutionFixture;\n auto const gridBlockExtent = alpaka::Vec::all(2);\n \/\/ Enforce one warp per thread block\n auto blockThreadExtent = alpaka::Vec::ones();\n blockThreadExtent[0] = static_cast(warpExtent);\n auto const threadElementExtent = alpaka::Vec::ones();\n auto workDiv = typename ExecutionFixture::WorkDiv{gridBlockExtent, blockThreadExtent, threadElementExtent};\n auto fixture = ExecutionFixture{workDiv};\n ShflMultipleThreadWarpTestKernel kernel;\n REQUIRE(fixture(kernel));\n#endif\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by lz on 1\/25\/17.\n\/\/\n\n#include \n#include \n#include \n#include \"test_common.hpp\"\n#include \n#include \n#include \n\nstruct ServerHandler: public c10k::Handler\n{\n std::uint16_t len;\n std::vector buffer;\n virtual void handle_init(const c10k::ConnectionPtr &conn) override\n {\n using namespace std::placeholders;\n using std::static_pointer_cast;\n conn->read_async_then((char*)&len, sizeof(len),\n std::bind(&ServerHandler::read_buffer,\n static_pointer_cast(shared_from_this()), _1, _2, _3));\n }\n\n void read_buffer(const c10k::ConnectionPtr &conn, char *st, char *ed)\n {\n using namespace std::placeholders;\n buffer.reserve(len);\n conn->read_async_then(std::back_inserter(buffer), len,\n std::bind(&ServerHandler::write_back,\n std::static_pointer_cast(shared_from_this()), _1, _2, _3));\n }\n\n void write_back(const c10k::ConnectionPtr &conn, char *st, char *ed)\n {\n using namespace std::placeholders;\n std::vector wrt_buffer;\n wrt_buffer.reserve(2 + len);\n std::copy_n((char *)&len, 2, std::back_inserter(wrt_buffer));\n std::copy(buffer.begin(), buffer.end(), std::back_inserter(wrt_buffer));\n conn->write_async_then(wrt_buffer.begin(), wrt_buffer.end(),\n std::bind(&ServerHandler::close_connection,\n std::static_pointer_cast(shared_from_this()), _1));\n }\n\n void close_connection(const c10k::ConnectionPtr &conn)\n {\n conn->close();\n }\n};\n\nstd::atomic_bool check_ok {true};\nstd::stringstream ss;\n\nstruct ClientHandler: public c10k::Handler\n{\n std::vector gen_data()\n {\n std::vector wrt_buffer;\n std::uint16_t len = std::rand() % 32768;\n wrt_buffer.reserve(2 + len);\n std::copy_n((char *)&len, 2, std::back_inserter(wrt_buffer));\n std::generate_n(std::back_inserter(wrt_buffer), len, []() {\n return std::rand() % 128;;\n });\n return wrt_buffer;\n }\n\n std::vector send_data, recv_data;\n virtual void handle_init(const c10k::ConnectionPtr &conn) override\n {\n using namespace std::placeholders;\n send_data = gen_data();\n conn->write_async(send_data.cbegin(), send_data.cend());\n conn->read_async_then(std::back_inserter(recv_data), send_data.size(),\n std::bind(&ClientHandler::check_data,\n std::static_pointer_cast(shared_from_this()), _1, _2, _3));\n }\n\n void check_data(const c10k::ConnectionPtr &conn, char *st, char *ed)\n {\n bool ok = true;\n ok &= send_data.size() == recv_data.size();\n if (ok)\n for (int i=0; igetFD() << std::endl;\n }\n }\n if (check_ok.load() && !ok) {\n check_ok = ok;\n ss << \"Err!\" << \"Send size=\"<< send_data.size() <<\" recv size=\" << recv_data.size() << std::endl;\n }\n conn->close();\n }\n};\n\nTEST_CASE(\"multiple WorkerThread test\", \"[worker_thread]\")\n{\n using namespace std::chrono_literals;\n using namespace c10k;\n using detail::call_must_ok;\n spdlog::set_level(spdlog::level::debug);\n auto server_logger = spdlog::stdout_color_mt(\"Server\"), client_logger = spdlog::stdout_color_mt(\"Client\");\n detail::WorkerThread worker(400, server_logger);\n\n std::thread server_t {std::ref(worker)};\n static constexpr int TEST_CNT = 600;\n\n std::thread main_t {[&]() {\n INFO(\"Main thread entered\");\n int main_fd = create_socket();\n INFO(\"Main thread created\");\n sockaddr_in addr = create_addr(\"127.0.0.1\", 6503);\n call_must_ok(::bind, \"Bind\", main_fd, (sockaddr*)&addr, sizeof(addr));\n call_must_ok(::listen, \"Listen\", main_fd, 1024);\n INFO(\"Main thread binded\");\n for (int i=0; iinfo(\"new fd created = {}\", new_sock);\n worker.add_new_connection(new_sock);\n }\n call_must_ok(::close, \"close\", main_fd);\n }};\n main_t.detach();\n INFO(\"Main thread detached\");\n cur_sleep_for(1s);\n INFO(\"Start to create clientWorker\");\n\n detail::WorkerThread clientWorker(400, client_logger);\n std::thread client_t {std::ref(clientWorker)};\n INFO(\"ClientWorker created\");\n\n for (int i=0; iTest: Detach server_t\/client_t earlier\/\/\n\/\/ Created by lz on 1\/25\/17.\n\/\/\n\n#include \n#include \n#include \n#include \"test_common.hpp\"\n#include \n#include \n#include \n\nstruct ServerHandler: public c10k::Handler\n{\n std::uint16_t len;\n std::vector buffer;\n virtual void handle_init(const c10k::ConnectionPtr &conn) override\n {\n using namespace std::placeholders;\n using std::static_pointer_cast;\n conn->read_async_then((char*)&len, sizeof(len),\n std::bind(&ServerHandler::read_buffer,\n static_pointer_cast(shared_from_this()), _1, _2, _3));\n }\n\n void read_buffer(const c10k::ConnectionPtr &conn, char *st, char *ed)\n {\n using namespace std::placeholders;\n buffer.reserve(len);\n conn->read_async_then(std::back_inserter(buffer), len,\n std::bind(&ServerHandler::write_back,\n std::static_pointer_cast(shared_from_this()), _1, _2, _3));\n }\n\n void write_back(const c10k::ConnectionPtr &conn, char *st, char *ed)\n {\n using namespace std::placeholders;\n std::vector wrt_buffer;\n wrt_buffer.reserve(2 + len);\n std::copy_n((char *)&len, 2, std::back_inserter(wrt_buffer));\n std::copy(buffer.begin(), buffer.end(), std::back_inserter(wrt_buffer));\n conn->write_async_then(wrt_buffer.begin(), wrt_buffer.end(),\n std::bind(&ServerHandler::close_connection,\n std::static_pointer_cast(shared_from_this()), _1));\n }\n\n void close_connection(const c10k::ConnectionPtr &conn)\n {\n conn->close();\n }\n};\n\nstd::atomic_bool check_ok {true};\nstd::stringstream ss;\n\nstruct ClientHandler: public c10k::Handler\n{\n std::vector gen_data()\n {\n std::vector wrt_buffer;\n std::uint16_t len = std::rand() % 32768;\n wrt_buffer.reserve(2 + len);\n std::copy_n((char *)&len, 2, std::back_inserter(wrt_buffer));\n std::generate_n(std::back_inserter(wrt_buffer), len, []() {\n return std::rand() % 128;;\n });\n return wrt_buffer;\n }\n\n std::vector send_data, recv_data;\n virtual void handle_init(const c10k::ConnectionPtr &conn) override\n {\n using namespace std::placeholders;\n send_data = gen_data();\n conn->write_async(send_data.cbegin(), send_data.cend());\n conn->read_async_then(std::back_inserter(recv_data), send_data.size(),\n std::bind(&ClientHandler::check_data,\n std::static_pointer_cast(shared_from_this()), _1, _2, _3));\n }\n\n void check_data(const c10k::ConnectionPtr &conn, char *st, char *ed)\n {\n bool ok = true;\n ok &= send_data.size() == recv_data.size();\n if (ok)\n for (int i=0; igetFD() << std::endl;\n }\n }\n if (check_ok.load() && !ok) {\n check_ok = ok;\n ss << \"Err!\" << \"Send size=\"<< send_data.size() <<\" recv size=\" << recv_data.size() << std::endl;\n }\n conn->close();\n }\n};\n\nTEST_CASE(\"multiple WorkerThread test\", \"[worker_thread]\")\n{\n using namespace std::chrono_literals;\n using namespace c10k;\n using detail::call_must_ok;\n spdlog::set_level(spdlog::level::debug);\n auto server_logger = spdlog::stdout_color_mt(\"Server\"), client_logger = spdlog::stdout_color_mt(\"Client\");\n detail::WorkerThread worker(400, server_logger);\n\n std::thread server_t {std::ref(worker)};\n static constexpr int TEST_CNT = 600;\n\n std::thread main_t {[&]() {\n INFO(\"Main thread entered\");\n int main_fd = create_socket();\n INFO(\"Main thread created\");\n sockaddr_in addr = create_addr(\"127.0.0.1\", 6503);\n call_must_ok(::bind, \"Bind\", main_fd, (sockaddr*)&addr, sizeof(addr));\n call_must_ok(::listen, \"Listen\", main_fd, 1024);\n INFO(\"Main thread binded\");\n for (int i=0; iinfo(\"new fd created = {}\", new_sock);\n worker.add_new_connection(new_sock);\n }\n call_must_ok(::close, \"close\", main_fd);\n }};\n main_t.detach();\n INFO(\"Main thread detached\");\n cur_sleep_for(1s);\n INFO(\"Start to create clientWorker\");\n\n detail::WorkerThread clientWorker(400, client_logger);\n std::thread client_t {std::ref(clientWorker)};\n INFO(\"ClientWorker created\");\n\n for (int i=0; i"} {"text":"#include \"libyaml_utils.h\"\n#include \"logger.h\"\n\n\/\/ ---------------------------------------------------------------------------------\n\/\/ ------------------------------- libyaml test code -------------------------------\n\/\/ ---------------------------------------------------------------------------------\nnamespace\n{\nbool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode)\n{\n if (reference_character == mode_type::MAP_TYPE)\n {\n if (map_mode)\n {\n *add_to_me = mode_type::KEY_TYPE;\n }\n else\n {\n *add_to_me = mode_type::VALUE_TYPE;\n }\n return !map_mode;\n }\n else if (reference_character == mode_type::SEQUENCE_TYPE)\n {\n *add_to_me = mode_type::SEQUENCE_TYPE;\n }\n else\n {\n *add_to_me = mode_type::UNKNOWN_TYPE;\n }\n\n return map_mode;\n}\n\nvoid addTag(YAML::Node* current_node, yaml_char_t* tag)\n{\n if (tag)\n {\n std::string temp_tag_translator = ((char*)tag);\n\n current_node->SetTag(temp_tag_translator); \n }\n else if(current_node->Tag().empty())\n {\n current_node->SetTag(\"?\");\n }\n}\n\nvoid addToNode\n (YAML::Node* addToMe, YAML::Node* add_me, std::stack* key_stack, \n const mode_type* tracking_current_type, yaml_char_t* tag)\n{\n addTag(add_me, tag);\n if (*tracking_current_type == mode_type::SEQUENCE_TYPE)\n {\n addToMe->push_back(*add_me);\n }\n else if (*tracking_current_type == mode_type::KEY_TYPE)\n {\n key_stack->push(*add_me);\n (*addToMe)[*add_me];\n }\n else if (*tracking_current_type == mode_type::VALUE_TYPE)\n {\n (*addToMe)[key_stack->top()] = *add_me;\n key_stack->pop();\n }\n}\n\nbool endEventAddition\n (std::vector* libyaml_local_output, std::stack* mode_stack, \n std::stack* map_mode_stack, bool map_mode, std::stack* key_stack)\n{\n\n if (libyaml_local_output->size() > 1)\n {\n mode_stack->pop();\n \n if (mode_stack->top() == mode_type::MAP_TYPE)\n {\n map_mode = map_mode_stack->top();\n map_mode_stack->pop();\n }\n mode_type temp_position_info;\n\n positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode);\n\n YAML::Node temp_node = libyaml_local_output->back();\n\n libyaml_local_output->pop_back();\n\n if (temp_node.size() <= 0)\n {\n TEST_PPRINT(\"interesting\\n\");\n }\n\n addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr);\n }\n return map_mode;\n}\n\nvoid restartVariables (std::stack* key_stack, \n std::stack* mode_stack, std::stack* map_mode_stack, \n std::vector* libyaml_local_output, std::vector* libyaml_final_output,\n bool* map_mode, std::map* anchor_map)\n{\n while (!key_stack->empty())\n {\n key_stack->pop();\n }\n\n while (!mode_stack->empty())\n {\n mode_stack->pop();\n }\n mode_stack->push(mode_type::UNKNOWN_TYPE);\n\n while (!map_mode_stack->empty())\n {\n map_mode_stack->pop();\n }\n\n if (!libyaml_local_output->empty())\n {\n libyaml_final_output->push_back(libyaml_local_output->back());\n }\n\n libyaml_local_output->clear();\n\n *map_mode = true;\n\n anchor_map->clear();\n}\n}\n\nstd::vector& libyaml_parsing::parseLibyaml\n (const uint8_t* input, size_t input_size, std::unique_ptr* error_message_container)\n{\n yaml_parser_t parser;\n yaml_event_t event;\n\n std::vector libyaml_local_output;\n\n std::vector* libyaml_final_output = new std::vector;\n\n std::stack key_stack;\n\n std::stack mode_stack;\n\n mode_stack.push(mode_type::UNKNOWN_TYPE);\n\n std::stack map_mode_stack;\n\n bool map_mode = true;\n \n std::map anchor_map;\n\n if (!yaml_parser_initialize(&parser)) \n {\n TEST_PPRINT(\"ERROR: Failed to initialize\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return *libyaml_final_output;\n }\n\n yaml_parser_set_input_string(&parser, input, input_size);\n \n while (true) \n {\n\n YAML::Node new_node;\n\n yaml_event_type_t type;\n\n mode_type tracking_current_type;\n\n if (!yaml_parser_parse(&parser, &event)) \n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Bad parsing\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return *libyaml_final_output;\n }\n type = event.type;\n \n switch (type)\n {\n case YAML_STREAM_END_EVENT:\n\n TEST_PPRINT(\"STR-\\n\");\n\n break;\n case YAML_DOCUMENT_END_EVENT:\n\n TEST_PPRINT(\"DOC-\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break; \n case YAML_DOCUMENT_START_EVENT:\n\n TEST_PPRINT(\"DOC+\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break;\n\n case YAML_MAPPING_END_EVENT:\n\n TEST_PPRINT(\"MAP-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_SEQUENCE_END_EVENT:\n\n TEST_PPRINT(\"SQU-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_MAPPING_START_EVENT:\n\n TEST_PPRINT(\"MAP+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (!mode_stack.empty())\n {\n positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n }\n\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n\n mode_stack.push(mode_type::MAP_TYPE);\n map_mode = true;\n\n if (event.data.mapping_start.anchor)\n {\n TEST_PPRINT(\"ANCH-map+\\n\");\n anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n case YAML_SEQUENCE_START_EVENT:\n\n TEST_PPRINT(\"SQU+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n\n mode_stack.push(mode_type::SEQUENCE_TYPE);\n\n if (event.data.sequence_start.anchor)\n {\n TEST_PPRINT(\"ANCH-squ+\\n\");\n\n anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n\n case YAML_SCALAR_EVENT:\n {\n TEST_PPRINT(\"SCL\\n\");\n\n YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length));\n addTag(&add_me, event.data.scalar.tag);\n\n if (event.data.scalar.anchor)\n {\n TEST_PPRINT(\"ANCH-scl\\n\");\n std::string temp_translator = ((char*)event.data.scalar.anchor);\n \n if (event.data.scalar.value)\n {\n\n TEST_PPRINT(\"value\\n\");\n\n if(event.data.scalar.length != 0)\n {\n anchor_map[temp_translator] = add_me;\n \n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n\n }\n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n else\n {\n TEST_PPRINT(\"empty\\n\");\n if (mode_stack.top() == mode_type::SEQUENCE_TYPE)\n {\n TEST_PPRINT(\"sequence\\n\");\n add_me = YAML::Node(YAML::NodeType::Null);\n\n libyaml_local_output.back().push_back(add_me);\n\n break;\n }\n \n mode_stack.pop();\n\n if (!mode_stack.empty())\n {\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n TEST_PPRINT(\"map\\n\");\n map_mode = map_mode_stack.top();\n map_mode_stack.pop();\n }\n libyaml_local_output.pop_back();\n }\n else\n {\n libyaml_local_output.push_back(YAML::Node());\n }\n }\n }\n }\n else\n {\n TEST_PPRINT(\"normal\\n\");\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (event.data.scalar.length <= 0 && !event.data.scalar.tag && \n event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE)\n {\n TEST_PPRINT(\"Begin from nothing\\n\");\n add_me = YAML::Node();\n }\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n } \n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n\n break;\n }\n case YAML_ALIAS_EVENT:\n {\n\n TEST_PPRINT(\"ALI\\n\");\n\n std::string temp_translator = ((char*) event.data.alias.anchor);\n \n if(anchor_map.find(temp_translator) != anchor_map.end())\n {\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator], \n &key_stack, &tracking_current_type, nullptr);\n }\n else\n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Missing anchor\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return *libyaml_final_output;\n }\n break;\n }\n default: \n break;\n }\n\n yaml_event_delete(&event);\n\n if (type == YAML_STREAM_END_EVENT)\n {\n break;\n }\n\n }\n\n yaml_parser_delete(&parser);\n\n fflush(stdout);\n\n return *libyaml_final_output;\n}edge handle empty key#include \"libyaml_utils.h\"\n#include \"logger.h\"\n\n\/\/ ---------------------------------------------------------------------------------\n\/\/ ------------------------------- libyaml test code -------------------------------\n\/\/ ---------------------------------------------------------------------------------\nnamespace\n{\nbool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode)\n{\n if (reference_character == mode_type::MAP_TYPE)\n {\n if (map_mode)\n {\n *add_to_me = mode_type::KEY_TYPE;\n }\n else\n {\n *add_to_me = mode_type::VALUE_TYPE;\n }\n return !map_mode;\n }\n else if (reference_character == mode_type::SEQUENCE_TYPE)\n {\n *add_to_me = mode_type::SEQUENCE_TYPE;\n }\n else\n {\n *add_to_me = mode_type::UNKNOWN_TYPE;\n }\n\n return map_mode;\n}\n\nvoid addTag(YAML::Node* current_node, yaml_char_t* tag)\n{\n if (tag)\n {\n std::string temp_tag_translator = ((char*)tag);\n\n current_node->SetTag(temp_tag_translator); \n }\n else if(current_node->Tag().empty())\n {\n current_node->SetTag(\"?\");\n }\n}\n\nvoid addToNode\n (YAML::Node* addToMe, YAML::Node* add_me, std::stack* key_stack, \n const mode_type* tracking_current_type, yaml_char_t* tag)\n{\n addTag(add_me, tag);\n \n if (*tracking_current_type == mode_type::SEQUENCE_TYPE)\n {\n TEST_PPRINT(\"squ type\\n\")\n addToMe->push_back(*add_me);\n }\n else if (*tracking_current_type == mode_type::KEY_TYPE)\n {\n TEST_PPRINT(\"key type\\n\")\n key_stack->push(*add_me);\n (*addToMe)[*add_me];\n }\n else if (*tracking_current_type == mode_type::VALUE_TYPE)\n {\n TEST_PPRINT(\"map type\\n\")\n if (!key_stack->empty())\n {\n (*addToMe)[key_stack->top()] = *add_me;\n key_stack->pop();\n }\n }\n else\n {\n TEST_PPRINT(\"? type\\n\")\n }\n}\n\nbool endEventAddition\n (std::vector* libyaml_local_output, std::stack* mode_stack, \n std::stack* map_mode_stack, bool map_mode, std::stack* key_stack)\n{\n\n if (libyaml_local_output->size() > 1)\n {\n mode_stack->pop();\n \n if (mode_stack->top() == mode_type::MAP_TYPE)\n {\n map_mode = map_mode_stack->top();\n map_mode_stack->pop();\n }\n mode_type temp_position_info;\n\n positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode);\n\n YAML::Node temp_node = libyaml_local_output->back();\n\n libyaml_local_output->pop_back();\n\n addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr);\n }\n return map_mode;\n}\n\nvoid restartVariables (std::stack* key_stack, \n std::stack* mode_stack, std::stack* map_mode_stack, \n std::vector* libyaml_local_output, std::vector* libyaml_final_output,\n bool* map_mode, std::map* anchor_map)\n{\n while (!key_stack->empty())\n {\n key_stack->pop();\n }\n\n while (!mode_stack->empty())\n {\n mode_stack->pop();\n }\n mode_stack->push(mode_type::UNKNOWN_TYPE);\n\n while (!map_mode_stack->empty())\n {\n map_mode_stack->pop();\n }\n\n if (!libyaml_local_output->empty())\n {\n libyaml_final_output->push_back(libyaml_local_output->back());\n }\n\n libyaml_local_output->clear();\n\n *map_mode = true;\n\n anchor_map->clear();\n}\n}\n\nstd::vector& libyaml_parsing::parseLibyaml\n (const uint8_t* input, size_t input_size, std::unique_ptr* error_message_container)\n{\n yaml_parser_t parser;\n yaml_event_t event;\n\n std::vector libyaml_local_output;\n\n std::vector* libyaml_final_output = new std::vector;\n\n std::stack key_stack;\n\n std::stack mode_stack;\n\n mode_stack.push(mode_type::UNKNOWN_TYPE);\n\n std::stack map_mode_stack;\n\n bool map_mode = true;\n \n std::map anchor_map;\n\n if (!yaml_parser_initialize(&parser)) \n {\n TEST_PPRINT(\"ERROR: Failed to initialize\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return *libyaml_final_output;\n }\n\n yaml_parser_set_input_string(&parser, input, input_size);\n \n while (true) \n {\n\n YAML::Node new_node;\n\n yaml_event_type_t type;\n\n mode_type tracking_current_type;\n\n if (!yaml_parser_parse(&parser, &event)) \n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Bad parsing\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return *libyaml_final_output;\n }\n type = event.type;\n \n switch (type)\n {\n case YAML_STREAM_END_EVENT:\n\n TEST_PPRINT(\"STR-\\n\");\n\n break;\n case YAML_DOCUMENT_END_EVENT:\n\n TEST_PPRINT(\"DOC-\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break; \n case YAML_DOCUMENT_START_EVENT:\n\n TEST_PPRINT(\"DOC+\\n\");\n\n restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,\n libyaml_final_output, &map_mode, &anchor_map);\n\n break;\n\n case YAML_MAPPING_END_EVENT:\n\n TEST_PPRINT(\"MAP-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_SEQUENCE_END_EVENT:\n\n TEST_PPRINT(\"SQU-\\n\");\n\n map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);\n\n break;\n case YAML_MAPPING_START_EVENT:\n\n TEST_PPRINT(\"MAP+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (!mode_stack.empty())\n {\n positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n }\n\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n\n mode_stack.push(mode_type::MAP_TYPE);\n map_mode = true;\n\n if (event.data.mapping_start.anchor)\n {\n TEST_PPRINT(\"ANCH-map+\\n\");\n anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n case YAML_SEQUENCE_START_EVENT:\n\n TEST_PPRINT(\"SQU+\\n\");\n\n libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence));\n addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);\n\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n map_mode_stack.push(!map_mode);\n }\n\n mode_stack.push(mode_type::SEQUENCE_TYPE);\n\n if (event.data.sequence_start.anchor)\n {\n TEST_PPRINT(\"ANCH-squ+\\n\");\n\n anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back();\n }\n\n break;\n\n case YAML_SCALAR_EVENT:\n {\n TEST_PPRINT(\"SCL\\n\");\n\n YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length));\n addTag(&add_me, event.data.scalar.tag);\n\n if (event.data.scalar.anchor)\n {\n TEST_PPRINT(\"ANCH-scl\\n\");\n std::string temp_translator = ((char*)event.data.scalar.anchor);\n \n if (event.data.scalar.value)\n {\n\n TEST_PPRINT(\"value\\n\");\n\n if(event.data.scalar.length != 0)\n {\n anchor_map[temp_translator] = add_me;\n \n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n\n }\n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n else\n {\n TEST_PPRINT(\"empty\\n\");\n if (mode_stack.top() == mode_type::SEQUENCE_TYPE)\n {\n TEST_PPRINT(\"sequence\\n\");\n add_me = YAML::Node(YAML::NodeType::Null);\n\n libyaml_local_output.back().push_back(add_me);\n\n break;\n }\n \n mode_stack.pop();\n\n if (!mode_stack.empty())\n {\n if (mode_stack.top() == mode_type::MAP_TYPE)\n {\n TEST_PPRINT(\"map\\n\");\n map_mode = map_mode_stack.top();\n map_mode_stack.pop();\n }\n libyaml_local_output.pop_back();\n }\n else\n {\n libyaml_local_output.push_back(YAML::Node());\n }\n }\n }\n }\n else\n {\n TEST_PPRINT(\"normal\\n\");\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n if (event.data.scalar.length <= 0 && !event.data.scalar.tag && \n event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE)\n {\n TEST_PPRINT(\"Begin from nothing\\n\");\n add_me = YAML::Node();\n }\n\n if (libyaml_local_output.empty())\n {\n libyaml_local_output.push_back(add_me);\n } \n else\n {\n addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type, \n event.data.scalar.tag);\n }\n }\n\n break;\n }\n case YAML_ALIAS_EVENT:\n {\n\n TEST_PPRINT(\"ALI\\n\");\n\n std::string temp_translator = ((char*) event.data.alias.anchor);\n \n if(anchor_map.find(temp_translator) != anchor_map.end())\n {\n map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);\n\n addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator], \n &key_stack, &tracking_current_type, nullptr);\n }\n else\n {\n yaml_event_delete(&event);\n\n yaml_parser_delete(&parser);\n\n TEST_PPRINT(\"ERROR: Missing anchor\\n\");\n\n *error_message_container = std::unique_ptr(new std::string(\"ERROR\"));\n\n return *libyaml_final_output;\n }\n break;\n }\n default: \n break;\n }\n\n yaml_event_delete(&event);\n\n if (type == YAML_STREAM_END_EVENT)\n {\n break;\n }\n\n }\n\n yaml_parser_delete(&parser);\n\n fflush(stdout);\n\n return *libyaml_final_output;\n}<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n#include \n\n\/\/ =======================================================================\n\nvoid ImplFillPrnDlgListBox( const Printer* pPrinter,\n ListBox* pBox, PushButton* pPropBtn )\n{\n ImplFreePrnDlgListBox( pBox );\n\n const std::vector& rPrinters = Printer::GetPrinterQueues();\n unsigned int nCount = rPrinters.size();\n if ( nCount )\n {\n for( unsigned int i = 0; i < nCount; i++ )\n pBox->InsertEntry( rPrinters[i] );\n pBox->SelectEntry( pPrinter->GetName() );\n }\n\n pBox->Enable( nCount != 0 );\n pPropBtn->Show( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplFreePrnDlgListBox( ListBox* pBox, sal_Bool bClear )\n{\n if ( bClear )\n pBox->Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgListBoxSelect( ListBox* pBox, PushButton* pPropBtn,\n Printer* pPrinter, Printer* pTempPrinter )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo)\n {\n if ( !pTempPrinter )\n {\n if ( (pPrinter->GetName() == pInfo->GetPrinterName()) &&\n (pPrinter->GetDriverName() == pInfo->GetDriver()) )\n pTempPrinter = new Printer( pPrinter->GetJobSetup() );\n else\n pTempPrinter = new Printer( *pInfo );\n }\n else\n {\n if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) ||\n (pTempPrinter->GetDriverName() != pInfo->GetDriver()) )\n {\n delete pTempPrinter;\n pTempPrinter = new Printer( *pInfo );\n }\n }\n\n pPropBtn->Enable( pTempPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n }\n else\n pPropBtn->Disable();\n }\n else\n pPropBtn->Disable();\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgUpdatePrinter( Printer* pPrinter, Printer* pTempPrinter )\n{\n OUString aPrnName;\n if ( pTempPrinter )\n aPrnName = pTempPrinter->GetName();\n else\n aPrnName = pPrinter->GetName();\n\n if ( ! Printer::GetQueueInfo( aPrnName, false ) )\n {\n if ( pTempPrinter )\n delete pTempPrinter;\n pTempPrinter = new Printer;\n }\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplPrnDlgUpdateQueueInfo( ListBox* pBox, QueueInfo& rInfo )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo )\n rInfo = *pInfo;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPrnDlgAddString( XubString& rStr, const OUString& rAddStr )\n{\n if ( rStr.Len() )\n rStr.AppendAscii( \"; \" );\n rStr += rAddStr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPrnDlgAddResString( XubString& rStr, sal_uInt16 nResId )\n{\n ImplPrnDlgAddString( rStr, SVT_RESSTR(nResId) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nOUString ImplPrnDlgGetStatusText( const QueueInfo& rInfo )\n{\n XubString aStr;\n sal_uLong nStatus = rInfo.GetStatus();\n\n \/\/ Default-Printer\n if ( !rInfo.GetPrinterName().isEmpty() &&\n (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER );\n\n \/\/ Status\n if ( nStatus & QUEUE_STATUS_READY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY );\n if ( nStatus & QUEUE_STATUS_PAUSED )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED );\n if ( nStatus & QUEUE_STATUS_PENDING_DELETION )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING );\n if ( nStatus & QUEUE_STATUS_BUSY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY );\n if ( nStatus & QUEUE_STATUS_INITIALIZING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING );\n if ( nStatus & QUEUE_STATUS_WAITING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING );\n if ( nStatus & QUEUE_STATUS_WARMING_UP )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP );\n if ( nStatus & QUEUE_STATUS_PROCESSING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING );\n if ( nStatus & QUEUE_STATUS_PRINTING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING );\n if ( nStatus & QUEUE_STATUS_OFFLINE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE );\n if ( nStatus & QUEUE_STATUS_ERROR )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR );\n if ( nStatus & QUEUE_STATUS_SERVER_UNKNOWN )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN );\n if ( nStatus & QUEUE_STATUS_PAPER_JAM )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM );\n if ( nStatus & QUEUE_STATUS_PAPER_OUT )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT );\n if ( nStatus & QUEUE_STATUS_MANUAL_FEED )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED );\n if ( nStatus & QUEUE_STATUS_PAPER_PROBLEM )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM );\n if ( nStatus & QUEUE_STATUS_IO_ACTIVE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE );\n if ( nStatus & QUEUE_STATUS_OUTPUT_BIN_FULL )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL );\n if ( nStatus & QUEUE_STATUS_TONER_LOW )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW );\n if ( nStatus & QUEUE_STATUS_NO_TONER )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER );\n if ( nStatus & QUEUE_STATUS_PAGE_PUNT )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT );\n if ( nStatus & QUEUE_STATUS_USER_INTERVENTION )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION );\n if ( nStatus & QUEUE_STATUS_OUT_OF_MEMORY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY );\n if ( nStatus & QUEUE_STATUS_DOOR_OPEN )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN );\n if ( nStatus & QUEUE_STATUS_POWER_SAVE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE );\n\n \/\/ Anzahl Jobs\n sal_uLong nJobs = rInfo.GetJobs();\n if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) )\n {\n XubString aJobStr( SVT_RESSTR( STR_SVT_PRNDLG_JOBCOUNT ) );\n OUString aJobs( OUString::number( nJobs ) );\n aJobStr.SearchAndReplaceAscii( \"%d\", aJobs );\n ImplPrnDlgAddString( aStr, aJobStr );\n }\n\n return aStr;\n}\n\n\/\/ =======================================================================\n\nPrinterSetupDialog::PrinterSetupDialog(Window* pParent)\n : ModalDialog(pParent, \"PrinterSetupDialog\",\n \"svt\/ui\/printersetupdialog.ui\")\n{\n get(m_pLbName, \"name\");\n m_pLbName->SetStyle(m_pLbName->GetStyle() | WB_SORT);\n get(m_pBtnProperties, \"properties\");\n get(m_pBtnOptions, \"options\");\n get(m_pFiStatus, \"status\");\n get(m_pFiType, \"type\");\n get(m_pFiLocation, \"location\");\n get(m_pFiComment, \"comment\");\n\n \/\/ show options button only if link is set\n m_pBtnOptions->Hide();\n\n mpPrinter = NULL;\n mpTempPrinter = NULL;\n\n maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE );\n maStatusTimer.SetTimeoutHdl( LINK( this, PrinterSetupDialog, ImplStatusHdl ) );\n m_pBtnProperties->SetClickHdl( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) );\n m_pLbName->SetSelectHdl( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinterSetupDialog::~PrinterSetupDialog()\n{\n ImplFreePrnDlgListBox(m_pLbName, sal_False);\n delete mpTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::SetOptionsHdl( const Link& rLink )\n{\n m_pBtnOptions->SetClickHdl( rLink );\n m_pBtnOptions->Show( rLink.IsSet() );\n}\n\nvoid PrinterSetupDialog::ImplSetInfo()\n{\n const QueueInfo* pInfo = Printer::GetQueueInfo(m_pLbName->GetSelectEntry(), true);\n if ( pInfo )\n {\n m_pFiType->SetText( pInfo->GetDriver() );\n m_pFiLocation->SetText( pInfo->GetLocation() );\n m_pFiComment->SetText( pInfo->GetComment() );\n m_pFiStatus->SetText( ImplPrnDlgGetStatusText( *pInfo ) );\n }\n else\n {\n OUString aTempStr;\n m_pFiType->SetText( aTempStr );\n m_pFiLocation->SetText( aTempStr );\n m_pFiComment->SetText( aTempStr );\n m_pFiStatus->SetText( aTempStr );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK_NOARG(PrinterSetupDialog, ImplStatusHdl)\n{\n QueueInfo aInfo;\n ImplPrnDlgUpdateQueueInfo(m_pLbName, aInfo);\n m_pFiStatus->SetText( ImplPrnDlgGetStatusText( aInfo ) );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK_NOARG(PrinterSetupDialog, ImplPropertiesHdl)\n{\n if ( !mpTempPrinter )\n mpTempPrinter = new Printer( mpPrinter->GetJobSetup() );\n mpTempPrinter->Setup( this );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK_NOARG(PrinterSetupDialog, ImplChangePrinterHdl)\n{\n mpTempPrinter = ImplPrnDlgListBoxSelect(m_pLbName, m_pBtnProperties,\n mpPrinter, mpTempPrinter );\n ImplSetInfo();\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nlong PrinterSetupDialog::Notify( NotifyEvent& rNEvt )\n{\n if ( (rNEvt.GetType() == EVENT_GETFOCUS) && IsReallyVisible() )\n ImplStatusHdl( &maStatusTimer );\n\n return ModalDialog::Notify( rNEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::DataChanged( const DataChangedEvent& rDCEvt )\n{\n if ( rDCEvt.GetType() == DATACHANGED_PRINTER )\n {\n mpTempPrinter = ImplPrnDlgUpdatePrinter( mpPrinter, mpTempPrinter );\n Printer* pPrn;\n if ( mpTempPrinter )\n pPrn = mpTempPrinter;\n else\n pPrn = mpPrinter;\n ImplFillPrnDlgListBox(pPrn, m_pLbName, m_pBtnProperties);\n ImplSetInfo();\n }\n\n ModalDialog::DataChanged( rDCEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nshort PrinterSetupDialog::Execute()\n{\n if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() )\n {\n SAL_WARN( \"svtools.dialogs\", \"PrinterSetupDialog::Execute() - No Printer or printer is printing\" );\n return sal_False;\n }\n\n Printer::updatePrinters();\n\n ImplFillPrnDlgListBox(mpPrinter, m_pLbName, m_pBtnProperties);\n ImplSetInfo();\n maStatusTimer.Start();\n\n \/\/ Dialog starten\n short nRet = ModalDialog::Execute();\n\n \/\/ Wenn Dialog mit OK beendet wurde, dann die Daten updaten\n if ( nRet == sal_True )\n {\n if ( mpTempPrinter )\n mpPrinter->SetPrinterProps( mpTempPrinter );\n }\n\n maStatusTimer.Stop();\n\n return nRet;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nmake svtools XubString free\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n#include \n\n\/\/ =======================================================================\n\nvoid ImplFillPrnDlgListBox( const Printer* pPrinter,\n ListBox* pBox, PushButton* pPropBtn )\n{\n ImplFreePrnDlgListBox( pBox );\n\n const std::vector& rPrinters = Printer::GetPrinterQueues();\n unsigned int nCount = rPrinters.size();\n if ( nCount )\n {\n for( unsigned int i = 0; i < nCount; i++ )\n pBox->InsertEntry( rPrinters[i] );\n pBox->SelectEntry( pPrinter->GetName() );\n }\n\n pBox->Enable( nCount != 0 );\n pPropBtn->Show( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplFreePrnDlgListBox( ListBox* pBox, sal_Bool bClear )\n{\n if ( bClear )\n pBox->Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgListBoxSelect( ListBox* pBox, PushButton* pPropBtn,\n Printer* pPrinter, Printer* pTempPrinter )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo)\n {\n if ( !pTempPrinter )\n {\n if ( (pPrinter->GetName() == pInfo->GetPrinterName()) &&\n (pPrinter->GetDriverName() == pInfo->GetDriver()) )\n pTempPrinter = new Printer( pPrinter->GetJobSetup() );\n else\n pTempPrinter = new Printer( *pInfo );\n }\n else\n {\n if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) ||\n (pTempPrinter->GetDriverName() != pInfo->GetDriver()) )\n {\n delete pTempPrinter;\n pTempPrinter = new Printer( *pInfo );\n }\n }\n\n pPropBtn->Enable( pTempPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n }\n else\n pPropBtn->Disable();\n }\n else\n pPropBtn->Disable();\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgUpdatePrinter( Printer* pPrinter, Printer* pTempPrinter )\n{\n OUString aPrnName;\n if ( pTempPrinter )\n aPrnName = pTempPrinter->GetName();\n else\n aPrnName = pPrinter->GetName();\n\n if ( ! Printer::GetQueueInfo( aPrnName, false ) )\n {\n if ( pTempPrinter )\n delete pTempPrinter;\n pTempPrinter = new Printer;\n }\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplPrnDlgUpdateQueueInfo( ListBox* pBox, QueueInfo& rInfo )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo )\n rInfo = *pInfo;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic OUString ImplPrnDlgAddString(const OUString& rStr, const OUString& rAddStr)\n{\n OUString aStr(rStr);\n if (!aStr.isEmpty())\n aStr += \"; \" ;\n return aStr + rAddStr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic OUString ImplPrnDlgAddResString(const OUString& rStr, sal_uInt16 nResId)\n{\n return ImplPrnDlgAddString(rStr, SVT_RESSTR(nResId));\n}\n\n\/\/ -----------------------------------------------------------------------\n\nOUString ImplPrnDlgGetStatusText( const QueueInfo& rInfo )\n{\n OUString aStr;\n sal_uLong nStatus = rInfo.GetStatus();\n\n \/\/ Default-Printer\n if ( !rInfo.GetPrinterName().isEmpty() &&\n (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER );\n\n \/\/ Status\n if ( nStatus & QUEUE_STATUS_READY )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY );\n if ( nStatus & QUEUE_STATUS_PAUSED )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED );\n if ( nStatus & QUEUE_STATUS_PENDING_DELETION )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING );\n if ( nStatus & QUEUE_STATUS_BUSY )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY );\n if ( nStatus & QUEUE_STATUS_INITIALIZING )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING );\n if ( nStatus & QUEUE_STATUS_WAITING )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING );\n if ( nStatus & QUEUE_STATUS_WARMING_UP )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP );\n if ( nStatus & QUEUE_STATUS_PROCESSING )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING );\n if ( nStatus & QUEUE_STATUS_PRINTING )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING );\n if ( nStatus & QUEUE_STATUS_OFFLINE )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE );\n if ( nStatus & QUEUE_STATUS_ERROR )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR );\n if ( nStatus & QUEUE_STATUS_SERVER_UNKNOWN )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN );\n if ( nStatus & QUEUE_STATUS_PAPER_JAM )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM );\n if ( nStatus & QUEUE_STATUS_PAPER_OUT )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT );\n if ( nStatus & QUEUE_STATUS_MANUAL_FEED )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED );\n if ( nStatus & QUEUE_STATUS_PAPER_PROBLEM )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM );\n if ( nStatus & QUEUE_STATUS_IO_ACTIVE )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE );\n if ( nStatus & QUEUE_STATUS_OUTPUT_BIN_FULL )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL );\n if ( nStatus & QUEUE_STATUS_TONER_LOW )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW );\n if ( nStatus & QUEUE_STATUS_NO_TONER )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER );\n if ( nStatus & QUEUE_STATUS_PAGE_PUNT )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT );\n if ( nStatus & QUEUE_STATUS_USER_INTERVENTION )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION );\n if ( nStatus & QUEUE_STATUS_OUT_OF_MEMORY )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY );\n if ( nStatus & QUEUE_STATUS_DOOR_OPEN )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN );\n if ( nStatus & QUEUE_STATUS_POWER_SAVE )\n aStr = ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE );\n\n \/\/ Anzahl Jobs\n sal_uLong nJobs = rInfo.GetJobs();\n if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) )\n {\n OUString aJobStr( SVT_RESSTR( STR_SVT_PRNDLG_JOBCOUNT ) );\n OUString aJobs( OUString::number( nJobs ) );\n aStr = ImplPrnDlgAddString(aStr, aJobStr.replaceAll(\"%d\", aJobs));\n }\n\n return aStr;\n}\n\n\/\/ =======================================================================\n\nPrinterSetupDialog::PrinterSetupDialog(Window* pParent)\n : ModalDialog(pParent, \"PrinterSetupDialog\",\n \"svt\/ui\/printersetupdialog.ui\")\n{\n get(m_pLbName, \"name\");\n m_pLbName->SetStyle(m_pLbName->GetStyle() | WB_SORT);\n get(m_pBtnProperties, \"properties\");\n get(m_pBtnOptions, \"options\");\n get(m_pFiStatus, \"status\");\n get(m_pFiType, \"type\");\n get(m_pFiLocation, \"location\");\n get(m_pFiComment, \"comment\");\n\n \/\/ show options button only if link is set\n m_pBtnOptions->Hide();\n\n mpPrinter = NULL;\n mpTempPrinter = NULL;\n\n maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE );\n maStatusTimer.SetTimeoutHdl( LINK( this, PrinterSetupDialog, ImplStatusHdl ) );\n m_pBtnProperties->SetClickHdl( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) );\n m_pLbName->SetSelectHdl( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinterSetupDialog::~PrinterSetupDialog()\n{\n ImplFreePrnDlgListBox(m_pLbName, sal_False);\n delete mpTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::SetOptionsHdl( const Link& rLink )\n{\n m_pBtnOptions->SetClickHdl( rLink );\n m_pBtnOptions->Show( rLink.IsSet() );\n}\n\nvoid PrinterSetupDialog::ImplSetInfo()\n{\n const QueueInfo* pInfo = Printer::GetQueueInfo(m_pLbName->GetSelectEntry(), true);\n if ( pInfo )\n {\n m_pFiType->SetText( pInfo->GetDriver() );\n m_pFiLocation->SetText( pInfo->GetLocation() );\n m_pFiComment->SetText( pInfo->GetComment() );\n m_pFiStatus->SetText( ImplPrnDlgGetStatusText( *pInfo ) );\n }\n else\n {\n OUString aTempStr;\n m_pFiType->SetText( aTempStr );\n m_pFiLocation->SetText( aTempStr );\n m_pFiComment->SetText( aTempStr );\n m_pFiStatus->SetText( aTempStr );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK_NOARG(PrinterSetupDialog, ImplStatusHdl)\n{\n QueueInfo aInfo;\n ImplPrnDlgUpdateQueueInfo(m_pLbName, aInfo);\n m_pFiStatus->SetText( ImplPrnDlgGetStatusText( aInfo ) );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK_NOARG(PrinterSetupDialog, ImplPropertiesHdl)\n{\n if ( !mpTempPrinter )\n mpTempPrinter = new Printer( mpPrinter->GetJobSetup() );\n mpTempPrinter->Setup( this );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK_NOARG(PrinterSetupDialog, ImplChangePrinterHdl)\n{\n mpTempPrinter = ImplPrnDlgListBoxSelect(m_pLbName, m_pBtnProperties,\n mpPrinter, mpTempPrinter );\n ImplSetInfo();\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nlong PrinterSetupDialog::Notify( NotifyEvent& rNEvt )\n{\n if ( (rNEvt.GetType() == EVENT_GETFOCUS) && IsReallyVisible() )\n ImplStatusHdl( &maStatusTimer );\n\n return ModalDialog::Notify( rNEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::DataChanged( const DataChangedEvent& rDCEvt )\n{\n if ( rDCEvt.GetType() == DATACHANGED_PRINTER )\n {\n mpTempPrinter = ImplPrnDlgUpdatePrinter( mpPrinter, mpTempPrinter );\n Printer* pPrn;\n if ( mpTempPrinter )\n pPrn = mpTempPrinter;\n else\n pPrn = mpPrinter;\n ImplFillPrnDlgListBox(pPrn, m_pLbName, m_pBtnProperties);\n ImplSetInfo();\n }\n\n ModalDialog::DataChanged( rDCEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nshort PrinterSetupDialog::Execute()\n{\n if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() )\n {\n SAL_WARN( \"svtools.dialogs\", \"PrinterSetupDialog::Execute() - No Printer or printer is printing\" );\n return sal_False;\n }\n\n Printer::updatePrinters();\n\n ImplFillPrnDlgListBox(mpPrinter, m_pLbName, m_pBtnProperties);\n ImplSetInfo();\n maStatusTimer.Start();\n\n \/\/ Dialog starten\n short nRet = ModalDialog::Execute();\n\n \/\/ Wenn Dialog mit OK beendet wurde, dann die Daten updaten\n if ( nRet == sal_True )\n {\n if ( mpTempPrinter )\n mpPrinter->SetPrinterProps( mpTempPrinter );\n }\n\n maStatusTimer.Stop();\n\n return nRet;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n* *\n* SPLASH build system v0.2 *\n* *\n* Copyright (c) 2016 Andrew D. Zonenberg *\n* All rights reserved. *\n* *\n* Redistribution and use in Object and binary forms, with or without modification, are permitted provided that the *\n* following conditions are met: *\n* *\n* * Redistributions of Object code must retain the above copyright notice, this list of conditions, and the *\n* following disclaimer. *\n* *\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *\n* following disclaimer in the documentation and\/or other materials provided with the distribution. *\n* *\n* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *\n* derived from this software without specific prior written permission. *\n* *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *\n* POSSIBILITY OF SUCH DAMAGE. *\n* *\n***********************************************************************************************************************\/\n\n#include \"splashcore.h\"\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nCPPObjectNode::CPPObjectNode(\n\tBuildGraph* graph,\n\tstd::string arch,\n\tstd::string config,\n\tstd::string fname,\n\tstd::string path,\n\tstd::string toolchain)\n{\n\/*\n\t\t$cc -M -MG\n\t *\/\n}\n\nCPPObjectNode::~CPPObjectNode()\n{\n}\n\nAdded debug log message\/***********************************************************************************************************************\n* *\n* SPLASH build system v0.2 *\n* *\n* Copyright (c) 2016 Andrew D. Zonenberg *\n* All rights reserved. *\n* *\n* Redistribution and use in Object and binary forms, with or without modification, are permitted provided that the *\n* following conditions are met: *\n* *\n* * Redistributions of Object code must retain the above copyright notice, this list of conditions, and the *\n* following disclaimer. *\n* *\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *\n* following disclaimer in the documentation and\/or other materials provided with the distribution. *\n* *\n* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *\n* derived from this software without specific prior written permission. *\n* *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *\n* POSSIBILITY OF SUCH DAMAGE. *\n* *\n***********************************************************************************************************************\/\n\n#include \"splashcore.h\"\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nCPPObjectNode::CPPObjectNode(\n\tBuildGraph* graph,\n\tstd::string arch,\n\tstd::string config,\n\tstd::string fname,\n\tstd::string path,\n\tstd::string toolchain)\n{\n\tLogDebug(\"Creating CPPObjectNode %s\\n\", fname.c_str());\n\/*\n\t$cc -M -MG\n *\/\n}\n\nCPPObjectNode::~CPPObjectNode()\n{\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: mailconfigpage.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-09-20 13:22:05 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _MAILCONFIGPAGE_HXX\n#define _MAILCONFIGPAGE_HXX\n\n#ifndef _SFXTABDLG_HXX\n#include \n#endif\n#ifndef _BUTTON_HXX\n#include \n#endif\n#ifndef _LSTBOX_HXX\n#include \n#endif\n#ifndef _FIELD_HXX\n#include \n#endif\n#ifndef _FIXED_HXX\n#include \n#endif\n#ifndef _BASEDLGS_HXX\n#include \n#endif\n\nclass SwTestAccountSettingsDialog;\nclass SwMailMergeConfigItem;\n\/*-- 05.05.2004 16:45:45---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nclass SwMailConfigPage : public SfxTabPage\n{\n friend class SwTestAccountSettingsDialog;\n\n FixedLine m_aIdentityFL;\n\n FixedText m_aDisplayNameFT;\n Edit m_aDisplayNameED;\n FixedText m_aAddressFT;\n Edit m_aAddressED;\n\n CheckBox m_aReplyToCB;\n FixedText m_aReplyToFT;\n Edit m_aReplyToED;\n\n FixedLine m_aSMTPFL;\n\n FixedText m_aServerFT;\n Edit m_aServerED;\n FixedText m_aPortFT;\n NumericField m_aPortNF;\n\n FixedText m_aSecureFT;\n ListBox m_aSecureLB;\n\n PushButton m_aServerAuthenticationPB;\n\n FixedLine m_aSeparatorFL;\n PushButton m_aTestPB;\n\n SwMailMergeConfigItem* m_pConfigItem;\n\n DECL_LINK(ReplyToHdl, CheckBox*);\n DECL_LINK(AuthenticationHdl, PushButton*);\n DECL_LINK(TestHdl, PushButton*);\n\n\npublic:\n SwMailConfigPage( Window* pParent, const SfxItemSet& rSet );\n ~SwMailConfigPage();\n\n static SfxTabPage* Create( Window* pParent,\n const SfxItemSet& rAttrSet);\n\n virtual BOOL FillItemSet( SfxItemSet& rSet );\n virtual void Reset( const SfxItemSet& rSet );\n\n};\n\n\/*-- 18.08.2004 12:02:02---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nclass SwMailConfigDlg : public SfxSingleTabDialog\n{\npublic:\n\n SwMailConfigDlg( Window* pParent, SfxItemSet& rSet );\n ~SwMailConfigDlg();\n};\n\n#endif\n\nINTEGRATION: CWS os51 (1.2.234); FILE MERGED 2005\/01\/21 10:57:07 mbu 1.2.234.1: #i40672\/*************************************************************************\n *\n * $RCSfile: mailconfigpage.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-02-16 17:04:59 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _MAILCONFIGPAGE_HXX\n#define _MAILCONFIGPAGE_HXX\n\n#ifndef _SFXTABDLG_HXX\n#include \n#endif\n#ifndef _BUTTON_HXX\n#include \n#endif\n#ifndef _LSTBOX_HXX\n#include \n#endif\n#ifndef _FIELD_HXX\n#include \n#endif\n#ifndef _FIXED_HXX\n#include \n#endif\n#ifndef _BASEDLGS_HXX\n#include \n#endif\n\nclass SwTestAccountSettingsDialog;\nclass SwMailMergeConfigItem;\n\/*-- 05.05.2004 16:45:45---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nclass SwMailConfigPage : public SfxTabPage\n{\n friend class SwTestAccountSettingsDialog;\n\n FixedLine m_aIdentityFL;\n\n FixedText m_aDisplayNameFT;\n Edit m_aDisplayNameED;\n FixedText m_aAddressFT;\n Edit m_aAddressED;\n\n CheckBox m_aReplyToCB;\n FixedText m_aReplyToFT;\n Edit m_aReplyToED;\n\n FixedLine m_aSMTPFL;\n\n FixedText m_aServerFT;\n Edit m_aServerED;\n FixedText m_aPortFT;\n NumericField m_aPortNF;\n\n CheckBox m_aSecureCB;\n\n PushButton m_aServerAuthenticationPB;\n\n FixedLine m_aSeparatorFL;\n PushButton m_aTestPB;\n\n SwMailMergeConfigItem* m_pConfigItem;\n\n DECL_LINK(ReplyToHdl, CheckBox*);\n DECL_LINK(AuthenticationHdl, PushButton*);\n DECL_LINK(TestHdl, PushButton*);\n\n\npublic:\n SwMailConfigPage( Window* pParent, const SfxItemSet& rSet );\n ~SwMailConfigPage();\n\n static SfxTabPage* Create( Window* pParent,\n const SfxItemSet& rAttrSet);\n\n virtual BOOL FillItemSet( SfxItemSet& rSet );\n virtual void Reset( const SfxItemSet& rSet );\n\n};\n\n\/*-- 18.08.2004 12:02:02---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nclass SwMailConfigDlg : public SfxSingleTabDialog\n{\npublic:\n\n SwMailConfigDlg( Window* pParent, SfxItemSet& rSet );\n ~SwMailConfigDlg();\n};\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ signatureactions.h\n\/\/\n\/\/ Copyright (c) 2013-2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"signatureactions.h\"\n\n#include \"signaturemodel.h\"\n#include \"signatureview.h\"\n#include \"signaturedialog.h\"\n#include \"passphrasedialog.h\"\n\n#include \"entropysource.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nSignatureActions::SignatureActions(CoinDB::SynchedVault& synchedVault, SignatureDialog& dialog)\n : m_synchedVault(synchedVault), m_dialog(dialog), m_currentRow(-1)\n{\n createActions();\n createMenus();\n connect(m_dialog.getView()->selectionModel(), &QItemSelectionModel::currentChanged, this, &SignatureActions::updateCurrentKeychain);\n}\n\nSignatureActions::~SignatureActions()\n{\n delete addSignatureAction;\n delete unlockKeychainAction;\n delete lockKeychainAction;\n delete menu;\n}\n\nvoid SignatureActions::updateCurrentKeychain(const QModelIndex& current, const QModelIndex& \/*previous*\/)\n{\n m_currentRow = current.row();\n refreshCurrentKeychain();\n}\n\nvoid SignatureActions::refreshCurrentKeychain()\n{\n if (m_currentRow != -1)\n {\n QStandardItem* keychainNameItem = m_dialog.getModel()->item(m_currentRow, 0);\n m_currentKeychain = keychainNameItem->text();\n\n if (m_synchedVault.isVaultOpen())\n {\n int keychainState = m_dialog.getModel()->getKeychainState(m_currentRow);\n bool hasSigned = m_dialog.getModel()->getKeychainHasSigned(m_currentRow);\n int sigsNeeded = m_dialog.getModel()->getSigsNeeded();\n\n addSignatureAction->setEnabled(keychainState != SignatureModel::PUBLIC && !hasSigned && sigsNeeded > 0);\n unlockKeychainAction->setEnabled(keychainState == SignatureModel::LOCKED);\n lockKeychainAction->setEnabled(keychainState == SignatureModel::UNLOCKED);\n return;\n }\n }\n else\n {\n m_currentKeychain = \"\";\n }\n\n addSignatureAction->setEnabled(false);\n unlockKeychainAction->setEnabled(false);\n lockKeychainAction->setEnabled(false);\n}\n\nvoid SignatureActions::addSignature()\n{\n try\n {\n if (m_currentKeychain.isEmpty()) throw std::runtime_error(\"No keychain is selected.\");\n if (!m_synchedVault.isVaultOpen()) throw std::runtime_error(\"No vault is open.\");\n\n CoinDB::Vault* vault = m_synchedVault.getVault();\n if (!vault->isKeychainPrivate(m_currentKeychain.toStdString()))\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Keychain is public.\"));\n return;\n }\n\n QString currentKeychain = m_currentKeychain;\n if (vault->isKeychainLocked(m_currentKeychain.toStdString()))\n { \n unlockKeychain();\n }\n\n std::vector keychainNames;\n keychainNames.push_back(currentKeychain.toStdString());\n\n seedEntropySource(false, &m_dialog);\n vault->signTx(m_dialog.getModel()->getTxHash(), keychainNames, true);\n\n if (keychainNames.empty())\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Signature could not be added.\"));\n return;\n }\n\n m_dialog.updateTx();\n }\n catch (const std::exception& e)\n {\n emit error(e.what());\n }\n}\n\nvoid SignatureActions::unlockKeychain()\n{\n try\n {\n if (m_currentKeychain.isEmpty()) throw std::runtime_error(\"No keychain is selected.\");\n if (!m_synchedVault.isVaultOpen()) throw std::runtime_error(\"No vault is open.\");\n\n CoinDB::Vault* vault = m_synchedVault.getVault();\n std::string keychainName = m_currentKeychain.toStdString();\n if (!vault->isKeychainLocked(keychainName))\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Keychain is already unlocked.\"));\n return;\n }\n\n secure_bytes_t lockKey;\n if (vault->isKeychainEncrypted(keychainName))\n {\n PassphraseDialog dlg(tr(\"Please enter the decryption passphrase for \") + m_currentKeychain + \":\");\n if (!dlg.exec()) return;\n lockKey = passphraseHash(dlg.getPassphrase().toStdString());\n }\n\n vault->unlockKeychain(keychainName, lockKey);\n refreshCurrentKeychain();\n m_dialog.updateKeychains();\n }\n catch (const CoinDB::KeychainPrivateKeyUnlockFailedException& e)\n {\n emit error(tr(\"Keychain decryption failed.\"));\n }\n catch (const std::exception& e)\n {\n emit error(e.what());\n }\n}\n\nvoid SignatureActions::lockKeychain()\n{\n try\n {\n if (m_currentKeychain.isEmpty()) throw std::runtime_error(\"No keychain is selected.\");\n if (!m_synchedVault.isVaultOpen()) throw std::runtime_error(\"No vault is open.\");\n\n CoinDB::Vault* vault = m_synchedVault.getVault();\n std::string keychainName = m_currentKeychain.toStdString();\n if (vault->isKeychainLocked(keychainName))\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Keychain is already locked.\"));\n return;\n }\n\n vault->lockKeychain(keychainName);\n refreshCurrentKeychain();\n m_dialog.updateKeychains();\n }\n catch (const std::exception& e)\n {\n emit error(e.what());\n }\n}\n\nvoid SignatureActions::createActions()\n{\n addSignatureAction = new QAction(tr(\"Add signature...\"), this);\n addSignatureAction->setEnabled(false);\n connect(addSignatureAction, SIGNAL(triggered()), this, SLOT(addSignature()));\n\n unlockKeychainAction = new QAction(tr(\"Unlock keychain...\"), this);\n unlockKeychainAction->setEnabled(false);\n connect(unlockKeychainAction, SIGNAL(triggered()), this, SLOT(unlockKeychain()));\n\n lockKeychainAction = new QAction(tr(\"Lock keychain\"), this);\n lockKeychainAction->setEnabled(false);\n connect(lockKeychainAction, SIGNAL(triggered()), this, SLOT(lockKeychain()));\n}\n\nvoid SignatureActions::createMenus()\n{\n menu = new QMenu();\n menu->addAction(addSignatureAction);\n menu->addSeparator();\n menu->addAction(unlockKeychainAction);\n menu->addAction(lockKeychainAction);\n}\n\nPrompt to send transaction after signing from SignatureDialog.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ CoinVault\n\/\/\n\/\/ signatureactions.h\n\/\/\n\/\/ Copyright (c) 2013-2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \"signatureactions.h\"\n\n#include \"signaturemodel.h\"\n#include \"signatureview.h\"\n#include \"signaturedialog.h\"\n#include \"passphrasedialog.h\"\n\n#include \"entropysource.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nSignatureActions::SignatureActions(CoinDB::SynchedVault& synchedVault, SignatureDialog& dialog)\n : m_synchedVault(synchedVault), m_dialog(dialog), m_currentRow(-1)\n{\n createActions();\n createMenus();\n connect(m_dialog.getView()->selectionModel(), &QItemSelectionModel::currentChanged, this, &SignatureActions::updateCurrentKeychain);\n}\n\nSignatureActions::~SignatureActions()\n{\n delete addSignatureAction;\n delete unlockKeychainAction;\n delete lockKeychainAction;\n delete menu;\n}\n\nvoid SignatureActions::updateCurrentKeychain(const QModelIndex& current, const QModelIndex& \/*previous*\/)\n{\n m_currentRow = current.row();\n refreshCurrentKeychain();\n}\n\nvoid SignatureActions::refreshCurrentKeychain()\n{\n if (m_currentRow != -1)\n {\n QStandardItem* keychainNameItem = m_dialog.getModel()->item(m_currentRow, 0);\n m_currentKeychain = keychainNameItem->text();\n\n if (m_synchedVault.isVaultOpen())\n {\n int keychainState = m_dialog.getModel()->getKeychainState(m_currentRow);\n bool hasSigned = m_dialog.getModel()->getKeychainHasSigned(m_currentRow);\n int sigsNeeded = m_dialog.getModel()->getSigsNeeded();\n\n addSignatureAction->setEnabled(keychainState != SignatureModel::PUBLIC && !hasSigned && sigsNeeded > 0);\n unlockKeychainAction->setEnabled(keychainState == SignatureModel::LOCKED);\n lockKeychainAction->setEnabled(keychainState == SignatureModel::UNLOCKED);\n return;\n }\n }\n else\n {\n m_currentKeychain = \"\";\n }\n\n addSignatureAction->setEnabled(false);\n unlockKeychainAction->setEnabled(false);\n lockKeychainAction->setEnabled(false);\n}\n\nvoid SignatureActions::addSignature()\n{\n try\n {\n if (m_currentKeychain.isEmpty()) throw std::runtime_error(\"No keychain is selected.\");\n if (!m_synchedVault.isVaultOpen()) throw std::runtime_error(\"No vault is open.\");\n\n CoinDB::Vault* vault = m_synchedVault.getVault();\n if (!vault->isKeychainPrivate(m_currentKeychain.toStdString()))\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Keychain is public.\"));\n return;\n }\n\n QString currentKeychain = m_currentKeychain;\n if (vault->isKeychainLocked(m_currentKeychain.toStdString()))\n { \n unlockKeychain();\n }\n\n std::vector keychainNames;\n keychainNames.push_back(currentKeychain.toStdString());\n\n seedEntropySource(false, &m_dialog);\n bytes_t txhash = m_dialog.getModel()->getTxHash();\n vault->signTx(txhash, keychainNames, true);\n\n if (keychainNames.empty())\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Signature could not be added.\"));\n return;\n }\n\n m_dialog.updateTx();\n if (m_synchedVault.isConnected() && m_dialog.getModel()->getSigsNeeded() == 0)\n {\n QMessageBox sendPrompt;\n sendPrompt.setText(tr(\"Transaction is fully signed. Would you like to send?\"));\n sendPrompt.setStandardButtons(QMessageBox::Yes | QMessageBox::No);\n sendPrompt.setDefaultButton(QMessageBox::Yes);\n if (sendPrompt.exec() == QMessageBox::Yes)\n {\n if (!m_synchedVault.isConnected())\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Connection was lost.\"));\n return;\n }\n std::shared_ptr tx = vault->getTx(txhash);\n Coin::Transaction coin_tx = tx->toCoinCore();\n m_synchedVault.sendTx(coin_tx);\n }\n }\n }\n catch (const std::exception& e)\n {\n emit error(e.what());\n }\n}\n\nvoid SignatureActions::unlockKeychain()\n{\n try\n {\n if (m_currentKeychain.isEmpty()) throw std::runtime_error(\"No keychain is selected.\");\n if (!m_synchedVault.isVaultOpen()) throw std::runtime_error(\"No vault is open.\");\n\n CoinDB::Vault* vault = m_synchedVault.getVault();\n std::string keychainName = m_currentKeychain.toStdString();\n if (!vault->isKeychainLocked(keychainName))\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Keychain is already unlocked.\"));\n return;\n }\n\n secure_bytes_t lockKey;\n if (vault->isKeychainEncrypted(keychainName))\n {\n PassphraseDialog dlg(tr(\"Please enter the decryption passphrase for \") + m_currentKeychain + \":\");\n if (!dlg.exec()) return;\n lockKey = passphraseHash(dlg.getPassphrase().toStdString());\n }\n\n vault->unlockKeychain(keychainName, lockKey);\n refreshCurrentKeychain();\n m_dialog.updateKeychains();\n }\n catch (const CoinDB::KeychainPrivateKeyUnlockFailedException& e)\n {\n emit error(tr(\"Keychain decryption failed.\"));\n }\n catch (const std::exception& e)\n {\n emit error(e.what());\n }\n}\n\nvoid SignatureActions::lockKeychain()\n{\n try\n {\n if (m_currentKeychain.isEmpty()) throw std::runtime_error(\"No keychain is selected.\");\n if (!m_synchedVault.isVaultOpen()) throw std::runtime_error(\"No vault is open.\");\n\n CoinDB::Vault* vault = m_synchedVault.getVault();\n std::string keychainName = m_currentKeychain.toStdString();\n if (vault->isKeychainLocked(keychainName))\n {\n QMessageBox::critical(nullptr, tr(\"Error\"), tr(\"Keychain is already locked.\"));\n return;\n }\n\n vault->lockKeychain(keychainName);\n refreshCurrentKeychain();\n m_dialog.updateKeychains();\n }\n catch (const std::exception& e)\n {\n emit error(e.what());\n }\n}\n\nvoid SignatureActions::createActions()\n{\n addSignatureAction = new QAction(tr(\"Add signature...\"), this);\n addSignatureAction->setEnabled(false);\n connect(addSignatureAction, SIGNAL(triggered()), this, SLOT(addSignature()));\n\n unlockKeychainAction = new QAction(tr(\"Unlock keychain...\"), this);\n unlockKeychainAction->setEnabled(false);\n connect(unlockKeychainAction, SIGNAL(triggered()), this, SLOT(unlockKeychain()));\n\n lockKeychainAction = new QAction(tr(\"Lock keychain\"), this);\n lockKeychainAction->setEnabled(false);\n connect(lockKeychainAction, SIGNAL(triggered()), this, SLOT(lockKeychain()));\n}\n\nvoid SignatureActions::createMenus()\n{\n menu = new QMenu();\n menu->addAction(addSignatureAction);\n menu->addSeparator();\n menu->addAction(unlockKeychainAction);\n menu->addAction(lockKeychainAction);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 The NXT Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"backend\/d3d12\/BufferD3D12.h\"\n\n#include \"backend\/d3d12\/D3D12Backend.h\"\n#include \"backend\/d3d12\/ResourceAllocator.h\"\n#include \"backend\/d3d12\/ResourceUploader.h\"\n#include \"common\/Assert.h\"\n\nnamespace backend {\nnamespace d3d12 {\n\n namespace {\n D3D12_RESOURCE_STATES D3D12BufferUsage(nxt::BufferUsageBit usage) {\n D3D12_RESOURCE_STATES resourceState = D3D12_RESOURCE_STATE_COMMON;\n\n if (usage & nxt::BufferUsageBit::TransferSrc) {\n resourceState |= D3D12_RESOURCE_STATE_COPY_SOURCE;\n }\n if (usage & nxt::BufferUsageBit::TransferDst) {\n resourceState |= D3D12_RESOURCE_STATE_COPY_DEST;\n }\n if (usage & (nxt::BufferUsageBit::Vertex | nxt::BufferUsageBit::Uniform)) {\n resourceState |= D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;\n }\n if (usage & nxt::BufferUsageBit::Index) {\n resourceState |= D3D12_RESOURCE_STATE_INDEX_BUFFER;\n }\n if (usage & nxt::BufferUsageBit::Storage) {\n resourceState |= D3D12_RESOURCE_STATE_UNORDERED_ACCESS;\n }\n\n return resourceState;\n }\n\n D3D12_HEAP_TYPE D3D12HeapType(nxt::BufferUsageBit allowedUsage) {\n if (allowedUsage & nxt::BufferUsageBit::MapRead) {\n return D3D12_HEAP_TYPE_READBACK;\n } else if (allowedUsage & nxt::BufferUsageBit::MapWrite) {\n return D3D12_HEAP_TYPE_UPLOAD;\n } else {\n return D3D12_HEAP_TYPE_DEFAULT;\n }\n }\n }\n\n Buffer::Buffer(Device* device, BufferBuilder* builder)\n : BufferBase(builder), device(device) {\n\n D3D12_RESOURCE_DESC resourceDescriptor;\n resourceDescriptor.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;\n resourceDescriptor.Alignment = 0;\n resourceDescriptor.Width = GetD3D12Size();\n resourceDescriptor.Height = 1;\n resourceDescriptor.DepthOrArraySize = 1;\n resourceDescriptor.MipLevels = 1;\n resourceDescriptor.Format = DXGI_FORMAT_UNKNOWN;\n resourceDescriptor.SampleDesc.Count = 1;\n resourceDescriptor.SampleDesc.Quality = 0;\n resourceDescriptor.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;\n resourceDescriptor.Flags = D3D12_RESOURCE_FLAG_NONE;\n\n auto heapType = D3D12HeapType(GetAllowedUsage());\n auto bufferUsage = D3D12BufferUsage(GetUsage());\n\n \/\/ D3D12 requires buffers on the READBACK heap to have the D3D12_RESOURCE_STATE_COPY_DEST state\n if (heapType == D3D12_HEAP_TYPE_READBACK) {\n bufferUsage |= D3D12_RESOURCE_STATE_COPY_DEST;\n }\n\n \/\/ D3D12 requires buffers on the UPLOAD heap to have the D3D12_RESOURCE_STATE_GENERIC_READ state\n if (heapType == D3D12_HEAP_TYPE_UPLOAD) {\n bufferUsage |= D3D12_RESOURCE_STATE_GENERIC_READ;\n }\n\n resource = device->GetResourceAllocator()->Allocate(heapType, resourceDescriptor, bufferUsage);\n }\n\n Buffer::~Buffer() {\n device->GetResourceAllocator()->Release(resource);\n }\n\n uint32_t Buffer::GetD3D12Size() const {\n \/\/ TODO(enga@google.com): TODO investigate if this needs to be a constraint at the API level\n return ((GetSize() + 256 - 1) \/ 256) * 256; \/\/ size is required to be 256-byte aligned.\n }\n\n ComPtr Buffer::GetD3D12Resource() {\n return resource;\n }\n\n bool Buffer::GetResourceTransitionBarrier(nxt::BufferUsageBit currentUsage, nxt::BufferUsageBit targetUsage, D3D12_RESOURCE_BARRIER* barrier) {\n if (GetAllowedUsage() & (nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::MapWrite)) {\n \/\/ Transitions are never needed for mapped buffers because they are created with and always need the Transfer(Dst|Src) state.\n \/\/ Mapped buffers cannot have states outside of (MapRead|TransferDst) and (MapWrite|TransferSrc)\n return false;\n }\n\n D3D12_RESOURCE_STATES stateBefore = D3D12BufferUsage(currentUsage);\n D3D12_RESOURCE_STATES stateAfter = D3D12BufferUsage(targetUsage);\n\n if (stateBefore == stateAfter) {\n return false;\n }\n\n barrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;\n barrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;\n barrier->Transition.pResource = resource.Get();\n barrier->Transition.StateBefore = stateBefore;\n barrier->Transition.StateAfter = stateAfter;\n barrier->Transition.Subresource = 0;\n\n return true;\n }\n\n D3D12_GPU_VIRTUAL_ADDRESS Buffer::GetVA() const {\n return resource->GetGPUVirtualAddress();\n }\n\n void Buffer::OnMapReadCommandSerialFinished(uint32_t mapSerial, const void* data) {\n CallMapReadCallback(mapSerial, NXT_BUFFER_MAP_READ_STATUS_SUCCESS, data);\n }\n\n void Buffer::SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) {\n device->GetResourceUploader()->BufferSubData(resource, start * sizeof(uint32_t), count * sizeof(uint32_t), data);\n }\n\n void Buffer::MapReadAsyncImpl(uint32_t serial, uint32_t start, uint32_t count) {\n D3D12_RANGE readRange = { start, start + count };\n char* data = nullptr;\n ASSERT_SUCCESS(resource->Map(0, &readRange, reinterpret_cast(&data)));\n\n MapReadRequestTracker* tracker = ToBackend(GetDevice())->GetMapReadRequestTracker();\n tracker->Track(this, serial, data);\n }\n\n void Buffer::UnmapImpl() {\n \/\/ TODO(enga@google.com): When MapWrite is implemented, this should state the range that was modified\n D3D12_RANGE writeRange = {};\n resource->Unmap(0, &writeRange);\n device->GetResourceAllocator()->Release(resource);\n }\n\n void Buffer::TransitionUsageImpl(nxt::BufferUsageBit currentUsage, nxt::BufferUsageBit targetUsage) {\n D3D12_RESOURCE_BARRIER barrier;\n if (GetResourceTransitionBarrier(currentUsage, targetUsage, &barrier)) {\n device->GetPendingCommandList()->ResourceBarrier(1, &barrier);\n }\n }\n\n\n BufferView::BufferView(BufferViewBuilder* builder)\n : BufferViewBase(builder) {\n\n cbvDesc.BufferLocation = ToBackend(GetBuffer())->GetVA() + GetOffset();\n cbvDesc.SizeInBytes = GetD3D12Size();\n\n uavDesc.Format = DXGI_FORMAT_UNKNOWN;\n uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;\n uavDesc.Buffer.FirstElement = GetOffset();\n uavDesc.Buffer.NumElements = GetD3D12Size();\n uavDesc.Buffer.StructureByteStride = 1;\n uavDesc.Buffer.CounterOffsetInBytes = 0;\n uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;\n }\n\n uint32_t BufferView::GetD3D12Size() const {\n \/\/ TODO(enga@google.com): TODO investigate if this needs to be a constraint at the API level\n return ((GetSize() + 256 - 1) \/ 256) * 256; \/\/ size is required to be 256-byte aligned.\n }\n\n const D3D12_CONSTANT_BUFFER_VIEW_DESC& BufferView::GetCBVDescriptor() const {\n return cbvDesc;\n }\n\n const D3D12_UNORDERED_ACCESS_VIEW_DESC& BufferView::GetUAVDescriptor() const {\n return uavDesc;\n }\n\n MapReadRequestTracker::MapReadRequestTracker(Device* device)\n : device(device) {\n }\n\n MapReadRequestTracker::~MapReadRequestTracker() {\n ASSERT(inflightRequests.Empty());\n }\n\n void MapReadRequestTracker::Track(Buffer* buffer, uint32_t mapSerial, const void* data) {\n Request request;\n request.buffer = buffer;\n request.mapSerial = mapSerial;\n request.data = data;\n\n inflightRequests.Enqueue(std::move(request), device->GetSerial());\n }\n\n void MapReadRequestTracker::Tick(Serial finishedSerial) {\n for (auto& request : inflightRequests.IterateUpTo(finishedSerial)) {\n request.buffer->OnMapReadCommandSerialFinished(request.mapSerial, request.data);\n }\n inflightRequests.ClearUpTo(finishedSerial);\n }\n\n}\n}\nUpdate BufferD3D12 to use Align helper\/\/ Copyright 2017 The NXT Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"backend\/d3d12\/BufferD3D12.h\"\n\n#include \"backend\/d3d12\/D3D12Backend.h\"\n#include \"backend\/d3d12\/ResourceAllocator.h\"\n#include \"backend\/d3d12\/ResourceUploader.h\"\n#include \"common\/Assert.h\"\n#include \"common\/Constants.h\"\n#include \"common\/Math.h\"\n\nnamespace backend {\nnamespace d3d12 {\n\n namespace {\n D3D12_RESOURCE_STATES D3D12BufferUsage(nxt::BufferUsageBit usage) {\n D3D12_RESOURCE_STATES resourceState = D3D12_RESOURCE_STATE_COMMON;\n\n if (usage & nxt::BufferUsageBit::TransferSrc) {\n resourceState |= D3D12_RESOURCE_STATE_COPY_SOURCE;\n }\n if (usage & nxt::BufferUsageBit::TransferDst) {\n resourceState |= D3D12_RESOURCE_STATE_COPY_DEST;\n }\n if (usage & (nxt::BufferUsageBit::Vertex | nxt::BufferUsageBit::Uniform)) {\n resourceState |= D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;\n }\n if (usage & nxt::BufferUsageBit::Index) {\n resourceState |= D3D12_RESOURCE_STATE_INDEX_BUFFER;\n }\n if (usage & nxt::BufferUsageBit::Storage) {\n resourceState |= D3D12_RESOURCE_STATE_UNORDERED_ACCESS;\n }\n\n return resourceState;\n }\n\n D3D12_HEAP_TYPE D3D12HeapType(nxt::BufferUsageBit allowedUsage) {\n if (allowedUsage & nxt::BufferUsageBit::MapRead) {\n return D3D12_HEAP_TYPE_READBACK;\n } else if (allowedUsage & nxt::BufferUsageBit::MapWrite) {\n return D3D12_HEAP_TYPE_UPLOAD;\n } else {\n return D3D12_HEAP_TYPE_DEFAULT;\n }\n }\n }\n\n Buffer::Buffer(Device* device, BufferBuilder* builder)\n : BufferBase(builder), device(device) {\n\n D3D12_RESOURCE_DESC resourceDescriptor;\n resourceDescriptor.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;\n resourceDescriptor.Alignment = 0;\n resourceDescriptor.Width = GetD3D12Size();\n resourceDescriptor.Height = 1;\n resourceDescriptor.DepthOrArraySize = 1;\n resourceDescriptor.MipLevels = 1;\n resourceDescriptor.Format = DXGI_FORMAT_UNKNOWN;\n resourceDescriptor.SampleDesc.Count = 1;\n resourceDescriptor.SampleDesc.Quality = 0;\n resourceDescriptor.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;\n resourceDescriptor.Flags = D3D12_RESOURCE_FLAG_NONE;\n\n auto heapType = D3D12HeapType(GetAllowedUsage());\n auto bufferUsage = D3D12BufferUsage(GetUsage());\n\n \/\/ D3D12 requires buffers on the READBACK heap to have the D3D12_RESOURCE_STATE_COPY_DEST state\n if (heapType == D3D12_HEAP_TYPE_READBACK) {\n bufferUsage |= D3D12_RESOURCE_STATE_COPY_DEST;\n }\n\n \/\/ D3D12 requires buffers on the UPLOAD heap to have the D3D12_RESOURCE_STATE_GENERIC_READ state\n if (heapType == D3D12_HEAP_TYPE_UPLOAD) {\n bufferUsage |= D3D12_RESOURCE_STATE_GENERIC_READ;\n }\n\n resource = device->GetResourceAllocator()->Allocate(heapType, resourceDescriptor, bufferUsage);\n }\n\n Buffer::~Buffer() {\n device->GetResourceAllocator()->Release(resource);\n }\n\n uint32_t Buffer::GetD3D12Size() const {\n \/\/ TODO(enga@google.com): TODO investigate if this needs to be a constraint at the API level\n return Align(GetSize(), 256);\n }\n\n ComPtr Buffer::GetD3D12Resource() {\n return resource;\n }\n\n bool Buffer::GetResourceTransitionBarrier(nxt::BufferUsageBit currentUsage, nxt::BufferUsageBit targetUsage, D3D12_RESOURCE_BARRIER* barrier) {\n if (GetAllowedUsage() & (nxt::BufferUsageBit::MapRead | nxt::BufferUsageBit::MapWrite)) {\n \/\/ Transitions are never needed for mapped buffers because they are created with and always need the Transfer(Dst|Src) state.\n \/\/ Mapped buffers cannot have states outside of (MapRead|TransferDst) and (MapWrite|TransferSrc)\n return false;\n }\n\n D3D12_RESOURCE_STATES stateBefore = D3D12BufferUsage(currentUsage);\n D3D12_RESOURCE_STATES stateAfter = D3D12BufferUsage(targetUsage);\n\n if (stateBefore == stateAfter) {\n return false;\n }\n\n barrier->Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;\n barrier->Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;\n barrier->Transition.pResource = resource.Get();\n barrier->Transition.StateBefore = stateBefore;\n barrier->Transition.StateAfter = stateAfter;\n barrier->Transition.Subresource = 0;\n\n return true;\n }\n\n D3D12_GPU_VIRTUAL_ADDRESS Buffer::GetVA() const {\n return resource->GetGPUVirtualAddress();\n }\n\n void Buffer::OnMapReadCommandSerialFinished(uint32_t mapSerial, const void* data) {\n CallMapReadCallback(mapSerial, NXT_BUFFER_MAP_READ_STATUS_SUCCESS, data);\n }\n\n void Buffer::SetSubDataImpl(uint32_t start, uint32_t count, const uint32_t* data) {\n device->GetResourceUploader()->BufferSubData(resource, start * sizeof(uint32_t), count * sizeof(uint32_t), data);\n }\n\n void Buffer::MapReadAsyncImpl(uint32_t serial, uint32_t start, uint32_t count) {\n D3D12_RANGE readRange = { start, start + count };\n char* data = nullptr;\n ASSERT_SUCCESS(resource->Map(0, &readRange, reinterpret_cast(&data)));\n\n MapReadRequestTracker* tracker = ToBackend(GetDevice())->GetMapReadRequestTracker();\n tracker->Track(this, serial, data);\n }\n\n void Buffer::UnmapImpl() {\n \/\/ TODO(enga@google.com): When MapWrite is implemented, this should state the range that was modified\n D3D12_RANGE writeRange = {};\n resource->Unmap(0, &writeRange);\n device->GetResourceAllocator()->Release(resource);\n }\n\n void Buffer::TransitionUsageImpl(nxt::BufferUsageBit currentUsage, nxt::BufferUsageBit targetUsage) {\n D3D12_RESOURCE_BARRIER barrier;\n if (GetResourceTransitionBarrier(currentUsage, targetUsage, &barrier)) {\n device->GetPendingCommandList()->ResourceBarrier(1, &barrier);\n }\n }\n\n\n BufferView::BufferView(BufferViewBuilder* builder)\n : BufferViewBase(builder) {\n\n cbvDesc.BufferLocation = ToBackend(GetBuffer())->GetVA() + GetOffset();\n cbvDesc.SizeInBytes = GetD3D12Size();\n\n uavDesc.Format = DXGI_FORMAT_UNKNOWN;\n uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;\n uavDesc.Buffer.FirstElement = GetOffset();\n uavDesc.Buffer.NumElements = GetD3D12Size();\n uavDesc.Buffer.StructureByteStride = 1;\n uavDesc.Buffer.CounterOffsetInBytes = 0;\n uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;\n }\n\n uint32_t BufferView::GetD3D12Size() const {\n \/\/ TODO(enga@google.com): TODO investigate if this needs to be a constraint at the API level\n return Align(GetSize(), 256);\n }\n\n const D3D12_CONSTANT_BUFFER_VIEW_DESC& BufferView::GetCBVDescriptor() const {\n return cbvDesc;\n }\n\n const D3D12_UNORDERED_ACCESS_VIEW_DESC& BufferView::GetUAVDescriptor() const {\n return uavDesc;\n }\n\n MapReadRequestTracker::MapReadRequestTracker(Device* device)\n : device(device) {\n }\n\n MapReadRequestTracker::~MapReadRequestTracker() {\n ASSERT(inflightRequests.Empty());\n }\n\n void MapReadRequestTracker::Track(Buffer* buffer, uint32_t mapSerial, const void* data) {\n Request request;\n request.buffer = buffer;\n request.mapSerial = mapSerial;\n request.data = data;\n\n inflightRequests.Enqueue(std::move(request), device->GetSerial());\n }\n\n void MapReadRequestTracker::Tick(Serial finishedSerial) {\n for (auto& request : inflightRequests.IterateUpTo(finishedSerial)) {\n request.buffer->OnMapReadCommandSerialFinished(request.mapSerial, request.data);\n }\n inflightRequests.ClearUpTo(finishedSerial);\n }\n\n}\n}\n<|endoftext|>"} {"text":"\/* \n * File: virusscan.c\n * \n * Copyright 2013 Heinrich Schuchardt \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file VirusScan.cc\n * @brief Scans files for viruses.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"unistd.h\"\n#include \"VirusScan.h\"\n#include \"Messaging.h\"\n\n\/**\n * @brief Initializes virus scan engine.\n *\/\nVirusScan::VirusScan(Environment * e) {\n int ret;\n\n env = e;\n status = RUNNING;\n engineRefCount = 0;\n pthread_mutex_init(&mutexEngine, NULL);\n pthread_mutex_init(&mutexUpdate, NULL);\n\n ret = cl_init(CL_INIT_DEFAULT);\n if (ret != CL_SUCCESS) {\n std::stringstream msg;\n msg << \"cl_init() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n throw SCANERROR;\n }\n\n \/\/ Create virus scan engine.\n engine = createEngine();\n \/\/ Initialize monitoring of pattern update.\n dbstat_clear();\n\n if (createThread()) {\n Messaging::message(Messaging::ERROR, \"Cannot create thread.\");\n cl_engine_free(engine);\n throw SCANERROR;\n }\n}\n\n\/**\n * @brief Creates a new virus scan engine.\n * \n * @return virus scan engine\n *\/\nstruct cl_engine *VirusScan::createEngine() {\n int ret;\n unsigned int sigs;\n cl_engine *e;\n\n Messaging::message(Messaging::DEBUG, \"Loading virus database\");\n e = cl_engine_new();\n if (e == NULL) {\n Messaging::message(Messaging::ERROR,\n \"Can't create new virus scan engine.\");\n throw SCANERROR;\n }\n \/\/ sigs must be zero before calling cl_load.\n sigs = 0;\n ret = cl_load(cl_retdbdir(), e, &sigs, CL_DB_STDOPT);\n if (ret != CL_SUCCESS) {\n std::stringstream msg;\n msg << \"cl_retdbdir() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n cl_engine_free(e);\n throw SCANERROR;\n } else {\n std::stringstream msg;\n msg << sigs << \" signatures loaded\";\n Messaging::message(Messaging::DEBUG, msg.str());\n }\n if ((ret = cl_engine_compile(e)) != CL_SUCCESS) {\n std::stringstream msg;\n msg << \"cl_engine_compile() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n cl_engine_free(e);\n throw SCANERROR;\n }\n {\n int err;\n time_t db_time;\n struct tm *timeinfo;\n uint version;\n std::stringstream msg;\n char buffer[80];\n\n do {\n version = (uint) cl_engine_get_num(e, CL_ENGINE_DB_VERSION, &err);\n if (err != CL_SUCCESS) {\n break;\n }\n db_time = (time_t) cl_engine_get_num(e, CL_ENGINE_DB_TIME, &err);\n if (err != CL_SUCCESS) {\n break;\n }\n timeinfo = gmtime(&db_time);\n strftime(buffer, sizeof (buffer), \"%F %T UTC\", timeinfo);\n msg << \"ClamAV database version \" << version << \", \" << buffer;\n Messaging::message(Messaging::INFORMATION, msg.str());\n } while (0);\n }\n return e;\n}\n\n\/**\n * Destroys virus scan engine.\n * @param e virus scan engine\n *\/\nvoid VirusScan::destroyEngine(cl_engine * e) {\n int ret;\n ret = cl_engine_free(e);\n if (ret != 0) {\n std::stringstream msg;\n msg << \"cl_engine_free() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n throw SCANERROR;\n }\n}\n\n\/**\n * @brief Gets reference to virus scan engine.\n * \n * @return scan engine\n *\/\nstruct cl_engine * VirusScan::getEngine() {\n struct cl_engine *ret = NULL;\n\n \/\/ Wait for update to complete\n pthread_mutex_lock(&mutexUpdate);\n pthread_mutex_unlock(&mutexUpdate);\n\n pthread_mutex_lock(&mutexEngine);\n ret = engine;\n engineRefCount++;\n pthread_mutex_unlock(&mutexEngine);\n return ret;\n}\n\n\/**\n * @brief Creates a new thread for managing the scan engine.\n * \n * @return success = 0\n *\/\nint VirusScan::createThread() {\n int ret;\n\n if (pthread_create(&updateThread, NULL, updater, this)) {\n ret = 1;\n } else {\n ret = 0;\n }\n return ret;\n}\n\n\/**\n * @brief Checks if database has changed.\n * @returned 0 = unchanged, 1 = changed\n *\/\nint VirusScan::dbstat_check() {\n int ret = 0;\n if (cl_statchkdir(&dbstat) == 1) {\n ret = 1;\n cl_statfree(&dbstat);\n cl_statinidir(cl_retdbdir(), &dbstat);\n }\n return ret;\n}\n\n\/**\n * @brief Clears database status.\n *\/\nvoid VirusScan::dbstat_clear() {\n memset(&dbstat, 0, sizeof (struct cl_stat));\n cl_statinidir(cl_retdbdir(), &dbstat);\n}\n\n\/**\n * @brief Frees database status.\n *\/\nvoid VirusScan::dbstat_free() {\n cl_statfree(&dbstat);\n}\n\n\/**\n * @brief Writes log entry.\n *\n * @param fd file descriptor\n * @param virname name of virus\n *\/\nvoid VirusScan::log_virus_found(const int fd, const char *virname) {\n int path_len;\n char path[PATH_MAX + 1];\n std::stringstream msg;\n\n snprintf(path, sizeof (path), \"\/proc\/self\/fd\/%d\", fd);\n path_len = readlink(path, path, sizeof (path) - 1);\n if (path_len < 0) {\n path_len = 0;\n }\n path[path_len] = '\\0';\n msg << \"Virus \\\"\" << virname << \"\\\" detected in file \\\"\" << path << \"\\\".\";\n Messaging::message(Messaging::ERROR, msg.str());\n}\n\n\/**\n * Decreases the viurs engine reference count.\n *\/\nvoid VirusScan::releaseEngine() {\n pthread_mutex_lock(&mutexEngine);\n engineRefCount--;\n pthread_mutex_unlock(&mutexEngine);\n}\n\n\/**\n * @brief Scans file for virus.\n *\n * @return success\n *\/\nint VirusScan::scan(const int fd) {\n int success = SCANOK;\n int ret;\n const char *virname;\n\n ret = cl_scandesc(fd, &virname, NULL, getEngine(), CL_SCAN_STDOPT);\n switch (ret) {\n case CL_CLEAN:\n success = SCANOK;\n break;\n case CL_VIRUS:\n log_virus_found(fd, virname);\n success = SCANVIRUS;\n break;\n default:\n std::stringstream msg;\n msg << \"cl_scandesc() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n success = SCANOK;\n break;\n }\n releaseEngine();\n return success;\n}\n\n\/**\n * @brief Thread to update engine.\n * \n * @param threadPool thread pool\n * @return return value\n *\/\nvoid * VirusScan::updater(void *virusScan) {\n int count = 0;\n cl_engine *e;\n struct timespec interval = {\n 1,\n 0\n };\n struct timespec interval2 = {\n 0,\n 100000\n };\n VirusScan *vs;\n\n vs = (VirusScan *) virusScan;\n\n for (;;) {\n if (vs->status == STOPPING) {\n break;\n }\n nanosleep(&interval, NULL);\n count++;\n \/\/ Every minute check for virus database updates\n if (count >= 60) {\n if (vs->dbstat_check()) {\n Messaging::message(Messaging::INFORMATION,\n \"ClamAV database update detected.\");\n try {\n \/\/ Create the new engine.\n e = vs->createEngine();\n \/\/ Stop scanning.\n pthread_mutex_lock(&(vs->mutexUpdate));\n \/\/ Wait for all running scans to be finished.\n for (;;) {\n pthread_mutex_lock(&(vs->mutexEngine));\n if (vs->engineRefCount == 0) {\n break;\n }\n pthread_mutex_unlock(&(vs->mutexEngine));\n nanosleep(&interval2, NULL);\n }\n \/\/ Destroy the old engine\n vs->destroyEngine(vs->engine);\n vs->engine = e;\n vs->env->getScanCache()->clear();\n pthread_mutex_unlock(&(vs->mutexEngine));\n Messaging::message(Messaging::INFORMATION,\n \"Using updated ClamAV database.\");\n } catch (Status e) {\n }\n \/\/ Allow scanning.\n pthread_mutex_unlock(&(vs->mutexUpdate));\n }\n }\n }\n vs->status = STOPPED;\n return NULL;\n}\n\n\/**\n * @brief Deletes the virus scanner.\n *\/\nVirusScan::~VirusScan() {\n struct timespec interval = {\n 0,\n 1000000\n };\n\n status = STOPPING;\n do {\n nanosleep(&interval, NULL);\n } while (status == STOPPING);\n\n destroyEngine(engine);\n pthread_mutex_destroy(&mutexUpdate);\n pthread_mutex_destroy(&mutexEngine);\n dbstat_free();\n}\nCorrect usage of update mutex in VirusScan\/* \n * File: virusscan.c\n * \n * Copyright 2013 Heinrich Schuchardt \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file VirusScan.cc\n * @brief Scans files for viruses.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"unistd.h\"\n#include \"VirusScan.h\"\n#include \"Messaging.h\"\n\n\/**\n * @brief Initializes virus scan engine.\n *\/\nVirusScan::VirusScan(Environment * e) {\n int ret;\n\n env = e;\n status = RUNNING;\n engineRefCount = 0;\n pthread_mutex_init(&mutexEngine, NULL);\n pthread_mutex_init(&mutexUpdate, NULL);\n\n ret = cl_init(CL_INIT_DEFAULT);\n if (ret != CL_SUCCESS) {\n std::stringstream msg;\n msg << \"cl_init() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n throw SCANERROR;\n }\n\n \/\/ Create virus scan engine.\n engine = createEngine();\n \/\/ Initialize monitoring of pattern update.\n dbstat_clear();\n\n if (createThread()) {\n Messaging::message(Messaging::ERROR, \"Cannot create thread.\");\n cl_engine_free(engine);\n throw SCANERROR;\n }\n}\n\n\/**\n * @brief Creates a new virus scan engine.\n * \n * @return virus scan engine\n *\/\nstruct cl_engine *VirusScan::createEngine() {\n int ret;\n unsigned int sigs;\n cl_engine *e;\n\n Messaging::message(Messaging::DEBUG, \"Loading virus database\");\n e = cl_engine_new();\n if (e == NULL) {\n Messaging::message(Messaging::ERROR,\n \"Can't create new virus scan engine.\");\n throw SCANERROR;\n }\n \/\/ sigs must be zero before calling cl_load.\n sigs = 0;\n ret = cl_load(cl_retdbdir(), e, &sigs, CL_DB_STDOPT);\n if (ret != CL_SUCCESS) {\n std::stringstream msg;\n msg << \"cl_retdbdir() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n cl_engine_free(e);\n throw SCANERROR;\n } else {\n std::stringstream msg;\n msg << sigs << \" signatures loaded\";\n Messaging::message(Messaging::DEBUG, msg.str());\n }\n if ((ret = cl_engine_compile(e)) != CL_SUCCESS) {\n std::stringstream msg;\n msg << \"cl_engine_compile() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n cl_engine_free(e);\n throw SCANERROR;\n }\n {\n int err;\n time_t db_time;\n struct tm *timeinfo;\n uint version;\n std::stringstream msg;\n char buffer[80];\n\n do {\n version = (uint) cl_engine_get_num(e, CL_ENGINE_DB_VERSION, &err);\n if (err != CL_SUCCESS) {\n break;\n }\n db_time = (time_t) cl_engine_get_num(e, CL_ENGINE_DB_TIME, &err);\n if (err != CL_SUCCESS) {\n break;\n }\n timeinfo = gmtime(&db_time);\n strftime(buffer, sizeof (buffer), \"%F %T UTC\", timeinfo);\n msg << \"ClamAV database version \" << version << \", \" << buffer;\n Messaging::message(Messaging::INFORMATION, msg.str());\n } while (0);\n }\n return e;\n}\n\n\/**\n * Destroys virus scan engine.\n * @param e virus scan engine\n *\/\nvoid VirusScan::destroyEngine(cl_engine * e) {\n int ret;\n ret = cl_engine_free(e);\n if (ret != 0) {\n std::stringstream msg;\n msg << \"cl_engine_free() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n throw SCANERROR;\n }\n}\n\n\/**\n * @brief Gets reference to virus scan engine.\n * \n * @return scan engine\n *\/\nstruct cl_engine * VirusScan::getEngine() {\n struct cl_engine *ret = NULL;\n\n \/\/ Wait for update to complete\n pthread_mutex_lock(&mutexUpdate);\n pthread_mutex_lock(&mutexEngine);\n\n ret = engine;\n \/\/ Increase reference count.\n engineRefCount++;\n\n pthread_mutex_unlock(&mutexEngine);\n pthread_mutex_unlock(&mutexUpdate);\n return ret;\n}\n\n\/**\n * @brief Creates a new thread for managing the scan engine.\n * \n * @return success = 0\n *\/\nint VirusScan::createThread() {\n int ret;\n\n if (pthread_create(&updateThread, NULL, updater, this)) {\n ret = 1;\n } else {\n ret = 0;\n }\n return ret;\n}\n\n\/**\n * @brief Checks if database has changed.\n * @returned 0 = unchanged, 1 = changed\n *\/\nint VirusScan::dbstat_check() {\n int ret = 0;\n if (cl_statchkdir(&dbstat) == 1) {\n ret = 1;\n cl_statfree(&dbstat);\n cl_statinidir(cl_retdbdir(), &dbstat);\n }\n return ret;\n}\n\n\/**\n * @brief Clears database status.\n *\/\nvoid VirusScan::dbstat_clear() {\n memset(&dbstat, 0, sizeof (struct cl_stat));\n cl_statinidir(cl_retdbdir(), &dbstat);\n}\n\n\/**\n * @brief Frees database status.\n *\/\nvoid VirusScan::dbstat_free() {\n cl_statfree(&dbstat);\n}\n\n\/**\n * @brief Writes log entry.\n *\n * @param fd file descriptor\n * @param virname name of virus\n *\/\nvoid VirusScan::log_virus_found(const int fd, const char *virname) {\n int path_len;\n char path[PATH_MAX + 1];\n std::stringstream msg;\n\n snprintf(path, sizeof (path), \"\/proc\/self\/fd\/%d\", fd);\n path_len = readlink(path, path, sizeof (path) - 1);\n if (path_len < 0) {\n path_len = 0;\n }\n path[path_len] = '\\0';\n msg << \"Virus \\\"\" << virname << \"\\\" detected in file \\\"\" << path << \"\\\".\";\n Messaging::message(Messaging::ERROR, msg.str());\n}\n\n\/**\n * Decreases the viurs engine reference count.\n *\/\nvoid VirusScan::releaseEngine() {\n pthread_mutex_lock(&mutexEngine);\n engineRefCount--;\n pthread_mutex_unlock(&mutexEngine);\n}\n\n\/**\n * @brief Scans file for virus.\n *\n * @return success\n *\/\nint VirusScan::scan(const int fd) {\n int success = SCANOK;\n int ret;\n const char *virname;\n\n ret = cl_scandesc(fd, &virname, NULL, getEngine(), CL_SCAN_STDOPT);\n switch (ret) {\n case CL_CLEAN:\n success = SCANOK;\n break;\n case CL_VIRUS:\n log_virus_found(fd, virname);\n success = SCANVIRUS;\n break;\n default:\n std::stringstream msg;\n msg << \"cl_scandesc() error: \" << cl_strerror(ret);\n Messaging::message(Messaging::ERROR, msg.str());\n success = SCANOK;\n break;\n }\n releaseEngine();\n return success;\n}\n\n\/**\n * @brief Thread to update engine.\n * \n * @param threadPool thread pool\n * @return return value\n *\/\nvoid * VirusScan::updater(void *virusScan) {\n int count = 0;\n cl_engine *e;\n struct timespec interval = {\n 1,\n 0\n };\n struct timespec interval2 = {\n 0,\n 100000\n };\n VirusScan *vs;\n\n vs = (VirusScan *) virusScan;\n\n for (;;) {\n if (vs->status == STOPPING) {\n break;\n }\n nanosleep(&interval, NULL);\n count++;\n \/\/ Every minute check for virus database updates\n if (count >= 60) {\n if (vs->dbstat_check()) {\n Messaging::message(Messaging::INFORMATION,\n \"ClamAV database update detected.\");\n try {\n \/\/ Create the new engine.\n e = vs->createEngine();\n \/\/ Stop scanning.\n pthread_mutex_lock(&(vs->mutexUpdate));\n \/\/ Wait for all running scans to be finished.\n for (;;) {\n pthread_mutex_lock(&(vs->mutexEngine));\n if (vs->engineRefCount == 0) {\n break;\n }\n pthread_mutex_unlock(&(vs->mutexEngine));\n nanosleep(&interval2, NULL);\n }\n \/\/ Destroy the old engine\n vs->destroyEngine(vs->engine);\n vs->engine = e;\n vs->env->getScanCache()->clear();\n pthread_mutex_unlock(&(vs->mutexEngine));\n Messaging::message(Messaging::INFORMATION,\n \"Using updated ClamAV database.\");\n } catch (Status e) {\n }\n \/\/ Allow scanning.\n pthread_mutex_unlock(&(vs->mutexUpdate));\n }\n }\n }\n vs->status = STOPPED;\n return NULL;\n}\n\n\/**\n * @brief Deletes the virus scanner.\n *\/\nVirusScan::~VirusScan() {\n struct timespec interval = {\n 0,\n 1000000\n };\n\n status = STOPPING;\n do {\n nanosleep(&interval, NULL);\n } while (status == STOPPING);\n\n destroyEngine(engine);\n pthread_mutex_destroy(&mutexUpdate);\n pthread_mutex_destroy(&mutexEngine);\n dbstat_free();\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright 2011, Filipe David Manana \n * Web: http:\/\/github.com\/fdmanana\/snappy-erlang-nif\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n **\/\n\n#include \n#include \n\n#include \"erl_nif_compat.h\"\n#include \"google-snappy\/snappy.h\"\n#include \"google-snappy\/snappy-sinksource.h\"\n\n#ifdef OTP_R13B03\n#error OTP R13B03 not supported. Upgrade to R13B04 or later.\n#endif\n\n#ifdef __cplusplus\n#define BEGIN_C extern \"C\" {\n#define END_C }\n#else\n#define BEGIN_C\n#define END_C\n#endif\n\n#define SC_PTR(c) reinterpret_cast(c)\n\nclass SnappyNifSink : public snappy::Sink\n{\n public:\n SnappyNifSink(ErlNifEnv* e);\n ~SnappyNifSink();\n \n void Append(const char* data, size_t n);\n char* GetAppendBuffer(size_t len, char* scratch);\n ErlNifBinary& getBin();\n\n private:\n ErlNifEnv* env;\n ErlNifBinary bin;\n size_t length;\n};\n\nSnappyNifSink::SnappyNifSink(ErlNifEnv* e) : env(e), length(0)\n{\n if(!enif_alloc_binary_compat(env, 0, &bin)) {\n env = NULL;\n throw std::bad_alloc();\n }\n}\n\nSnappyNifSink::~SnappyNifSink()\n{\n if(env != NULL) {\n enif_release_binary_compat(env, &bin);\n }\n}\n\nvoid\nSnappyNifSink::Append(const char *data, size_t n)\n{\n if(data != (SC_PTR(bin.data) + length)) {\n memcpy(bin.data + length, data, n);\n }\n length += n;\n}\n\nchar*\nSnappyNifSink::GetAppendBuffer(size_t len, char* scratch)\n{\n size_t sz;\n \n if((length + len) > bin.size) {\n sz = (len * 4) < 8192 ? 8192 : (len * 4);\n\n if(!enif_realloc_binary_compat(env, &bin, bin.size + sz)) {\n throw std::bad_alloc();\n }\n }\n\n return SC_PTR(bin.data) + length;\n}\n\nErlNifBinary&\nSnappyNifSink::getBin()\n{\n if(bin.size > length) {\n if(!enif_realloc_binary_compat(env, &bin, length)) {\n throw std::bad_alloc();\n }\n }\n return bin;\n}\n\n\nBEGIN_C\n\n\nERL_NIF_TERM\nmake_atom(ErlNifEnv* env, const char* name)\n{\n ERL_NIF_TERM ret;\n if(enif_make_existing_atom_compat(env, name, &ret, ERL_NIF_LATIN1)) {\n return ret;\n }\n return enif_make_atom(env, name);\n}\n\n\nERL_NIF_TERM\nmake_ok(ErlNifEnv* env, ERL_NIF_TERM mesg)\n{\n ERL_NIF_TERM ok = make_atom(env, \"ok\");\n return enif_make_tuple2(env, ok, mesg); \n}\n\n\nERL_NIF_TERM\nmake_error(ErlNifEnv* env, const char* mesg)\n{\n ERL_NIF_TERM error = make_atom(env, \"error\");\n return enif_make_tuple2(env, error, make_atom(env, mesg));\n}\n\n\nERL_NIF_TERM\nsnappy_compress(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary input;\n\n if(!enif_inspect_iolist_as_binary(env, argv[0], &input)) {\n return enif_make_badarg(env);\n }\n\n try {\n snappy::ByteArraySource source(SC_PTR(input.data), input.size);\n SnappyNifSink sink(env);\n snappy::Compress(&source, &sink);\n return make_ok(env, enif_make_binary(env, &sink.getBin()));\n } catch(std::bad_alloc e) {\n return make_error(env, \"insufficient_memory\");\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nERL_NIF_TERM\nsnappy_decompress(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary bin;\n ErlNifBinary ret;\n size_t len;\n\n if(!enif_inspect_iolist_as_binary(env, argv[0], &bin)) {\n return enif_make_badarg(env);\n }\n\n try {\n if(!snappy::GetUncompressedLength(SC_PTR(bin.data), bin.size, &len)) {\n return make_error(env, \"data_not_compressed\");\n }\n\n if(!enif_alloc_binary_compat(env, len, &ret)) {\n return make_error(env, \"insufficient_memory\");\n }\n\n if(!snappy::RawUncompress(SC_PTR(bin.data), bin.size,\n SC_PTR(ret.data))) {\n return make_error(env, \"corrupted_data\");\n }\n\n return make_ok(env, enif_make_binary(env, &ret));\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nERL_NIF_TERM\nsnappy_uncompressed_length(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary bin;\n size_t len;\n\n if(!enif_inspect_iolist_as_binary(env, argv[0], &bin)) {\n return enif_make_badarg(env);\n }\n\n try {\n if(!snappy::GetUncompressedLength(SC_PTR(bin.data), bin.size, &len)) {\n return make_error(env, \"data_not_compressed\");\n }\n return make_ok(env, enif_make_ulong(env, len));\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nERL_NIF_TERM\nsnappy_is_valid(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary bin;\n\n if (!enif_inspect_iolist_as_binary(env, argv[0], &bin)) {\n return enif_make_badarg(env);\n }\n\n try {\n if(snappy::IsValidCompressedBuffer(SC_PTR(bin.data), bin.size)) {\n return make_atom(env, \"true\");\n } else {\n return make_atom(env, \"false\");\n }\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nint\non_load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)\n{\n return 0;\n}\n\n\nint\non_reload(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)\n{\n return 0;\n}\n\n\nint\non_upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM info)\n{\n return 0;\n}\n\n\nstatic ErlNifFunc nif_functions[] = {\n {\"compress\", 1, snappy_compress},\n {\"decompress\", 1, snappy_decompress},\n {\"uncompressed_length\", 1, snappy_uncompressed_length},\n {\"is_valid\", 1, snappy_is_valid}\n};\n\n\nERL_NIF_INIT(snappy, nif_functions, &on_load, &on_reload, &on_upgrade, NULL);\n\n\nEND_C\nAdded missing static qualifier, and inline hint, to internal functions\/**\n * Copyright 2011, Filipe David Manana \n * Web: http:\/\/github.com\/fdmanana\/snappy-erlang-nif\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n **\/\n\n#include \n#include \n\n#include \"erl_nif_compat.h\"\n#include \"google-snappy\/snappy.h\"\n#include \"google-snappy\/snappy-sinksource.h\"\n\n#ifdef OTP_R13B03\n#error OTP R13B03 not supported. Upgrade to R13B04 or later.\n#endif\n\n#ifdef __cplusplus\n#define BEGIN_C extern \"C\" {\n#define END_C }\n#else\n#define BEGIN_C\n#define END_C\n#endif\n\n#define SC_PTR(c) reinterpret_cast(c)\n\nclass SnappyNifSink : public snappy::Sink\n{\n public:\n SnappyNifSink(ErlNifEnv* e);\n ~SnappyNifSink();\n \n void Append(const char* data, size_t n);\n char* GetAppendBuffer(size_t len, char* scratch);\n ErlNifBinary& getBin();\n\n private:\n ErlNifEnv* env;\n ErlNifBinary bin;\n size_t length;\n};\n\nSnappyNifSink::SnappyNifSink(ErlNifEnv* e) : env(e), length(0)\n{\n if(!enif_alloc_binary_compat(env, 0, &bin)) {\n env = NULL;\n throw std::bad_alloc();\n }\n}\n\nSnappyNifSink::~SnappyNifSink()\n{\n if(env != NULL) {\n enif_release_binary_compat(env, &bin);\n }\n}\n\nvoid\nSnappyNifSink::Append(const char *data, size_t n)\n{\n if(data != (SC_PTR(bin.data) + length)) {\n memcpy(bin.data + length, data, n);\n }\n length += n;\n}\n\nchar*\nSnappyNifSink::GetAppendBuffer(size_t len, char* scratch)\n{\n size_t sz;\n \n if((length + len) > bin.size) {\n sz = (len * 4) < 8192 ? 8192 : (len * 4);\n\n if(!enif_realloc_binary_compat(env, &bin, bin.size + sz)) {\n throw std::bad_alloc();\n }\n }\n\n return SC_PTR(bin.data) + length;\n}\n\nErlNifBinary&\nSnappyNifSink::getBin()\n{\n if(bin.size > length) {\n if(!enif_realloc_binary_compat(env, &bin, length)) {\n throw std::bad_alloc();\n }\n }\n return bin;\n}\n\n\nBEGIN_C\n\n\nstatic inline ERL_NIF_TERM\nmake_atom(ErlNifEnv* env, const char* name)\n{\n ERL_NIF_TERM ret;\n if(enif_make_existing_atom_compat(env, name, &ret, ERL_NIF_LATIN1)) {\n return ret;\n }\n return enif_make_atom(env, name);\n}\n\n\nstatic inline ERL_NIF_TERM\nmake_ok(ErlNifEnv* env, ERL_NIF_TERM mesg)\n{\n ERL_NIF_TERM ok = make_atom(env, \"ok\");\n return enif_make_tuple2(env, ok, mesg); \n}\n\n\nstatic inline ERL_NIF_TERM\nmake_error(ErlNifEnv* env, const char* mesg)\n{\n ERL_NIF_TERM error = make_atom(env, \"error\");\n return enif_make_tuple2(env, error, make_atom(env, mesg));\n}\n\n\nERL_NIF_TERM\nsnappy_compress(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary input;\n\n if(!enif_inspect_iolist_as_binary(env, argv[0], &input)) {\n return enif_make_badarg(env);\n }\n\n try {\n snappy::ByteArraySource source(SC_PTR(input.data), input.size);\n SnappyNifSink sink(env);\n snappy::Compress(&source, &sink);\n return make_ok(env, enif_make_binary(env, &sink.getBin()));\n } catch(std::bad_alloc e) {\n return make_error(env, \"insufficient_memory\");\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nERL_NIF_TERM\nsnappy_decompress(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary bin;\n ErlNifBinary ret;\n size_t len;\n\n if(!enif_inspect_iolist_as_binary(env, argv[0], &bin)) {\n return enif_make_badarg(env);\n }\n\n try {\n if(!snappy::GetUncompressedLength(SC_PTR(bin.data), bin.size, &len)) {\n return make_error(env, \"data_not_compressed\");\n }\n\n if(!enif_alloc_binary_compat(env, len, &ret)) {\n return make_error(env, \"insufficient_memory\");\n }\n\n if(!snappy::RawUncompress(SC_PTR(bin.data), bin.size,\n SC_PTR(ret.data))) {\n return make_error(env, \"corrupted_data\");\n }\n\n return make_ok(env, enif_make_binary(env, &ret));\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nERL_NIF_TERM\nsnappy_uncompressed_length(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary bin;\n size_t len;\n\n if(!enif_inspect_iolist_as_binary(env, argv[0], &bin)) {\n return enif_make_badarg(env);\n }\n\n try {\n if(!snappy::GetUncompressedLength(SC_PTR(bin.data), bin.size, &len)) {\n return make_error(env, \"data_not_compressed\");\n }\n return make_ok(env, enif_make_ulong(env, len));\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nERL_NIF_TERM\nsnappy_is_valid(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ErlNifBinary bin;\n\n if (!enif_inspect_iolist_as_binary(env, argv[0], &bin)) {\n return enif_make_badarg(env);\n }\n\n try {\n if(snappy::IsValidCompressedBuffer(SC_PTR(bin.data), bin.size)) {\n return make_atom(env, \"true\");\n } else {\n return make_atom(env, \"false\");\n }\n } catch(...) {\n return make_error(env, \"unknown\");\n }\n}\n\n\nint\non_load(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)\n{\n return 0;\n}\n\n\nint\non_reload(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)\n{\n return 0;\n}\n\n\nint\non_upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM info)\n{\n return 0;\n}\n\n\nstatic ErlNifFunc nif_functions[] = {\n {\"compress\", 1, snappy_compress},\n {\"decompress\", 1, snappy_decompress},\n {\"uncompressed_length\", 1, snappy_uncompressed_length},\n {\"is_valid\", 1, snappy_is_valid}\n};\n\n\nERL_NIF_INIT(snappy, nif_functions, &on_load, &on_reload, &on_upgrade, NULL);\n\n\nEND_C\n<|endoftext|>"} {"text":"\/\/ Copyright 2006-2008 the V8 project authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Used for building with external snapshots.\n\n#include \"src\/snapshot.h\"\n\n#include \"src\/serialize.h\"\n#include \"src\/snapshot-source-sink.h\"\n#include \"src\/v8.h\" \/\/ for V8::Initialize\n\n\n#ifndef V8_USE_EXTERNAL_STARTUP_DATA\n#error snapshot-external.cc is used only for the external snapshot build.\n#endif \/\/ V8_USE_EXTERNAL_STARTUP_DATA\n\n\nnamespace v8 {\nnamespace internal {\n\nstatic v8::StartupData external_startup_blob = {NULL, 0};\n\nvoid SetSnapshotFromFile(StartupData* snapshot_blob) {\n DCHECK(snapshot_blob);\n DCHECK(snapshot_blob->data);\n DCHECK(snapshot_blob->raw_size > 0);\n DCHECK(!external_startup_blob.data);\n DCHECK(Snapshot::SnapshotIsValid(snapshot_blob));\n external_startup_blob = *snapshot_blob;\n}\n\n\nconst v8::StartupData Snapshot::SnapshotBlob() { return external_startup_blob; }\n} } \/\/ namespace v8::internal\nProtect access to the external_snapshot_blob global with a lock.\/\/ Copyright 2006-2008 the V8 project authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Used for building with external snapshots.\n\n#include \"src\/snapshot.h\"\n\n#include \"src\/base\/platform\/mutex.h\"\n#include \"src\/serialize.h\"\n#include \"src\/snapshot-source-sink.h\"\n#include \"src\/v8.h\" \/\/ for V8::Initialize\n\n\n#ifndef V8_USE_EXTERNAL_STARTUP_DATA\n#error snapshot-external.cc is used only for the external snapshot build.\n#endif \/\/ V8_USE_EXTERNAL_STARTUP_DATA\n\n\nnamespace v8 {\nnamespace internal {\n\nstatic base::LazyMutex external_startup_data_mutex = LAZY_MUTEX_INITIALIZER;\nstatic v8::StartupData external_startup_blob = {NULL, 0};\n\nvoid SetSnapshotFromFile(StartupData* snapshot_blob) {\n base::LockGuard lock_guard(\n external_startup_data_mutex.Pointer());\n DCHECK(snapshot_blob);\n DCHECK(snapshot_blob->data);\n DCHECK(snapshot_blob->raw_size > 0);\n DCHECK(!external_startup_blob.data);\n DCHECK(Snapshot::SnapshotIsValid(snapshot_blob));\n external_startup_blob = *snapshot_blob;\n}\n\n\nconst v8::StartupData Snapshot::SnapshotBlob() {\n base::LockGuard lock_guard(\n external_startup_data_mutex.Pointer());\n return external_startup_blob;\n}\n} } \/\/ namespace v8::internal\n<|endoftext|>"} {"text":"\/**\n\tCopyright (c) 2009 James Wynn (james@jameswynn.com)\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy\n\tof this software and associated documentation files (the \"Software\"), to deal\n\tin the Software without restriction, including without limitation the rights\n\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the Software is\n\tfurnished to do so, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in\n\tall copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\tTHE SOFTWARE.\n\n\tJames Wynn james@jameswynn.com\n*\/\n\n#include \n\n#if FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_LINUX\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define BUFF_SIZE ((sizeof(struct inotify_event)+FILENAME_MAX)*1024)\n\nnamespace FW\n{\n\n\tstruct WatchStruct\n\t{\n\t\tWatchID mWatchID;\n\t\tString mDirName;\n\t\tFileWatchListener* mListener;\t\t\n\t};\n\n\t\/\/--------\n\tFileWatcherLinux::FileWatcherLinux()\n\t{\n\t\tmFD = inotify_init();\n\t\tif (mFD < 0)\n\t\t\tfprintf (stderr, \"Error: %s\\n\", strerror(errno));\n\t\t\n\t\tmTimeOut.tv_sec = 0;\n\t\tmTimeOut.tv_usec = 0;\n\t \t\t\n\t\tFD_ZERO(&mDescriptorSet);\n\t}\n\n\t\/\/--------\n\tFileWatcherLinux::~FileWatcherLinux()\n\t{\n\t\tWatchMap::iterator iter = mWatches.begin();\n\t\tWatchMap::iterator end = mWatches.end();\n\t\tfor(; iter != end; ++iter)\n\t\t{\n\t\t\tdelete iter->second;\n\t\t}\n\t\tmWatches.clear();\n\t}\n\n\t\/\/--------\n\tWatchID FileWatcherLinux::addWatch(const String& directory, FileWatchListener* watcher, bool recursive)\n\t{\n\t\tint wd = inotify_add_watch (mFD, directory.c_str(), \n\t\t\tIN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_MOVED_FROM | IN_DELETE);\n\t\tif (wd < 0)\n\t\t{\n\t\t\tif(errno == ENOENT)\n\t\t\t\tthrow FileNotFoundException(directory);\n\t\t\telse\n\t\t\t\tthrow Exception(strerror(errno));\n\n\/\/\t\t\tfprintf (stderr, \"Error: %s\\n\", strerror(errno));\n\/\/\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tWatchStruct* pWatch = new WatchStruct();\n\t\tpWatch->mListener = watcher;\n\t\tpWatch->mWatchID = wd;\n\t\tpWatch->mDirName = directory;\n\t\t\n\t\tmWatches.insert(std::make_pair(wd, pWatch));\n\t\n\t\treturn wd;\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::removeWatch(const String& directory)\n\t{\n\t\tWatchMap::iterator iter = mWatches.begin();\n\t\tWatchMap::iterator end = mWatches.end();\n\t\tfor(; iter != end; ++iter)\n\t\t{\n\t\t\tif(directory == iter->second->mDirName)\n\t\t\t{\n\t\t\t\tremoveWatch(iter->first);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::removeWatch(WatchID watchid)\n\t{\n\t\tWatchMap::iterator iter = mWatches.find(watchid);\n\n\t\tif(iter == mWatches.end())\n\t\t\treturn;\n\n\t\tWatchStruct* watch = iter->second;\n\t\tmWatches.erase(iter);\n\t\n\t\tinotify_rm_watch(mFD, watchid);\n\t\t\n\t\tdelete watch;\n\t\twatch = 0;\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::update()\n\t{\n\t\tFD_SET(mFD, &mDescriptorSet);\n\n\t\tint ret = select(mFD + 1, &mDescriptorSet, NULL, NULL, &mTimeOut);\n\t\tif(ret < 0)\n\t\t{\n\t\t\tperror(\"select\");\n\t\t}\n\t\telse if(FD_ISSET(mFD, &mDescriptorSet))\n\t\t{\n\t\t\tssize_t len, i = 0;\n\t\t\tchar action[81+FILENAME_MAX] = {0};\n\t\t\tchar buff[BUFF_SIZE] = {0};\n\n\t\t\tlen = read (mFD, buff, BUFF_SIZE);\n\t\t \n\t\t\twhile (i < len)\n\t\t\t{\n\t\t\t\tstruct inotify_event *pevent = (struct inotify_event *)&buff[i];\n\n\t\t\t\tWatchStruct* watch = mWatches[pevent->wd];\n\t\t\t\thandleAction(watch, pevent->name, pevent->mask);\n\t\t\t\ti += sizeof(struct inotify_event) + pevent->len;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::handleAction(WatchStruct* watch, const String& filename, unsigned long action)\n\t{\n\t\tif(!watch->mListener)\n\t\t\treturn;\n\n\t\tif(IN_CLOSE_WRITE & action)\n\t\t{\n\t\t\twatch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename,\n\t\t\t\t\t\t\t\tActions::Modified);\n\t\t}\n\t\tif(IN_MOVED_TO & action || IN_CREATE & action)\n\t\t{\n\t\t\twatch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename,\n\t\t\t\t\t\t\t\tActions::Add);\n\t\t}\n\t\tif(IN_MOVED_FROM & action || IN_DELETE & action)\n\t\t{\n\t\t\twatch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename,\n\t\t\t\t\t\t\t\tActions::Delete);\n\t\t}\n\t}\n\n};\/\/namespace FW\n\n#endif\/\/FILEWATCHER_PLATFORM_LINUX\nfixed missing include on linux\/**\n\tCopyright (c) 2009 James Wynn (james@jameswynn.com)\n\n\tPermission is hereby granted, free of charge, to any person obtaining a copy\n\tof this software and associated documentation files (the \"Software\"), to deal\n\tin the Software without restriction, including without limitation the rights\n\tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the Software is\n\tfurnished to do so, subject to the following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in\n\tall copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\tTHE SOFTWARE.\n\n\tJames Wynn james@jameswynn.com\n*\/\n\n#include \n\n#if FILEWATCHER_PLATFORM == FILEWATCHER_PLATFORM_LINUX\n\n#include \n#include \n#include \n#include \n#include \n#include \/\/ read\n#include \n\n#define BUFF_SIZE ((sizeof(struct inotify_event)+FILENAME_MAX)*1024)\n\nnamespace FW\n{\n\n\tstruct WatchStruct\n\t{\n\t\tWatchID mWatchID;\n\t\tString mDirName;\n\t\tFileWatchListener* mListener;\t\t\n\t};\n\n\t\/\/--------\n\tFileWatcherLinux::FileWatcherLinux()\n\t{\n\t\tmFD = inotify_init();\n\t\tif (mFD < 0)\n\t\t\tfprintf (stderr, \"Error: %s\\n\", strerror(errno));\n\t\t\n\t\tmTimeOut.tv_sec = 0;\n\t\tmTimeOut.tv_usec = 0;\n\t \t\t\n\t\tFD_ZERO(&mDescriptorSet);\n\t}\n\n\t\/\/--------\n\tFileWatcherLinux::~FileWatcherLinux()\n\t{\n\t\tWatchMap::iterator iter = mWatches.begin();\n\t\tWatchMap::iterator end = mWatches.end();\n\t\tfor(; iter != end; ++iter)\n\t\t{\n\t\t\tdelete iter->second;\n\t\t}\n\t\tmWatches.clear();\n\t}\n\n\t\/\/--------\n\tWatchID FileWatcherLinux::addWatch(const String& directory, FileWatchListener* watcher, bool recursive)\n\t{\n\t\tint wd = inotify_add_watch (mFD, directory.c_str(), \n\t\t\tIN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_MOVED_FROM | IN_DELETE);\n\t\tif (wd < 0)\n\t\t{\n\t\t\tif(errno == ENOENT)\n\t\t\t\tthrow FileNotFoundException(directory);\n\t\t\telse\n\t\t\t\tthrow Exception(strerror(errno));\n\n\/\/\t\t\tfprintf (stderr, \"Error: %s\\n\", strerror(errno));\n\/\/\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tWatchStruct* pWatch = new WatchStruct();\n\t\tpWatch->mListener = watcher;\n\t\tpWatch->mWatchID = wd;\n\t\tpWatch->mDirName = directory;\n\t\t\n\t\tmWatches.insert(std::make_pair(wd, pWatch));\n\t\n\t\treturn wd;\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::removeWatch(const String& directory)\n\t{\n\t\tWatchMap::iterator iter = mWatches.begin();\n\t\tWatchMap::iterator end = mWatches.end();\n\t\tfor(; iter != end; ++iter)\n\t\t{\n\t\t\tif(directory == iter->second->mDirName)\n\t\t\t{\n\t\t\t\tremoveWatch(iter->first);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::removeWatch(WatchID watchid)\n\t{\n\t\tWatchMap::iterator iter = mWatches.find(watchid);\n\n\t\tif(iter == mWatches.end())\n\t\t\treturn;\n\n\t\tWatchStruct* watch = iter->second;\n\t\tmWatches.erase(iter);\n\t\n\t\tinotify_rm_watch(mFD, watchid);\n\t\t\n\t\tdelete watch;\n\t\twatch = 0;\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::update()\n\t{\n\t\tFD_SET(mFD, &mDescriptorSet);\n\n\t\tint ret = select(mFD + 1, &mDescriptorSet, NULL, NULL, &mTimeOut);\n\t\tif(ret < 0)\n\t\t{\n\t\t\tperror(\"select\");\n\t\t}\n\t\telse if(FD_ISSET(mFD, &mDescriptorSet))\n\t\t{\n\t\t\tssize_t len, i = 0;\n\t\t\tchar action[81+FILENAME_MAX] = {0};\n\t\t\tchar buff[BUFF_SIZE] = {0};\n\n\t\t\tlen = read (mFD, buff, BUFF_SIZE);\n\t\t \n\t\t\twhile (i < len)\n\t\t\t{\n\t\t\t\tstruct inotify_event *pevent = (struct inotify_event *)&buff[i];\n\n\t\t\t\tWatchStruct* watch = mWatches[pevent->wd];\n\t\t\t\thandleAction(watch, pevent->name, pevent->mask);\n\t\t\t\ti += sizeof(struct inotify_event) + pevent->len;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/--------\n\tvoid FileWatcherLinux::handleAction(WatchStruct* watch, const String& filename, unsigned long action)\n\t{\n\t\tif(!watch->mListener)\n\t\t\treturn;\n\n\t\tif(IN_CLOSE_WRITE & action)\n\t\t{\n\t\t\twatch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename,\n\t\t\t\t\t\t\t\tActions::Modified);\n\t\t}\n\t\tif(IN_MOVED_TO & action || IN_CREATE & action)\n\t\t{\n\t\t\twatch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename,\n\t\t\t\t\t\t\t\tActions::Add);\n\t\t}\n\t\tif(IN_MOVED_FROM & action || IN_DELETE & action)\n\t\t{\n\t\t\twatch->mListener->handleFileAction(watch->mWatchID, watch->mDirName, filename,\n\t\t\t\t\t\t\t\tActions::Delete);\n\t\t}\n\t}\n\n};\/\/namespace FW\n\n#endif\/\/FILEWATCHER_PLATFORM_LINUX\n<|endoftext|>"} {"text":"#include \"main.hpp\"\n\n#include \"ParticleRenderer.hpp\"\n#include \"Timeline.hpp\"\n\nvoid ParticleRenderer::reset() {\n graphicsPipeline.destroy();\n uniforms.clear();\n}\n\nvoid ParticleRenderer::setTimeline(std::unique_ptr _timeline) {\n reset();\n\n timeline = std::move(_timeline);\n\n state.clock.setPeriod(timeline->getPeriod());\n\n std::vector uniforms;\n ShaderBuilder vertexShader, fragmentShader;\n\n uniforms.emplace_back(\"invImageAspectRatio\", GLSLType::Float,\n [](const RenderProps &props) {\n return UniformValue((float)props.webcam_height \/ props.webcam_width);\n });\n uniforms.emplace_back(\"invScreenAspectRatio\", GLSLType::Float,\n [](const RenderProps &props) {\n return UniformValue((float)props.screen_height \/ props.screen_width);\n });\n uniforms.emplace_back(\"viewProjectionMatrix\", GLSLType::Mat4,\n [](const RenderProps &props) {\n const auto aspect = (float)props.screen_width \/ props.screen_height;\n const auto underscan = 1 - ((float)props.screen_height \/ props.screen_width) \/\n ((float)props.webcam_height \/ props.webcam_width);\n return UniformValue(glm::mat4(\n 2.f \/ aspect, 0.f, 0.f, 0.f,\n 0.f, 2.f, 0.f, 0.f,\n 0.f, 0.f, 0.f, 0.f,\n underscan - 1.f, -1.f, 0.f, 1.f\n ));\n });\n uniforms.emplace_back(\"invViewProjectionMatrix\", GLSLType::Mat4,\n [](const RenderProps &props) {\n const auto aspect = (float)props.screen_width \/ props.screen_height;\n const auto underscan = 1 - ((float)props.screen_height \/ props.screen_width) \/\n ((float)props.webcam_height \/ props.webcam_width);\n return UniformValue(glm::mat4(\n .5f * aspect, 0.f, 0.f, 0.f,\n 0.f, .5f, 0.f, 0.f,\n 0.f, 0.f, 0.f, 0.f,\n (-.5f * (underscan - 1.f)) * aspect, .5f, 0.f, 1.f\n ));\n });\n uniforms.emplace_back(\"particleSize\", GLSLType::Float,\n [](const RenderProps &props) {\n \/\/TODO: particleScaling config\n return UniformValue(((float)props.screen_height \/ props.webcam_height) * 2 \/* * particleScaling*\/);\n });\n uniforms.emplace_back(\"globalTime\", GLSLType::Float,\n [](const RenderProps &props) {\n return UniformValue(props.state.clock.getTime());\n });\n\n vertexShader.appendIn(\"texcoord\", GLSLType::Vec2);\n vertexShader.appendIn(\"rgb\", GLSLType::Vec3);\n vertexShader.appendIn(\"hsv\", GLSLType::Vec3);\n\n vertexShader.appendOut(\"color\", GLSLType::Vec3);\n\n vertexShader.appendGlobal(\"PI\", GLSLType::Float, std::to_string(PI));\n\n vertexShader.appendFunction(R\"glsl(\n vec2 getDirectionVector(float angle) {\n return vec2(cos(angle), sin(angle));\n }\n )glsl\");\n\n fragmentShader.appendIn(\"color\", GLSLType::Vec3);\n\n fragmentShader.appendOut(\"frag_color\", GLSLType::Vec4);\n\n vertexShader.appendMainBody(R\"glsl(\n vec3 initialPosition = vec3(texcoord, 0);\n initialPosition.y *= invImageAspectRatio;\n float pointSize = max(particleSize, 0.);\n\n vec3 position = initialPosition;\n )glsl\");\n\n fragmentShader.appendMainBody(R\"glsl(\n float v = pow(max(1. - 2. * length(gl_PointCoord - vec2(.5)), 0.), 1.5);\n )glsl\");\n\n unsigned instanceId = 0;\n timeline->forEachInstance([&](const IEffect &i) {\n Uniforms instanceUniforms(uniforms, instanceId++);\n vertexShader.appendMainBody((\"if(\" + std::to_string(i.getTimeBegin()) +\n \"<= globalTime && globalTime <=\" +\n std::to_string(i.getTimeEnd()) + \") {\")\n .c_str());\n#if 1\n vertexShader.appendMainBody(\"\\n#line 0\\n\");\n fragmentShader.appendMainBody(\"\\n#line 0\\n\");\n#endif\n i.registerEffect(instanceUniforms, vertexShader, fragmentShader);\n vertexShader.appendMainBody(\"}\");\n });\n\n vertexShader.appendMainBody(R\"glsl(\n color = rgb;\n gl_PointSize = pointSize;\n gl_Position = viewProjectionMatrix * vec4(position, 1.);\n )glsl\");\n\n \/\/ TODO: different overlap modes\n fragmentShader.appendMainBody(R\"glsl(\n frag_color = vec4(color * v, 1);\n )glsl\");\n\n for (const auto &u : uniforms) {\n vertexShader.appendUniform(u);\n fragmentShader.appendUniform(u);\n }\n\n const auto vertexShaderSource = vertexShader.assemble();\n const auto fragmentShaderSource = fragmentShader.assemble();\n\n std::cout << vertexShaderSource << \"\\n\" << fragmentShaderSource << \"\\n\";\n\n graphicsPipeline.create(vertexShaderSource.c_str(),\n fragmentShaderSource.c_str());\n\n for (const auto &u : uniforms) {\n UniformElement newElement;\n newElement.location = graphicsPipeline.getUniformLocation(u.name.c_str());\n newElement.value = u.value;\n this->uniforms.push_back(newElement);\n }\n}\n\nvoid ParticleRenderer::update(float dt) {\n state.clock.frame(dt);\n}\n\nvoid ParticleRenderer::render(const RendererParameters ¶meters) {\n RenderProps props(parameters, state);\n\n graphicsPipeline.bind();\n\n for (const auto &uniform : uniforms) {\n const auto value = uniform.value(props);\n switch (value.type) {\n case GLSLType::Float:\n glUniform1fv(uniform.location, 1, &value.data.f);\n break;\n case GLSLType::Vec2:\n glUniform2fv(uniform.location, 1, &value.data.v2[0]);\n break;\n case GLSLType::Vec3:\n glUniform3fv(uniform.location, 1, &value.data.v3[0]);\n break;\n case GLSLType::Vec4:\n glUniform4fv(uniform.location, 1, &value.data.v4[0]);\n break;\n case GLSLType::Mat4:\n glUniformMatrix4fv(uniform.location, 1, GL_FALSE, &value.data.m4[0][0]);\n break;\n }\n }\n\n parameters.particle_buffer.draw();\n}\nAdd clang-format off comments to matrix definitions#include \"main.hpp\"\n\n#include \"ParticleRenderer.hpp\"\n#include \"Timeline.hpp\"\n\nvoid ParticleRenderer::reset() {\n graphicsPipeline.destroy();\n uniforms.clear();\n}\n\nvoid ParticleRenderer::setTimeline(std::unique_ptr _timeline) {\n reset();\n\n timeline = std::move(_timeline);\n\n state.clock.setPeriod(timeline->getPeriod());\n\n std::vector uniforms;\n ShaderBuilder vertexShader, fragmentShader;\n\n uniforms.emplace_back(\"invImageAspectRatio\", GLSLType::Float,\n [](const RenderProps &props) {\n return UniformValue((float)props.webcam_height \/ props.webcam_width);\n });\n uniforms.emplace_back(\"invScreenAspectRatio\", GLSLType::Float,\n [](const RenderProps &props) {\n return UniformValue((float)props.screen_height \/ props.screen_width);\n });\n uniforms.emplace_back(\"viewProjectionMatrix\", GLSLType::Mat4,\n [](const RenderProps &props) {\n const auto aspect = (float)props.screen_width \/ props.screen_height;\n const auto underscan = 1 - ((float)props.screen_height \/ props.screen_width) \/\n ((float)props.webcam_height \/ props.webcam_width);\n \/\/ clang-format off\n return UniformValue(glm::mat4(\n 2.f \/ aspect, 0.f, 0.f, 0.f,\n 0.f, 2.f, 0.f, 0.f,\n 0.f, 0.f, 0.f, 0.f,\n underscan - 1.f, -1.f, 0.f, 1.f\n ));\n \/\/ clang-format on\n });\n uniforms.emplace_back(\"invViewProjectionMatrix\", GLSLType::Mat4,\n [](const RenderProps &props) {\n const auto aspect = (float)props.screen_width \/ props.screen_height;\n const auto underscan = 1 - ((float)props.screen_height \/ props.screen_width) \/\n ((float)props.webcam_height \/ props.webcam_width);\n \/\/ clang-format off\n return UniformValue(glm::mat4(\n .5f * aspect, 0.f, 0.f, 0.f,\n 0.f, .5f, 0.f, 0.f,\n 0.f, 0.f, 0.f, 0.f,\n (-.5f * (underscan - 1.f)) * aspect, .5f, 0.f, 1.f\n ));\n \/\/ clang-format on\n });\n uniforms.emplace_back(\"particleSize\", GLSLType::Float,\n [](const RenderProps &props) {\n \/\/TODO: particleScaling config\n return UniformValue(((float)props.screen_height \/ props.webcam_height) * 2 \/* * particleScaling*\/);\n });\n uniforms.emplace_back(\"globalTime\", GLSLType::Float,\n [](const RenderProps &props) {\n return UniformValue(props.state.clock.getTime());\n });\n\n vertexShader.appendIn(\"texcoord\", GLSLType::Vec2);\n vertexShader.appendIn(\"rgb\", GLSLType::Vec3);\n vertexShader.appendIn(\"hsv\", GLSLType::Vec3);\n\n vertexShader.appendOut(\"color\", GLSLType::Vec3);\n\n vertexShader.appendGlobal(\"PI\", GLSLType::Float, std::to_string(PI));\n\n vertexShader.appendFunction(R\"glsl(\n vec2 getDirectionVector(float angle) {\n return vec2(cos(angle), sin(angle));\n }\n )glsl\");\n\n fragmentShader.appendIn(\"color\", GLSLType::Vec3);\n\n fragmentShader.appendOut(\"frag_color\", GLSLType::Vec4);\n\n vertexShader.appendMainBody(R\"glsl(\n vec3 initialPosition = vec3(texcoord, 0);\n initialPosition.y *= invImageAspectRatio;\n float pointSize = max(particleSize, 0.);\n\n vec3 position = initialPosition;\n )glsl\");\n\n fragmentShader.appendMainBody(R\"glsl(\n float v = pow(max(1. - 2. * length(gl_PointCoord - vec2(.5)), 0.), 1.5);\n )glsl\");\n\n unsigned instanceId = 0;\n timeline->forEachInstance([&](const IEffect &i) {\n Uniforms instanceUniforms(uniforms, instanceId++);\n vertexShader.appendMainBody((\"if(\" + std::to_string(i.getTimeBegin()) +\n \"<= globalTime && globalTime <=\" +\n std::to_string(i.getTimeEnd()) + \") {\")\n .c_str());\n#if 1\n vertexShader.appendMainBody(\"\\n#line 0\\n\");\n fragmentShader.appendMainBody(\"\\n#line 0\\n\");\n#endif\n i.registerEffect(instanceUniforms, vertexShader, fragmentShader);\n vertexShader.appendMainBody(\"}\");\n });\n\n vertexShader.appendMainBody(R\"glsl(\n color = rgb;\n gl_PointSize = pointSize;\n gl_Position = viewProjectionMatrix * vec4(position, 1.);\n )glsl\");\n\n \/\/ TODO: different overlap modes\n fragmentShader.appendMainBody(R\"glsl(\n frag_color = vec4(color * v, 1);\n )glsl\");\n\n for (const auto &u : uniforms) {\n vertexShader.appendUniform(u);\n fragmentShader.appendUniform(u);\n }\n\n const auto vertexShaderSource = vertexShader.assemble();\n const auto fragmentShaderSource = fragmentShader.assemble();\n\n std::cout << vertexShaderSource << \"\\n\" << fragmentShaderSource << \"\\n\";\n\n graphicsPipeline.create(vertexShaderSource.c_str(),\n fragmentShaderSource.c_str());\n\n for (const auto &u : uniforms) {\n UniformElement newElement;\n newElement.location = graphicsPipeline.getUniformLocation(u.name.c_str());\n newElement.value = u.value;\n this->uniforms.push_back(newElement);\n }\n}\n\nvoid ParticleRenderer::update(float dt) {\n state.clock.frame(dt);\n}\n\nvoid ParticleRenderer::render(const RendererParameters ¶meters) {\n RenderProps props(parameters, state);\n\n graphicsPipeline.bind();\n\n for (const auto &uniform : uniforms) {\n const auto value = uniform.value(props);\n switch (value.type) {\n case GLSLType::Float:\n glUniform1fv(uniform.location, 1, &value.data.f);\n break;\n case GLSLType::Vec2:\n glUniform2fv(uniform.location, 1, &value.data.v2[0]);\n break;\n case GLSLType::Vec3:\n glUniform3fv(uniform.location, 1, &value.data.v3[0]);\n break;\n case GLSLType::Vec4:\n glUniform4fv(uniform.location, 1, &value.data.v4[0]);\n break;\n case GLSLType::Mat4:\n glUniformMatrix4fv(uniform.location, 1, GL_FALSE, &value.data.m4[0][0]);\n break;\n }\n }\n\n parameters.particle_buffer.draw();\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * c7a\/api\/reduce_node.hpp\n *\n * DIANode for a reduce operation. Performs the actual reduce operation\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_REDUCE_NODE_HEADER\n#define C7A_API_REDUCE_NODE_HEADER\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace c7a {\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * A DIANode which performs a Reduce operation. Reduce groups the elements in a\n * DIA by their key and reduces every key bucket to a single element each. The\n * ReduceNode stores the key_extractor and the reduce_function UDFs. The\n * chainable LOps ahead of the Reduce operation are stored in the Stack. The\n * ReduceNode has the type Output, which is the result type of the\n * reduce_function.\n *\n * \\tparam Input Input type of the Reduce operation\n * \\tparam Output Output type of the Reduce operation\n * \\tparam Stack Function stack, which contains the chained lambdas between the last and this DIANode.\n * \\tparam KeyExtractor Type of the key_extractor function.\n * \\tparam ReduceFunction Type of the reduce_function\n *\/\ntemplate \nclass ReduceNode : public DOpNode\n{\n static const bool debug = true;\n\n typedef DOpNode Super;\n\n using reduce_arg_t = typename FunctionTraits::template arg<0>;\n\n using Super::context_;\n using Super::data_id_;\n\npublic:\n \/*!\n * Constructor for a ReduceNode. Sets the DataManager, parent, stack,\n * key_extractor and reduce_function.\n *\n * \\param ctx Reference to Context, which holds references to data and network.\n * \\param parent Parent DIANode.\n * \\param stack Function chain with all lambdas between the parent and this node\n * \\param key_extractor Key extractor function\n * \\param reduce_function Reduce function\n *\/\n ReduceNode(Context& ctx,\n DIANode* parent,\n Stack& stack,\n KeyExtractor key_extractor,\n ReduceFunction reduce_function)\n : DOpNode(ctx, { parent }),\n local_stack_(stack),\n key_extractor_(key_extractor),\n reduce_function_(reduce_function),\n channel_id_(ctx.get_data_manager().AllocateNetworkChannel()),\n reduce_pre_table_(ctx.number_worker(), key_extractor, reduce_function_, ctx.get_data_manager().template GetNetworkEmitters(channel_id_))\n {\n \/\/ Hook PreOp\n auto pre_op_fn = [ = ](reduce_arg_t input) {\n PreOp(input);\n };\n auto lop_chain = local_stack_.push(pre_op_fn).emit();\n\n parent->RegisterChild(lop_chain);\n }\n\n \/\/! Virtual destructor for a ReduceNode.\n virtual ~ReduceNode() { }\n\n \/*!\n * Actually executes the reduce operation. Uses the member functions PreOp,\n * MainOp and PostOp.\n *\/\n void execute() override {\n \/\/Flush hash table to send data before main op begins\n reduce_pre_table_.Flush();\n reduce_pre_table_.CloseEmitter();\n\n MainOp();\n }\n\n \/*!\n * Produces a function stack, which only contains the PostOp function.\n * \\return PostOp function stack\n *\/\n auto ProduceStack() {\n \/\/ Hook PostOp\n auto post_op_fn = [ = ](Output elem, std::function emit_func) {\n return PostOp(elem, emit_func);\n };\n\n FunctionStack<> stack;\n return stack.push(post_op_fn);\n }\n\n \/*!\n * Returns \"[ReduceNode]\" and its id as a string.\n * \\return \"[ReduceNode]\"\n *\/\n std::string ToString() override {\n return \"[ReduceNode] Id: \" + std::to_string(data_id_);\n }\n\nprivate:\n \/\/! Local stack\n Stack local_stack_;\n \/\/!Key extractor function\n KeyExtractor key_extractor_;\n \/\/!Reduce function\n ReduceFunction reduce_function_;\n\n data::ChannelId channel_id_;\n\n core::ReducePreTable > reduce_pre_table_;\n\n \/\/! Locally hash elements of the current DIA onto buckets and reduce each\n \/\/! bucket to a single value, afterwards send data to another worker given\n \/\/! by the shuffle algorithm.\n void PreOp(reduce_arg_t input) {\n reduce_pre_table_.Insert(input);\n }\n\n \/\/!Recieve elements from other workers.\n auto MainOp() {\n std::function print =\n [](Output elem) {\n LOG << elem.first << \" \" << elem.second;\n };\n\n using ReduceTable\n = core::ReducePostTable >;\n\n ReduceTable table(key_extractor_, reduce_function_, DIANode::callbacks());\n\n auto it = context_.get_data_manager().template GetRemoteBlocks(channel_id_);\n\n while (!it.IsClosed()) {\n it.WaitForMore();\n while (it.HasNext()) {\n table.Insert(it.Next());\n }\n }\n\n table.Flush();\n }\n\n \/\/! Hash recieved elements onto buckets and reduce each bucket to a single value.\n void PostOp(Output input, std::function emit_func) {\n emit_func(input);\n }\n};\n\n\/\/! \\}\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_API_REDUCE_NODE_HEADER\n\n\/******************************************************************************\/\nadd comment on WriteNode\/*******************************************************************************\n * c7a\/api\/reduce_node.hpp\n *\n * DIANode for a reduce operation. Performs the actual reduce operation\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_REDUCE_NODE_HEADER\n#define C7A_API_REDUCE_NODE_HEADER\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace c7a {\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * A DIANode which performs a Reduce operation. Reduce groups the elements in a\n * DIA by their key and reduces every key bucket to a single element each. The\n * ReduceNode stores the key_extractor and the reduce_function UDFs. The\n * chainable LOps ahead of the Reduce operation are stored in the Stack. The\n * ReduceNode has the type Output, which is the result type of the\n * reduce_function.\n *\n * \\tparam Input Input type of the Reduce operation\n * \\tparam Output Output type of the Reduce operation\n * \\tparam Stack Function stack, which contains the chained lambdas between the last and this DIANode.\n * \\tparam KeyExtractor Type of the key_extractor function.\n * \\tparam ReduceFunction Type of the reduce_function\n *\/\ntemplate \nclass ReduceNode : public DOpNode\n{\n static const bool debug = true;\n\n typedef DOpNode Super;\n\n using reduce_arg_t = typename FunctionTraits::template arg<0>;\n\n using Super::context_;\n using Super::data_id_;\n\npublic:\n \/*!\n * Constructor for a ReduceNode. Sets the DataManager, parent, stack,\n * key_extractor and reduce_function.\n *\n * \\param ctx Reference to Context, which holds references to data and network.\n * \\param parent Parent DIANode.\n * \\param stack Function chain with all lambdas between the parent and this node\n * \\param key_extractor Key extractor function\n * \\param reduce_function Reduce function\n *\/\n ReduceNode(Context& ctx,\n DIANode* parent,\n Stack& stack,\n KeyExtractor key_extractor,\n ReduceFunction reduce_function)\n : DOpNode(ctx, { parent }),\n local_stack_(stack),\n key_extractor_(key_extractor),\n reduce_function_(reduce_function),\n channel_id_(ctx.get_data_manager().AllocateNetworkChannel()),\n reduce_pre_table_(ctx.number_worker(), key_extractor, reduce_function_, ctx.get_data_manager().template GetNetworkEmitters(channel_id_))\n {\n \/\/ Hook PreOp\n auto pre_op_fn = [ = ](reduce_arg_t input) {\n PreOp(input);\n };\n auto lop_chain = local_stack_.push(pre_op_fn).emit();\n\n parent->RegisterChild(lop_chain);\n }\n\n \/\/! Virtual destructor for a ReduceNode.\n virtual ~ReduceNode() { }\n\n \/*!\n * Actually executes the reduce operation. Uses the member functions PreOp,\n * MainOp and PostOp.\n *\/\n void execute() override {\n LOG << ToString() << \" flushing pre tables\";\n \/\/Flush hash table to send data before main op begins\n reduce_pre_table_.Flush();\n reduce_pre_table_.CloseEmitter();\n\n LOG << ToString() << \" running main op\";\n MainOp();\n }\n\n \/*!\n * Produces a function stack, which only contains the PostOp function.\n * \\return PostOp function stack\n *\/\n auto ProduceStack() {\n \/\/ Hook PostOp\n auto post_op_fn = [ = ](Output elem, std::function emit_func) {\n return PostOp(elem, emit_func);\n };\n\n FunctionStack<> stack;\n return stack.push(post_op_fn);\n }\n\n \/*!\n * Returns \"[ReduceNode]\" and its id as a string.\n * \\return \"[ReduceNode]\"\n *\/\n std::string ToString() override {\n return \"[ReduceNode] Id: \" + std::to_string(data_id_);\n }\n\nprivate:\n \/\/! Local stack\n Stack local_stack_;\n \/\/!Key extractor function\n KeyExtractor key_extractor_;\n \/\/!Reduce function\n ReduceFunction reduce_function_;\n\n data::ChannelId channel_id_;\n\n core::ReducePreTable > reduce_pre_table_;\n\n \/\/! Locally hash elements of the current DIA onto buckets and reduce each\n \/\/! bucket to a single value, afterwards send data to another worker given\n \/\/! by the shuffle algorithm.\n void PreOp(reduce_arg_t input) {\n reduce_pre_table_.Insert(input);\n }\n\n \/\/!Recieve elements from other workers.\n auto MainOp() {\n std::function print =\n [](Output elem) {\n LOG << elem.first << \" \" << elem.second;\n };\n\n using ReduceTable\n = core::ReducePostTable >;\n\n ReduceTable table(key_extractor_, reduce_function_, DIANode::callbacks());\n\n auto it = context_.get_data_manager().template GetRemoteBlocks(channel_id_);\n\n while (!it.IsClosed()) {\n it.WaitForMore();\n while (it.HasNext()) {\n table.Insert(it.Next());\n }\n }\n\n table.Flush();\n }\n\n \/\/! Hash recieved elements onto buckets and reduce each bucket to a single value.\n void PostOp(Output input, std::function emit_func) {\n emit_func(input);\n }\n};\n\n\/\/! \\}\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_API_REDUCE_NODE_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"#include \"master.hpp\"\n\nnamespace factor\n{\n\ncell factor_vm::compute_entry_point_address(cell obj)\n{\n\tswitch(tagged(obj).type())\n\t{\n\tcase WORD_TYPE:\n\t\treturn (cell)untag(obj)->entry_point;\n\tcase QUOTATION_TYPE:\n\t\treturn (cell)untag(obj)->entry_point;\n\tdefault:\n\t\tcritical_error(\"Expected word or quotation\",obj);\n\t\treturn 0;\n\t}\n}\n\ncell factor_vm::compute_entry_point_pic_address(word *w, cell tagged_quot)\n{\n\tif(!to_boolean(tagged_quot) || max_pic_size == 0)\n\t\treturn (cell)w->entry_point;\n\telse\n\t{\n\t\tquotation *quot = untag(tagged_quot);\n\t\tif(quot_compiled_p(quot))\n\t\t\treturn (cell)quot->entry_point;\n\t\telse\n\t\t\treturn (cell)w->entry_point;\n\t}\n}\n\ncell factor_vm::compute_entry_point_pic_address(cell w_)\n{\n\ttagged w(w_);\n\treturn compute_entry_point_pic_address(w.untagged(),w->pic_def);\n}\n\ncell factor_vm::compute_entry_point_pic_tail_address(cell w_)\n{\n\ttagged w(w_);\n\treturn compute_entry_point_pic_address(w.untagged(),w->pic_tail_def);\n}\n\ncell factor_vm::code_block_owner(code_block *compiled)\n{\n\ttagged owner(compiled->owner);\n\n\t\/* Cold generic word call sites point to quotations that call the\n\tinline-cache-miss and inline-cache-miss-tail primitives. *\/\n\tif(owner.type_p(QUOTATION_TYPE))\n\t{\n\t\ttagged quot(owner.as());\n\t\ttagged elements(quot->array);\n#ifdef FACTOR_DEBUG\n\t\tassert(array_capacity(elements.untagged()) == 5);\n\t\tassert(array_nth(elements.untagged(),4) == special_objects[PIC_MISS_WORD]\n\t\t\t|| array_nth(elements.untagged(),4) == special_objects[PIC_MISS_TAIL_WORD]);\n#endif\n\t\ttagged word_wrapper(array_nth(elements.untagged(),0));\n\t\treturn word_wrapper->object;\n\t}\n\telse\n\t\treturn compiled->owner;\n}\n\nstruct update_word_references_relocation_visitor {\n\tfactor_vm *parent;\n\tbool reset_inline_caches;\n\n\tupdate_word_references_relocation_visitor(\n\t\tfactor_vm *parent_,\n\t\tbool reset_inline_caches_) :\n\t\tparent(parent_),\n\t\treset_inline_caches(reset_inline_caches_) {}\n\n\tvoid operator()(instruction_operand op)\n\t{\n\t\tswitch(op.rel_type())\n\t\t{\n\t\tcase RT_ENTRY_POINT:\n\t\t\t{\n\t\t\t\tcode_block *compiled = op.load_code_block();\n\t\t\t\tcell owner = compiled->owner;\n\t\t\t\tif(to_boolean(owner))\n\t\t\t\t\top.store_value(parent->compute_entry_point_address(owner));\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase RT_ENTRY_POINT_PIC:\n\t\t\t{\n\t\t\t\tcode_block *compiled = op.load_code_block();\n\t\t\t\tif(reset_inline_caches || !compiled->pic_p())\n\t\t\t\t{\n\t\t\t\t\tcell owner = parent->code_block_owner(compiled);\n\t\t\t\t\tif(to_boolean(owner))\n\t\t\t\t\t\top.store_value(parent->compute_entry_point_pic_address(owner));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase RT_ENTRY_POINT_PIC_TAIL:\n\t\t\t{\n\t\t\t\tcode_block *compiled = op.load_code_block();\n\t\t\t\tif(reset_inline_caches || !compiled->pic_p())\n\t\t\t\t{\n\t\t\t\t\tcell owner = parent->code_block_owner(compiled);\n\t\t\t\t\tif(to_boolean(owner))\n\t\t\t\t\t\top.store_value(parent->compute_entry_point_pic_tail_address(owner));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n};\n\n\/* Relocate new code blocks completely; updating references to literals,\ndlsyms, and words. For all other words in the code heap, we only need\nto update references to other words, without worrying about literals\nor dlsyms. *\/\nvoid factor_vm::update_word_references(code_block *compiled, bool reset_inline_caches)\n{\n\tif(code->uninitialized_p(compiled))\n\t\tinitialize_code_block(compiled);\n\t\/* update_word_references() is always applied to every block in\n\t the code heap. Since it resets all call sites to point to\n\t their canonical entry point (cold entry point for non-tail calls,\n\t standard entry point for tail calls), it means that no PICs\n\t are referenced after this is done. So instead of polluting\n\t the code heap with dead PICs that will be freed on the next\n\t GC, we add them to the free list immediately. *\/\n\telse if(reset_inline_caches && compiled->pic_p())\n\t\tcode->free(compiled);\n\telse\n\t{\n\t\tupdate_word_references_relocation_visitor visitor(this,reset_inline_caches);\n\t\tcompiled->each_instruction_operand(visitor);\n\t\tcompiled->flush_icache();\n\t}\n}\n\n\/* References to undefined symbols are patched up to call this function on\nimage load *\/\nvoid factor_vm::undefined_symbol()\n{\n\tgeneral_error(ERROR_UNDEFINED_SYMBOL,false_object,false_object);\n}\n\nvoid undefined_symbol()\n{\n\treturn current_vm()->undefined_symbol();\n}\n\n\/* Look up an external library symbol referenced by a compiled code block *\/\ncell factor_vm::compute_dlsym_address(array *literals, cell index)\n{\n\tcell symbol = array_nth(literals,index);\n\tcell library = array_nth(literals,index + 1);\n\n\tdll *d = (to_boolean(library) ? untag(library) : NULL);\n\n\tif(d != NULL && !d->handle)\n\t\treturn (cell)factor::undefined_symbol;\n\n\tswitch(tagged(symbol).type())\n\t{\n\tcase BYTE_ARRAY_TYPE:\n\t\t{\n\t\t\tsymbol_char *name = alien_offset(symbol);\n\t\t\tvoid *sym = ffi_dlsym(d,name);\n\n\t\t\tif(sym)\n\t\t\t\treturn (cell)sym;\n\t\t\telse\n\t\t\t\treturn (cell)factor::undefined_symbol;\n\t\t}\n\tcase ARRAY_TYPE:\n\t\t{\n\t\t\tarray *names = untag(symbol);\n\t\t\tfor(cell i = 0; i < array_capacity(names); i++)\n\t\t\t{\n\t\t\t\tsymbol_char *name = alien_offset(array_nth(names,i));\n\t\t\t\tvoid *sym = ffi_dlsym(d,name);\n\n\t\t\t\tif(sym)\n\t\t\t\t\treturn (cell)sym;\n\t\t\t}\n\t\t\treturn (cell)factor::undefined_symbol;\n\t\t}\n\tdefault:\n\t\tcritical_error(\"Bad symbol specifier\",symbol);\n\t\treturn (cell)factor::undefined_symbol;\n\t}\n}\n\ncell factor_vm::compute_vm_address(cell arg)\n{\n\treturn (cell)this + untag_fixnum(arg);\n}\n\nvoid factor_vm::store_external_address(instruction_operand op)\n{\n\tcode_block *compiled = op.parent_code_block();\n\tarray *parameters = (to_boolean(compiled->parameters) ? untag(compiled->parameters) : NULL);\n\tcell index = op.parameter_index();\n\n\tswitch(op.rel_type())\n\t{\n\tcase RT_DLSYM:\n\t\top.store_value(compute_dlsym_address(parameters,index));\n\t\tbreak;\n\tcase RT_THIS:\n\t\top.store_value((cell)compiled->entry_point());\n\t\tbreak;\n\tcase RT_MEGAMORPHIC_CACHE_HITS:\n\t\top.store_value((cell)&dispatch_stats.megamorphic_cache_hits);\n\t\tbreak;\n\tcase RT_VM:\n\t\top.store_value(compute_vm_address(array_nth(parameters,index)));\n\t\tbreak;\n\tcase RT_CARDS_OFFSET:\n\t\top.store_value(cards_offset);\n\t\tbreak;\n\tcase RT_DECKS_OFFSET:\n\t\top.store_value(decks_offset);\n\t\tbreak;\n#ifdef WINDOWS\n\tcase RT_EXCEPTION_HANDLER:\n\t\top.store_value(&factor::exception_handler);\n\t\tbreak;\n#endif\n\tdefault:\n\t\tcritical_error(\"Bad rel type\",op.rel_type());\n\t\tbreak;\n\t}\n}\n\ncell factor_vm::compute_here_address(cell arg, cell offset, code_block *compiled)\n{\n\tfixnum n = untag_fixnum(arg);\n\tif(n >= 0)\n\t\treturn (cell)compiled->entry_point() + offset + n;\n\telse\n\t\treturn (cell)compiled->entry_point() - n;\n}\n\nstruct initial_code_block_visitor {\n\tfactor_vm *parent;\n\tcell literals;\n\tcell literal_index;\n\n\texplicit initial_code_block_visitor(factor_vm *parent_, cell literals_)\n\t\t: parent(parent_), literals(literals_), literal_index(0) {}\n\n\tcell next_literal()\n\t{\n\t\treturn array_nth(untag(literals),literal_index++);\n\t}\n\n\tvoid operator()(instruction_operand op)\n\t{\n\t\tswitch(op.rel_type())\n\t\t{\n\t\tcase RT_LITERAL:\n\t\t\top.store_value(next_literal());\n\t\t\tbreak;\n\t\tcase RT_ENTRY_POINT:\n\t\t\top.store_value(parent->compute_entry_point_address(next_literal()));\n\t\t\tbreak;\n\t\tcase RT_ENTRY_POINT_PIC:\n\t\t\top.store_value(parent->compute_entry_point_pic_address(next_literal()));\n\t\t\tbreak;\n\t\tcase RT_ENTRY_POINT_PIC_TAIL:\n\t\t\top.store_value(parent->compute_entry_point_pic_tail_address(next_literal()));\n\t\t\tbreak;\n\t\tcase RT_HERE:\n\t\t\top.store_value(parent->compute_here_address(next_literal(),op.rel_offset(),op.parent_code_block()));\n\t\t\tbreak;\n\t\tcase RT_UNTAGGED:\n\t\t\top.store_value(untag_fixnum(next_literal()));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tparent->store_external_address(op);\n\t\t\tbreak;\n\t\t}\n\t}\n};\n\n\/* Perform all fixups on a code block *\/\nvoid factor_vm::initialize_code_block(code_block *compiled, cell literals)\n{\n\tinitial_code_block_visitor visitor(this,literals);\n\tcompiled->each_instruction_operand(visitor);\n\tcompiled->flush_icache();\n\n\t\/* next time we do a minor GC, we have to trace this code block, since\n\tthe newly-installed instruction operands might point to literals in\n\tnursery or aging *\/\n\tcode->write_barrier(compiled);\n}\n\nvoid factor_vm::initialize_code_block(code_block *compiled)\n{\n\tstd::map::iterator iter = code->uninitialized_blocks.find(compiled);\n\tinitialize_code_block(compiled,iter->second);\n\tcode->uninitialized_blocks.erase(iter);\n}\n\n\/* Fixup labels. This is done at compile time, not image load time *\/\nvoid factor_vm::fixup_labels(array *labels, code_block *compiled)\n{\n\tcell size = array_capacity(labels);\n\n\tfor(cell i = 0; i < size; i += 3)\n\t{\n\t\trelocation_class rel_class = (relocation_class)untag_fixnum(array_nth(labels,i));\n\t\tcell offset = untag_fixnum(array_nth(labels,i + 1));\n\t\tcell target = untag_fixnum(array_nth(labels,i + 2));\n\n\t\trelocation_entry new_entry(RT_HERE,rel_class,offset);\n\n\t\tinstruction_operand op(new_entry,compiled,0);\n\t\top.store_value(target + (cell)compiled->entry_point());\n\t}\n}\n\n\/* Might GC *\/\ncode_block *factor_vm::allot_code_block(cell size, code_block_type type)\n{\n\tcode_block *block = code->allocator->allot(size + sizeof(code_block));\n\n\t\/* If allocation failed, do a full GC and compact the code heap.\n\tA full GC that occurs as a result of the data heap filling up does not\n\ttrigger a compaction. This setup ensures that most GCs do not compact\n\tthe code heap, but if the code fills up, it probably means it will be\n\tfragmented after GC anyway, so its best to compact. *\/\n\tif(block == NULL)\n\t{\n\t\tprimitive_compact_gc();\n\t\tblock = code->allocator->allot(size + sizeof(code_block));\n\n\t\t\/* Insufficient room even after code GC, give up *\/\n\t\tif(block == NULL)\n\t\t{\n\t\t\tstd::cout << \"Code heap used: \" << code->allocator->occupied_space() << \"\\n\";\n\t\t\tstd::cout << \"Code heap free: \" << code->allocator->free_space() << \"\\n\";\n\t\t\tfatal_error(\"Out of memory in add-compiled-block\",0);\n\t\t}\n\t}\n\n\tblock->set_type(type);\n\treturn block;\n}\n\n\/* Might GC *\/\ncode_block *factor_vm::add_code_block(code_block_type type, cell code_, cell labels_, cell owner_, cell relocation_, cell parameters_, cell literals_)\n{\n\tdata_root code(code_,this);\n\tdata_root labels(labels_,this);\n\tdata_root owner(owner_,this);\n\tdata_root relocation(relocation_,this);\n\tdata_root parameters(parameters_,this);\n\tdata_root literals(literals_,this);\n\n\tcell code_length = array_capacity(code.untagged());\n\tcode_block *compiled = allot_code_block(code_length,type);\n\n\tcompiled->owner = owner.value();\n\n\t\/* slight space optimization *\/\n\tif(relocation.type() == BYTE_ARRAY_TYPE && array_capacity(relocation.untagged()) == 0)\n\t\tcompiled->relocation = false_object;\n\telse\n\t\tcompiled->relocation = relocation.value();\n\n\tif(parameters.type() == ARRAY_TYPE && array_capacity(parameters.untagged()) == 0)\n\t\tcompiled->parameters = false_object;\n\telse\n\t\tcompiled->parameters = parameters.value();\n\n\t\/* code *\/\n\tmemcpy(compiled + 1,code.untagged() + 1,code_length);\n\n\t\/* fixup labels *\/\n\tif(to_boolean(labels.value()))\n\t\tfixup_labels(labels.as().untagged(),compiled);\n\n\t\/* Once we are ready, fill in literal and word references in this code\n\tblock's instruction operands. In most cases this is done right after this\n\tmethod returns, except when compiling words with the non-optimizing\n\tcompiler at the beginning of bootstrap *\/\n\tthis->code->uninitialized_blocks.insert(std::make_pair(compiled,literals.value()));\n\n\t\/* next time we do a minor GC, we have to trace this code block, since\n\tthe fields of the code_block struct might point into nursery or aging *\/\n\tthis->code->write_barrier(compiled);\n\n\treturn compiled;\n}\n\n}\nvm: fix compile error#include \"master.hpp\"\n\nnamespace factor\n{\n\ncell factor_vm::compute_entry_point_address(cell obj)\n{\n\tswitch(tagged(obj).type())\n\t{\n\tcase WORD_TYPE:\n\t\treturn (cell)untag(obj)->entry_point;\n\tcase QUOTATION_TYPE:\n\t\treturn (cell)untag(obj)->entry_point;\n\tdefault:\n\t\tcritical_error(\"Expected word or quotation\",obj);\n\t\treturn 0;\n\t}\n}\n\ncell factor_vm::compute_entry_point_pic_address(word *w, cell tagged_quot)\n{\n\tif(!to_boolean(tagged_quot) || max_pic_size == 0)\n\t\treturn (cell)w->entry_point;\n\telse\n\t{\n\t\tquotation *quot = untag(tagged_quot);\n\t\tif(quot_compiled_p(quot))\n\t\t\treturn (cell)quot->entry_point;\n\t\telse\n\t\t\treturn (cell)w->entry_point;\n\t}\n}\n\ncell factor_vm::compute_entry_point_pic_address(cell w_)\n{\n\ttagged w(w_);\n\treturn compute_entry_point_pic_address(w.untagged(),w->pic_def);\n}\n\ncell factor_vm::compute_entry_point_pic_tail_address(cell w_)\n{\n\ttagged w(w_);\n\treturn compute_entry_point_pic_address(w.untagged(),w->pic_tail_def);\n}\n\ncell factor_vm::code_block_owner(code_block *compiled)\n{\n\ttagged owner(compiled->owner);\n\n\t\/* Cold generic word call sites point to quotations that call the\n\tinline-cache-miss and inline-cache-miss-tail primitives. *\/\n\tif(owner.type_p(QUOTATION_TYPE))\n\t{\n\t\ttagged quot(owner.as());\n\t\ttagged elements(quot->array);\n#ifdef FACTOR_DEBUG\n\t\tassert(array_capacity(elements.untagged()) == 5);\n\t\tassert(array_nth(elements.untagged(),4) == special_objects[PIC_MISS_WORD]\n\t\t\t|| array_nth(elements.untagged(),4) == special_objects[PIC_MISS_TAIL_WORD]);\n#endif\n\t\ttagged word_wrapper(array_nth(elements.untagged(),0));\n\t\treturn word_wrapper->object;\n\t}\n\telse\n\t\treturn compiled->owner;\n}\n\nstruct update_word_references_relocation_visitor {\n\tfactor_vm *parent;\n\tbool reset_inline_caches;\n\n\tupdate_word_references_relocation_visitor(\n\t\tfactor_vm *parent_,\n\t\tbool reset_inline_caches_) :\n\t\tparent(parent_),\n\t\treset_inline_caches(reset_inline_caches_) {}\n\n\tvoid operator()(instruction_operand op)\n\t{\n\t\tswitch(op.rel_type())\n\t\t{\n\t\tcase RT_ENTRY_POINT:\n\t\t\t{\n\t\t\t\tcode_block *compiled = op.load_code_block();\n\t\t\t\tcell owner = compiled->owner;\n\t\t\t\tif(to_boolean(owner))\n\t\t\t\t\top.store_value(parent->compute_entry_point_address(owner));\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase RT_ENTRY_POINT_PIC:\n\t\t\t{\n\t\t\t\tcode_block *compiled = op.load_code_block();\n\t\t\t\tif(reset_inline_caches || !compiled->pic_p())\n\t\t\t\t{\n\t\t\t\t\tcell owner = parent->code_block_owner(compiled);\n\t\t\t\t\tif(to_boolean(owner))\n\t\t\t\t\t\top.store_value(parent->compute_entry_point_pic_address(owner));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase RT_ENTRY_POINT_PIC_TAIL:\n\t\t\t{\n\t\t\t\tcode_block *compiled = op.load_code_block();\n\t\t\t\tif(reset_inline_caches || !compiled->pic_p())\n\t\t\t\t{\n\t\t\t\t\tcell owner = parent->code_block_owner(compiled);\n\t\t\t\t\tif(to_boolean(owner))\n\t\t\t\t\t\top.store_value(parent->compute_entry_point_pic_tail_address(owner));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n};\n\n\/* Relocate new code blocks completely; updating references to literals,\ndlsyms, and words. For all other words in the code heap, we only need\nto update references to other words, without worrying about literals\nor dlsyms. *\/\nvoid factor_vm::update_word_references(code_block *compiled, bool reset_inline_caches)\n{\n\tif(code->uninitialized_p(compiled))\n\t\tinitialize_code_block(compiled);\n\t\/* update_word_references() is always applied to every block in\n\t the code heap. Since it resets all call sites to point to\n\t their canonical entry point (cold entry point for non-tail calls,\n\t standard entry point for tail calls), it means that no PICs\n\t are referenced after this is done. So instead of polluting\n\t the code heap with dead PICs that will be freed on the next\n\t GC, we add them to the free list immediately. *\/\n\telse if(reset_inline_caches && compiled->pic_p())\n\t\tcode->free(compiled);\n\telse\n\t{\n\t\tupdate_word_references_relocation_visitor visitor(this,reset_inline_caches);\n\t\tcompiled->each_instruction_operand(visitor);\n\t\tcompiled->flush_icache();\n\t}\n}\n\n\/* References to undefined symbols are patched up to call this function on\nimage load *\/\nvoid factor_vm::undefined_symbol()\n{\n\tgeneral_error(ERROR_UNDEFINED_SYMBOL,false_object,false_object);\n}\n\nvoid undefined_symbol()\n{\n\treturn current_vm()->undefined_symbol();\n}\n\n\/* Look up an external library symbol referenced by a compiled code block *\/\ncell factor_vm::compute_dlsym_address(array *literals, cell index)\n{\n\tcell symbol = array_nth(literals,index);\n\tcell library = array_nth(literals,index + 1);\n\n\tdll *d = (to_boolean(library) ? untag(library) : NULL);\n\n\tif(d != NULL && !d->handle)\n\t\treturn (cell)factor::undefined_symbol;\n\n\tswitch(tagged(symbol).type())\n\t{\n\tcase BYTE_ARRAY_TYPE:\n\t\t{\n\t\t\tsymbol_char *name = alien_offset(symbol);\n\t\t\tvoid *sym = ffi_dlsym(d,name);\n\n\t\t\tif(sym)\n\t\t\t\treturn (cell)sym;\n\t\t\telse\n\t\t\t\treturn (cell)factor::undefined_symbol;\n\t\t}\n\tcase ARRAY_TYPE:\n\t\t{\n\t\t\tarray *names = untag(symbol);\n\t\t\tfor(cell i = 0; i < array_capacity(names); i++)\n\t\t\t{\n\t\t\t\tsymbol_char *name = alien_offset(array_nth(names,i));\n\t\t\t\tvoid *sym = ffi_dlsym(d,name);\n\n\t\t\t\tif(sym)\n\t\t\t\t\treturn (cell)sym;\n\t\t\t}\n\t\t\treturn (cell)factor::undefined_symbol;\n\t\t}\n\tdefault:\n\t\tcritical_error(\"Bad symbol specifier\",symbol);\n\t\treturn (cell)factor::undefined_symbol;\n\t}\n}\n\ncell factor_vm::compute_vm_address(cell arg)\n{\n\treturn (cell)this + untag_fixnum(arg);\n}\n\nvoid factor_vm::store_external_address(instruction_operand op)\n{\n\tcode_block *compiled = op.parent_code_block();\n\tarray *parameters = (to_boolean(compiled->parameters) ? untag(compiled->parameters) : NULL);\n\tcell index = op.parameter_index();\n\n\tswitch(op.rel_type())\n\t{\n\tcase RT_DLSYM:\n\t\top.store_value(compute_dlsym_address(parameters,index));\n\t\tbreak;\n\tcase RT_THIS:\n\t\top.store_value((cell)compiled->entry_point());\n\t\tbreak;\n\tcase RT_MEGAMORPHIC_CACHE_HITS:\n\t\top.store_value((cell)&dispatch_stats.megamorphic_cache_hits);\n\t\tbreak;\n\tcase RT_VM:\n\t\top.store_value(compute_vm_address(array_nth(parameters,index)));\n\t\tbreak;\n\tcase RT_CARDS_OFFSET:\n\t\top.store_value(cards_offset);\n\t\tbreak;\n\tcase RT_DECKS_OFFSET:\n\t\top.store_value(decks_offset);\n\t\tbreak;\n#ifdef WINDOWS\n\tcase RT_EXCEPTION_HANDLER:\n\t\top.store_value((cell)&factor::exception_handler);\n\t\tbreak;\n#endif\n\tdefault:\n\t\tcritical_error(\"Bad rel type\",op.rel_type());\n\t\tbreak;\n\t}\n}\n\ncell factor_vm::compute_here_address(cell arg, cell offset, code_block *compiled)\n{\n\tfixnum n = untag_fixnum(arg);\n\tif(n >= 0)\n\t\treturn (cell)compiled->entry_point() + offset + n;\n\telse\n\t\treturn (cell)compiled->entry_point() - n;\n}\n\nstruct initial_code_block_visitor {\n\tfactor_vm *parent;\n\tcell literals;\n\tcell literal_index;\n\n\texplicit initial_code_block_visitor(factor_vm *parent_, cell literals_)\n\t\t: parent(parent_), literals(literals_), literal_index(0) {}\n\n\tcell next_literal()\n\t{\n\t\treturn array_nth(untag(literals),literal_index++);\n\t}\n\n\tvoid operator()(instruction_operand op)\n\t{\n\t\tswitch(op.rel_type())\n\t\t{\n\t\tcase RT_LITERAL:\n\t\t\top.store_value(next_literal());\n\t\t\tbreak;\n\t\tcase RT_ENTRY_POINT:\n\t\t\top.store_value(parent->compute_entry_point_address(next_literal()));\n\t\t\tbreak;\n\t\tcase RT_ENTRY_POINT_PIC:\n\t\t\top.store_value(parent->compute_entry_point_pic_address(next_literal()));\n\t\t\tbreak;\n\t\tcase RT_ENTRY_POINT_PIC_TAIL:\n\t\t\top.store_value(parent->compute_entry_point_pic_tail_address(next_literal()));\n\t\t\tbreak;\n\t\tcase RT_HERE:\n\t\t\top.store_value(parent->compute_here_address(next_literal(),op.rel_offset(),op.parent_code_block()));\n\t\t\tbreak;\n\t\tcase RT_UNTAGGED:\n\t\t\top.store_value(untag_fixnum(next_literal()));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tparent->store_external_address(op);\n\t\t\tbreak;\n\t\t}\n\t}\n};\n\n\/* Perform all fixups on a code block *\/\nvoid factor_vm::initialize_code_block(code_block *compiled, cell literals)\n{\n\tinitial_code_block_visitor visitor(this,literals);\n\tcompiled->each_instruction_operand(visitor);\n\tcompiled->flush_icache();\n\n\t\/* next time we do a minor GC, we have to trace this code block, since\n\tthe newly-installed instruction operands might point to literals in\n\tnursery or aging *\/\n\tcode->write_barrier(compiled);\n}\n\nvoid factor_vm::initialize_code_block(code_block *compiled)\n{\n\tstd::map::iterator iter = code->uninitialized_blocks.find(compiled);\n\tinitialize_code_block(compiled,iter->second);\n\tcode->uninitialized_blocks.erase(iter);\n}\n\n\/* Fixup labels. This is done at compile time, not image load time *\/\nvoid factor_vm::fixup_labels(array *labels, code_block *compiled)\n{\n\tcell size = array_capacity(labels);\n\n\tfor(cell i = 0; i < size; i += 3)\n\t{\n\t\trelocation_class rel_class = (relocation_class)untag_fixnum(array_nth(labels,i));\n\t\tcell offset = untag_fixnum(array_nth(labels,i + 1));\n\t\tcell target = untag_fixnum(array_nth(labels,i + 2));\n\n\t\trelocation_entry new_entry(RT_HERE,rel_class,offset);\n\n\t\tinstruction_operand op(new_entry,compiled,0);\n\t\top.store_value(target + (cell)compiled->entry_point());\n\t}\n}\n\n\/* Might GC *\/\ncode_block *factor_vm::allot_code_block(cell size, code_block_type type)\n{\n\tcode_block *block = code->allocator->allot(size + sizeof(code_block));\n\n\t\/* If allocation failed, do a full GC and compact the code heap.\n\tA full GC that occurs as a result of the data heap filling up does not\n\ttrigger a compaction. This setup ensures that most GCs do not compact\n\tthe code heap, but if the code fills up, it probably means it will be\n\tfragmented after GC anyway, so its best to compact. *\/\n\tif(block == NULL)\n\t{\n\t\tprimitive_compact_gc();\n\t\tblock = code->allocator->allot(size + sizeof(code_block));\n\n\t\t\/* Insufficient room even after code GC, give up *\/\n\t\tif(block == NULL)\n\t\t{\n\t\t\tstd::cout << \"Code heap used: \" << code->allocator->occupied_space() << \"\\n\";\n\t\t\tstd::cout << \"Code heap free: \" << code->allocator->free_space() << \"\\n\";\n\t\t\tfatal_error(\"Out of memory in add-compiled-block\",0);\n\t\t}\n\t}\n\n\tblock->set_type(type);\n\treturn block;\n}\n\n\/* Might GC *\/\ncode_block *factor_vm::add_code_block(code_block_type type, cell code_, cell labels_, cell owner_, cell relocation_, cell parameters_, cell literals_)\n{\n\tdata_root code(code_,this);\n\tdata_root labels(labels_,this);\n\tdata_root owner(owner_,this);\n\tdata_root relocation(relocation_,this);\n\tdata_root parameters(parameters_,this);\n\tdata_root literals(literals_,this);\n\n\tcell code_length = array_capacity(code.untagged());\n\tcode_block *compiled = allot_code_block(code_length,type);\n\n\tcompiled->owner = owner.value();\n\n\t\/* slight space optimization *\/\n\tif(relocation.type() == BYTE_ARRAY_TYPE && array_capacity(relocation.untagged()) == 0)\n\t\tcompiled->relocation = false_object;\n\telse\n\t\tcompiled->relocation = relocation.value();\n\n\tif(parameters.type() == ARRAY_TYPE && array_capacity(parameters.untagged()) == 0)\n\t\tcompiled->parameters = false_object;\n\telse\n\t\tcompiled->parameters = parameters.value();\n\n\t\/* code *\/\n\tmemcpy(compiled + 1,code.untagged() + 1,code_length);\n\n\t\/* fixup labels *\/\n\tif(to_boolean(labels.value()))\n\t\tfixup_labels(labels.as().untagged(),compiled);\n\n\t\/* Once we are ready, fill in literal and word references in this code\n\tblock's instruction operands. In most cases this is done right after this\n\tmethod returns, except when compiling words with the non-optimizing\n\tcompiler at the beginning of bootstrap *\/\n\tthis->code->uninitialized_blocks.insert(std::make_pair(compiled,literals.value()));\n\n\t\/* next time we do a minor GC, we have to trace this code block, since\n\tthe fields of the code_block struct might point into nursery or aging *\/\n\tthis->code->write_barrier(compiled);\n\n\treturn compiled;\n}\n\n}\n<|endoftext|>"} {"text":"non-functional update<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ Provide BZFS with a list server connection\n\n\/* class header *\/\n#include \"ListServerConnection.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n#include \n#include \n\n\/* common implementation headers *\/\n#include \"bzfio.h\"\n#include \"version.h\"\n#include \"TextUtils.h\"\n#include \"Protocol.h\"\n#include \"GameKeeper.h\"\n\n\/* local implementation headers *\/\n#include \"CmdLineOptions.h\"\n\n\/\/ FIXME remove externs!\nextern Address serverAddress;\nextern PingPacket getTeamCounts();\nextern uint16_t curMaxPlayers;\nextern int getTarget(const char *victimname);\nextern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message);\nextern void sendPlayerInfo(void);\nextern void sendIPUpdate(int targetPlayer, int playerIndex);\nextern CmdLineOptions *clOptions;\n\nListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)\n{\n \/\/ parse url\n std::string protocol, hostname, pathname;\n int port = 80;\n bool useDefault = false;\n\n \/\/ use default if it can't be parsed\n if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))\n useDefault = true;\n\n \/\/ use default if wrong protocol or invalid port\n if ((protocol != \"http\") || (port < 1) || (port > 65535))\n useDefault = true;\n\n \/\/ use default if bad address\n Address address = Address::getHostAddress(hostname);\n if (address.isAny())\n useDefault = true;\n\n \/\/ parse default list server URL if we need to; assume default works\n if (useDefault) {\n BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);\n DEBUG1(\"Provided list server URL (%s) is invalid. Using default of %s.\\n\", listServerURL.c_str(), DefaultListServerURL);\n }\n\n \/\/ add to list\n this->address\t = address;\n this->port\t = port;\n this->pathname = pathname;\n this->hostname = hostname;\n this->linkSocket = NotConnected;\n\n this->publicizeAddress = publicizedAddress;\n this->publicizeDescription = publicizedTitle;\n this->publicizeServer\t = true; \/\/if this c'tor is called, it's safe to publicize\n\n \/\/ schedule initial ADD message\n queueMessage(ListServerLink::ADD);\n}\n\nListServerLink::ListServerLink()\n{\n \/\/ does not create a usable link, so checks should be placed\n \/\/ in all public member functions to ensure that nothing tries\n \/\/ to happen if publicizeServer is false\n this->linkSocket = NotConnected;\n this->publicizeServer = false;\n}\n\nListServerLink::~ListServerLink()\n{\n \/\/ now tell the list server that we're going away. this can\n \/\/ take some time but we don't want to wait too long. we do\n \/\/ our own multiplexing loop and wait for a maximum of 3 seconds\n \/\/ total.\n\n \/\/ if we aren't supposed to be publicizing, skip the whole thing\n \/\/ and don't waste 3 seconds.\n if (!publicizeServer)\n return;\n\n queueMessage(ListServerLink::REMOVE);\n TimeKeeper start = TimeKeeper::getCurrent();\n do {\n \/\/ compute timeout\n float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);\n if (waitTime <= 0.0f)\n break;\n if (!isConnected()) \/\/queueMessage should have connected us\n break;\n \/\/ check for list server socket connection\n int fdMax = -1;\n fd_set write_set;\n fd_set read_set;\n FD_ZERO(&write_set);\n FD_ZERO(&read_set);\n if (phase == ListServerLink::CONNECTING)\n _FD_SET(linkSocket, &write_set);\n else\n _FD_SET(linkSocket, &read_set);\n fdMax = linkSocket;\n\n \/\/ wait for socket to connect or timeout\n struct timeval timeout;\n timeout.tv_sec = long(floorf(waitTime));\n timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));\n int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,\n\t\t\t0, &timeout);\n if (nfound == 0)\n \/\/ Time has gone, close and go\n break;\n \/\/ check for connection to list server\n if (FD_ISSET(linkSocket, &write_set))\n sendQueuedMessages();\n else if (FD_ISSET(linkSocket, &read_set))\n read();\n } while (true);\n\n \/\/ stop list server communication\n closeLink();\n}\n\nvoid ListServerLink::closeLink()\n{\n if (isConnected()) {\n close(linkSocket);\n DEBUG4(\"Closing List Server\\n\");\n linkSocket = NotConnected;\n }\n}\n\nvoid ListServerLink::read()\n{\n if (isConnected()) {\n char buf[2048];\n int bytes = recv(linkSocket, buf, sizeof(buf)-1, 0);\n \/\/ TODO don't close unless we've got it all\n closeLink();\n buf[bytes]=0;\n char* base = buf;\n static char *tokGoodIdentifier = \"TOKGOOD: \";\n static char *tokBadIdentifier = \"TOKBAD: \";\n \/\/ walks entire reply including HTTP headers\n while (*base) {\n \/\/ find next newline\n char* scan = base;\n while (*scan && *scan != '\\r' && *scan != '\\n') scan++;\n \/\/ if no newline then no more complete replies\n if (*scan != '\\r' && *scan != '\\n') break;\n while (*scan && (*scan == '\\r' || *scan == '\\n')) *scan++ = '\\0';\n DEBUG4(\"Got line: \\\"%s\\\"\\n\", base);\n \/\/ TODO don't do this if we don't want central logins\n if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {\n\tchar *callsign, *group;\n\tcallsign = base + strlen(tokGoodIdentifier);\n\tDEBUG3(\"Got: %s\\n\", base);\n\tgroup = callsign;\n\twhile (*group && (*group != ':')) group++;\n\twhile (*group && (*group == ':')) *group++ = 0;\n\tint playerIndex = getTarget(callsign);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t if (!playerData->accessInfo.isRegistered())\n\t playerData->accessInfo.storeInfo(NULL);\n\t playerData->accessInfo.setPermissionRights();\n\t while (*group) {\n\t char *nextgroup = group;\n\t while (*nextgroup && (*nextgroup != ':')) nextgroup++;\n\t while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;\n\t playerData->accessInfo.addGroup(group);\n\t \/\/DEBUG3(\"Got: [%d] \\\"%s\\\" \\\"%s\\\"\\n\", playerIndex, callsign, group);\n\t group = nextgroup;\n\t }\n\t sendMessage(ServerPlayer, playerIndex, \"Global login approved!\");\n\t sendIPUpdate(playerIndex, -1);\n\t sendPlayerInfo();\n\t playerData->player.clearToken();\n\t}\n } else if (strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier)) == 0) {\n\tchar *callsign;\n\tcallsign = base + strlen(tokBadIdentifier);\n\t\/\/ find end of callsign (string is \"callsign=token\")\n\tchar *p = callsign;\n\twhile (*p && (*p != '=')) p++;\n\t*p = 0;\n\tint playerIndex = getTarget(callsign);\n\tDEBUG3(\"Got: [%d] %s\\n\", playerIndex, base);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t sendMessage(ServerPlayer, playerIndex, \"Global login rejected, bad token.\");\n\t playerData->player.clearToken();\n\t}\n }\n\n \/\/ next reply\n base = scan;\n }\n if (nextMessageType != ListServerLink::NONE) {\n \/\/ There was a pending request arrived after we write:\n \/\/ we should redo all the stuff\n openLink();\n }\n }\n}\n\nvoid ListServerLink::openLink()\n{\n \/\/ start opening connection if not already doing so\n if (!isConnected()) {\n linkSocket = socket(AF_INET, SOCK_STREAM, 0);\n DEBUG4(\"Opening List Server\\n\");\n if (!isConnected()) {\n return;\n }\n\n \/\/ set to non-blocking for connect\n if (BzfNetwork::setNonBlocking(linkSocket) < 0) {\n closeLink();\n return;\n }\n\n \/\/ Make our connection come from our serverAddress in case we have\n \/\/ multiple\/masked IPs so the list server can verify us.\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr = serverAddress;\n\n \/\/ assign the address to the socket\n if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n closeLink();\n return;\n }\n\n \/\/ connect. this should fail with EINPROGRESS but check for\n \/\/ success just in case.\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n addr.sin_addr = address;\n if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n#if defined(_WIN32)\n#undef EINPROGRESS\n#define EINPROGRESS EWOULDBLOCK\n#endif\n if (getErrno() != EINPROGRESS) {\n\tnerror(\"connecting to list server\");\n\t\/\/ try to lookup dns name again in case it moved\n\tthis->address = Address::getHostAddress(this->hostname);\n\tcloseLink();\n } else {\n\tphase = CONNECTING;\n }\n } else {\n \/\/ shouldn't arrive here. Just in case, clean\n DEBUG3(\"list server connect and close?\\n\");\n closeLink();\n }\n }\n}\n\nvoid ListServerLink::queueMessage(MessageType type)\n{\n \/\/ ignore if the server is not public\n if (!publicizeServer) return;\n\n \/\/ Open network connection only if closed\n if (!isConnected()) openLink();\n\n \/\/ record next message to send.\n nextMessageType = type;\n}\n\nvoid ListServerLink::sendQueuedMessages()\n{\n if (!isConnected())\n return;\n\n if (nextMessageType == ListServerLink::ADD) {\n DEBUG3(\"Queuing ADD message to list server\\n\");\n addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));\n lastAddTime = TimeKeeper::getCurrent();\n } else if (nextMessageType == ListServerLink::REMOVE) {\n DEBUG3(\"Queuing REMOVE message to list server\\n\");\n removeMe(publicizeAddress);\n }\n}\n\nvoid ListServerLink::addMe(PingPacket pingInfo,\n\t\t\t std::string publicizedAddress,\n\t\t\t std::string publicizedTitle)\n{\n std::string msg;\n\n \/\/ encode ping reply as ascii hex digits plus NULL\n char gameInfo[PingPacketHexPackedSize + 1];\n pingInfo.packHex(gameInfo);\n\n \/\/ TODO we probably should convert to a POST. List server now allows either\n \/\/ send ADD message (must send blank line)\n msg = TextUtils::format(\"GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s\",\n pathname.c_str(), publicizedAddress.c_str(),\n getServerVersion(), gameInfo,\n getAppVersion());\n msg += \"&checktokens=\";\n for (int i = 0; i < curMaxPlayers; i++) {\n GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);\n if (!playerData)\n continue;\n std::string encodedCallsign = TextUtils::url_encode(playerData->player.getCallSign());\n if (strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) {\n msg += encodedCallsign;\n msg += \"=\";\n msg += playerData->player.getToken();\n msg += \"%0D%0A\";\n }\n }\n \/\/ *groups=GROUP0%0D%0AGROUP1%0D%0A\n msg += \"&groups=\";\n std::vector::iterator itr = clOptions->remoteGroups.begin();\n for ( ; itr != clOptions->remoteGroups.end(); itr++) {\n if (*itr != \"ADMIN\") {\n msg += *itr;\n msg += \"%0D%0A\";\n }\n }\n\n msg += TextUtils::format(\"&title=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n publicizedTitle.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::removeMe(std::string publicizedAddress)\n{\n std::string msg;\n \/\/ send REMOVE (must send blank line)\n msg = TextUtils::format(\"GET %s?action=REMOVE&nameport=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n pathname.c_str(),\n publicizedAddress.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::sendLSMessage(std::string message)\n{\n const int bufsize = 4096;\n char msg[bufsize];\n strncpy(msg, message.c_str(), bufsize);\n msg[bufsize - 1] = 0;\n if (strlen(msg) > 0) {\n DEBUG3(\"%s\\n\", msg);\n if (send(linkSocket, msg, strlen(msg), 0) == -1) {\n perror(\"List server send failed\");\n DEBUG3(\"Unable to send to the list server!\\n\");\n closeLink();\n } else {\n nextMessageType = ListServerLink::NONE;\n phase\t = ListServerLink::WRITTEN;\n }\n } else {\n closeLink();\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nbzfs asks list server to check whether token and client IP match\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ Provide BZFS with a list server connection\n\n\/* class header *\/\n#include \"ListServerConnection.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n#include \n#include \n\n\/* common implementation headers *\/\n#include \"bzfio.h\"\n#include \"version.h\"\n#include \"TextUtils.h\"\n#include \"Protocol.h\"\n#include \"GameKeeper.h\"\n\n\/* local implementation headers *\/\n#include \"CmdLineOptions.h\"\n\n\/\/ FIXME remove externs!\nextern Address serverAddress;\nextern PingPacket getTeamCounts();\nextern uint16_t curMaxPlayers;\nextern int getTarget(const char *victimname);\nextern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message);\nextern void sendPlayerInfo(void);\nextern void sendIPUpdate(int targetPlayer, int playerIndex);\nextern CmdLineOptions *clOptions;\n\nListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)\n{\n \/\/ parse url\n std::string protocol, hostname, pathname;\n int port = 80;\n bool useDefault = false;\n\n \/\/ use default if it can't be parsed\n if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))\n useDefault = true;\n\n \/\/ use default if wrong protocol or invalid port\n if ((protocol != \"http\") || (port < 1) || (port > 65535))\n useDefault = true;\n\n \/\/ use default if bad address\n Address address = Address::getHostAddress(hostname);\n if (address.isAny())\n useDefault = true;\n\n \/\/ parse default list server URL if we need to; assume default works\n if (useDefault) {\n BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);\n DEBUG1(\"Provided list server URL (%s) is invalid. Using default of %s.\\n\", listServerURL.c_str(), DefaultListServerURL);\n }\n\n \/\/ add to list\n this->address\t = address;\n this->port\t = port;\n this->pathname = pathname;\n this->hostname = hostname;\n this->linkSocket = NotConnected;\n\n this->publicizeAddress = publicizedAddress;\n this->publicizeDescription = publicizedTitle;\n this->publicizeServer\t = true; \/\/if this c'tor is called, it's safe to publicize\n\n \/\/ schedule initial ADD message\n queueMessage(ListServerLink::ADD);\n}\n\nListServerLink::ListServerLink()\n{\n \/\/ does not create a usable link, so checks should be placed\n \/\/ in all public member functions to ensure that nothing tries\n \/\/ to happen if publicizeServer is false\n this->linkSocket = NotConnected;\n this->publicizeServer = false;\n}\n\nListServerLink::~ListServerLink()\n{\n \/\/ now tell the list server that we're going away. this can\n \/\/ take some time but we don't want to wait too long. we do\n \/\/ our own multiplexing loop and wait for a maximum of 3 seconds\n \/\/ total.\n\n \/\/ if we aren't supposed to be publicizing, skip the whole thing\n \/\/ and don't waste 3 seconds.\n if (!publicizeServer)\n return;\n\n queueMessage(ListServerLink::REMOVE);\n TimeKeeper start = TimeKeeper::getCurrent();\n do {\n \/\/ compute timeout\n float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);\n if (waitTime <= 0.0f)\n break;\n if (!isConnected()) \/\/queueMessage should have connected us\n break;\n \/\/ check for list server socket connection\n int fdMax = -1;\n fd_set write_set;\n fd_set read_set;\n FD_ZERO(&write_set);\n FD_ZERO(&read_set);\n if (phase == ListServerLink::CONNECTING)\n _FD_SET(linkSocket, &write_set);\n else\n _FD_SET(linkSocket, &read_set);\n fdMax = linkSocket;\n\n \/\/ wait for socket to connect or timeout\n struct timeval timeout;\n timeout.tv_sec = long(floorf(waitTime));\n timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));\n int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,\n\t\t\t0, &timeout);\n if (nfound == 0)\n \/\/ Time has gone, close and go\n break;\n \/\/ check for connection to list server\n if (FD_ISSET(linkSocket, &write_set))\n sendQueuedMessages();\n else if (FD_ISSET(linkSocket, &read_set))\n read();\n } while (true);\n\n \/\/ stop list server communication\n closeLink();\n}\n\nvoid ListServerLink::closeLink()\n{\n if (isConnected()) {\n close(linkSocket);\n DEBUG4(\"Closing List Server\\n\");\n linkSocket = NotConnected;\n }\n}\n\nvoid ListServerLink::read()\n{\n if (isConnected()) {\n char buf[2048];\n int bytes = recv(linkSocket, buf, sizeof(buf)-1, 0);\n \/\/ TODO don't close unless we've got it all\n closeLink();\n buf[bytes]=0;\n char* base = buf;\n static char *tokGoodIdentifier = \"TOKGOOD: \";\n static char *tokBadIdentifier = \"TOKBAD: \";\n \/\/ walks entire reply including HTTP headers\n while (*base) {\n \/\/ find next newline\n char* scan = base;\n while (*scan && *scan != '\\r' && *scan != '\\n') scan++;\n \/\/ if no newline then no more complete replies\n if (*scan != '\\r' && *scan != '\\n') break;\n while (*scan && (*scan == '\\r' || *scan == '\\n')) *scan++ = '\\0';\n DEBUG4(\"Got line: \\\"%s\\\"\\n\", base);\n \/\/ TODO don't do this if we don't want central logins\n if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {\n\tchar *callsign, *group;\n\tcallsign = base + strlen(tokGoodIdentifier);\n\tDEBUG3(\"Got: %s\\n\", base);\n\tgroup = callsign;\n\twhile (*group && (*group != ':')) group++;\n\twhile (*group && (*group == ':')) *group++ = 0;\n\tint playerIndex = getTarget(callsign);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t if (!playerData->accessInfo.isRegistered())\n\t playerData->accessInfo.storeInfo(NULL);\n\t playerData->accessInfo.setPermissionRights();\n\t while (*group) {\n\t char *nextgroup = group;\n\t while (*nextgroup && (*nextgroup != ':')) nextgroup++;\n\t while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;\n\t playerData->accessInfo.addGroup(group);\n\t \/\/DEBUG3(\"Got: [%d] \\\"%s\\\" \\\"%s\\\"\\n\", playerIndex, callsign, group);\n\t group = nextgroup;\n\t }\n\t sendMessage(ServerPlayer, playerIndex, \"Global login approved!\");\n\t sendIPUpdate(playerIndex, -1);\n\t sendPlayerInfo();\n\t playerData->player.clearToken();\n\t}\n } else if (strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier)) == 0) {\n\tchar *callsign;\n\tcallsign = base + strlen(tokBadIdentifier);\n\t\/\/ find end of callsign (string is \"callsign=token\")\n\tchar *p = callsign;\n\twhile (*p && (*p != '=')) p++;\n\t*p = 0;\n\tint playerIndex = getTarget(callsign);\n\tDEBUG3(\"Got: [%d] %s\\n\", playerIndex, base);\n\tif (playerIndex < curMaxPlayers) {\n\t GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\t sendMessage(ServerPlayer, playerIndex, \"Global login rejected, bad token.\");\n\t playerData->player.clearToken();\n\t}\n }\n\n \/\/ next reply\n base = scan;\n }\n if (nextMessageType != ListServerLink::NONE) {\n \/\/ There was a pending request arrived after we write:\n \/\/ we should redo all the stuff\n openLink();\n }\n }\n}\n\nvoid ListServerLink::openLink()\n{\n \/\/ start opening connection if not already doing so\n if (!isConnected()) {\n linkSocket = socket(AF_INET, SOCK_STREAM, 0);\n DEBUG4(\"Opening List Server\\n\");\n if (!isConnected()) {\n return;\n }\n\n \/\/ set to non-blocking for connect\n if (BzfNetwork::setNonBlocking(linkSocket) < 0) {\n closeLink();\n return;\n }\n\n \/\/ Make our connection come from our serverAddress in case we have\n \/\/ multiple\/masked IPs so the list server can verify us.\n struct sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr = serverAddress;\n\n \/\/ assign the address to the socket\n if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n closeLink();\n return;\n }\n\n \/\/ connect. this should fail with EINPROGRESS but check for\n \/\/ success just in case.\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n addr.sin_addr = address;\n if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {\n#if defined(_WIN32)\n#undef EINPROGRESS\n#define EINPROGRESS EWOULDBLOCK\n#endif\n if (getErrno() != EINPROGRESS) {\n\tnerror(\"connecting to list server\");\n\t\/\/ try to lookup dns name again in case it moved\n\tthis->address = Address::getHostAddress(this->hostname);\n\tcloseLink();\n } else {\n\tphase = CONNECTING;\n }\n } else {\n \/\/ shouldn't arrive here. Just in case, clean\n DEBUG3(\"list server connect and close?\\n\");\n closeLink();\n }\n }\n}\n\nvoid ListServerLink::queueMessage(MessageType type)\n{\n \/\/ ignore if the server is not public\n if (!publicizeServer) return;\n\n \/\/ Open network connection only if closed\n if (!isConnected()) openLink();\n\n \/\/ record next message to send.\n nextMessageType = type;\n}\n\nvoid ListServerLink::sendQueuedMessages()\n{\n if (!isConnected())\n return;\n\n if (nextMessageType == ListServerLink::ADD) {\n DEBUG3(\"Queuing ADD message to list server\\n\");\n addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));\n lastAddTime = TimeKeeper::getCurrent();\n } else if (nextMessageType == ListServerLink::REMOVE) {\n DEBUG3(\"Queuing REMOVE message to list server\\n\");\n removeMe(publicizeAddress);\n }\n}\n\nvoid ListServerLink::addMe(PingPacket pingInfo,\n\t\t\t std::string publicizedAddress,\n\t\t\t std::string publicizedTitle)\n{\n std::string msg;\n\n \/\/ encode ping reply as ascii hex digits plus NULL\n char gameInfo[PingPacketHexPackedSize + 1];\n pingInfo.packHex(gameInfo);\n\n \/\/ TODO we probably should convert to a POST. List server now allows either\n \/\/ send ADD message (must send blank line)\n msg = TextUtils::format(\"GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s\",\n pathname.c_str(), publicizedAddress.c_str(),\n getServerVersion(), gameInfo,\n getAppVersion());\n msg += \"&checktokens=\";\n \/\/ callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A\n for (int i = 0; i < curMaxPlayers; i++) {\n GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);\n if (!playerData)\n continue;\n NetHandler *handler = playerData->netHandler;\n std::string encodedCallsign = TextUtils::url_encode(playerData->player.getCallSign());\n if (strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) {\n msg += encodedCallsign;\n msg += \"@\";\n msg += handler->getTargetIP();\n msg += \"=\";\n msg += playerData->player.getToken();\n msg += \"%0D%0A\";\n }\n }\n \/\/ *groups=GROUP0%0D%0AGROUP1%0D%0A\n msg += \"&groups=\";\n std::vector::iterator itr = clOptions->remoteGroups.begin();\n for ( ; itr != clOptions->remoteGroups.end(); itr++) {\n if (*itr != \"ADMIN\") {\n msg += *itr;\n msg += \"%0D%0A\";\n }\n }\n\n msg += TextUtils::format(\"&title=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n publicizedTitle.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::removeMe(std::string publicizedAddress)\n{\n std::string msg;\n \/\/ send REMOVE (must send blank line)\n msg = TextUtils::format(\"GET %s?action=REMOVE&nameport=%s HTTP\/1.1\\r\\n\"\n \"User-Agent: bzfs %s\\r\\n\"\n \"Host: %s\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\"\n \"Connection: close\\r\\n\"\n \"\\r\\n\",\n pathname.c_str(),\n publicizedAddress.c_str(),\n getAppVersion(),\n hostname.c_str());\n sendLSMessage(msg);\n}\n\nvoid ListServerLink::sendLSMessage(std::string message)\n{\n const int bufsize = 4096;\n char msg[bufsize];\n strncpy(msg, message.c_str(), bufsize);\n msg[bufsize - 1] = 0;\n if (strlen(msg) > 0) {\n DEBUG3(\"%s\\n\", msg);\n if (send(linkSocket, msg, strlen(msg), 0) == -1) {\n perror(\"List server send failed\");\n DEBUG3(\"Unable to send to the list server!\\n\");\n closeLink();\n } else {\n nextMessageType = ListServerLink::NONE;\n phase\t = ListServerLink::WRITTEN;\n }\n } else {\n closeLink();\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more \n * details.\n * \n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite\n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably\n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/ \n\n#if 0\n#include \"base\/EncodingUtils.h\"\n#endif\n\n#include \"base\/util\/StringBuffer.h\"\n#include \"spdm\/constants.h\"\n#include \"push\/CTPConfig.h\" \n#include \"base\/globalsdef.h\"\n\nUSE_NAMESPACE\n\n#define CTP_QUEUE_PUSH \"queuePush\"\n#define CTP_RETRY \"ctpRetry\"\n#define CTP_MAX_RETRY_TIMEOUT \"maxCtpRetry\"\n#define CTP_CMD_TIMEOUT \"ctpCmdTimeout\"\n#define CTP_CONN_TIMEOUT \"ctpConnTimeout\"\n#define CTP_PORT \"ctpPort\"\n#define CTP_READY \"ctpReady\"\n#define PROPERTY_CTP_SERVER \"ctpServer\"\n#define PROPERTY_NOTIFY_TIMEOUT \"notifyTimeout\"\n\n\nCTPConfig::CTPConfig(const char* application_uri)\n : DMTClientConfig(application_uri) {\n}\n \nCTPConfig::~CTPConfig() {}\n\nchar* CTPConfig::decodePassword(const char* password) {\n \n char* decripted = NULL;\n#if 0\n \/\/ Encryption not supported yet!!! TODO FIXME\n if (password && strlen(password) > 0) {\n decripted = decryptData(password); \n } \n\n if (decripted == NULL || getLastErrorCode() == 801) {\n decripted = new char[1];\n decripted[0] = 0;\n setError(ERR_NONE, \"\");\n }\n#endif\n return decripted; \n}\n\nStringBuffer CTPConfig::encodePassword(const char* password) {\n \n StringBuffer buffer(\"\");\n#if 0\n \/\/ Encryption not supported yet!!! TODO FIXME\n if (password && strlen(password) > 0) {\n char* encoded = encryptData(password); \n buffer = encoded; \n } \n#endif\n return buffer; \n}\n \nvoid CTPConfig::readCTPConfig() {\n\n if (!open()) {\n LOG.error(\"Impossible read the ctp configuration. exit\");\n return;\n }\n\n if (readAccessConfig(*syncMLNode)) {\n setUsername(accessConfig.getUsername());\n \/\/ urlTo is loaded from 'ctpServer' key \n \/\/ nonce is read calling 'readAccessConfig()'\n }\n\n bool passEncoded = false;\n \/\/ TODO we should stringbuffer instead of malloc\/new strings\n char* passDecoded;\n if (passEncoded) {\n#if 0\n \/\/ FIXME TODO\n passDecoded = decodePassword(accessConfig.getPassword());\n accessConfig.setPassword(passDecoded);\n#endif\n } else {\n passDecoded = stringdup(accessConfig.getPassword());\n accessConfig.setPassword(passDecoded);\n }\n delete [] passDecoded;\n\n if (readDeviceConfig(*syncMLNode)) {\n setDeviceId(deviceConfig.getDevID());\n\n }\n \n \/\/ now read the single CTP properties\n ManagementNode* node;\n char nodeName[DIM_MANAGEMENT_PATH];\n nodeName[0] = 0;\n sprintf(nodeName, \"%s%s\", rootContext, CONTEXT_PUSH_CTP);\n \n\n node = dmt->readManagementNode(nodeName);\n if (node) \n {\n char* tmp; \n tmp = node->readPropertyValue(PROPERTY_PUSH_NOTIFICATION);\n if (tmp) {\n setPush(atoi(tmp));\n } else {\n setPush(0);\n } \n delete [] tmp;\n \n tmp = node->readPropertyValue(PROPERTY_POLLING_NOTIFICATION);\n if (tmp) {\n setPolling(atoi(tmp));\n } else {\n setPolling(0);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_QUEUE_PUSH);\n if (tmp) {\n setQueuePush(atoi(tmp) == 0 ? false : true);\n } else {\n setQueuePush(false);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(PROPERTY_NOTIFY_TIMEOUT);\n if (tmp) {\n setNotifyTimeout(atoi(tmp));\n } else {\n setNotifyTimeout(180);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_RETRY);\n if (tmp) {\n setCtpRetry(atoi(tmp));\n } else {\n setCtpRetry(5);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_MAX_RETRY_TIMEOUT);\n if (tmp) {\n setMaxCtpRetry(atoi(tmp));\n } else {\n setMaxCtpRetry(900); \/\/ 15 min\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_CMD_TIMEOUT);\n if (tmp) {\n setCtpCmdTimeout(atoi(tmp));\n } else {\n setCtpCmdTimeout(0); \n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_CONN_TIMEOUT);\n if (tmp) {\n setCtpConnTimeout(atoi(tmp));\n } else {\n setCtpConnTimeout(0); \n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_PORT);\n if (tmp) {\n setCtpPort(atoi(tmp));\n } else {\n setCtpPort(0); \n } \n delete [] tmp;\n \n tmp = node->readPropertyValue(CTP_READY);\n if (tmp) {\n setCtpReady(atoi(tmp));\n } else {\n setCtpReady(5);\n } \n delete [] tmp;\n\n \/\/ server url is loaded from regstry key 'ctpServer'\n tmp = node->readPropertyValue(PROPERTY_CTP_SERVER);\n if (tmp && strlen(tmp)>0) {\n \/\/ *** workaround for prefix: remove this when not necessary! ***\n StringBuffer url = checkPrefix(tmp);\n LOG.debug(\"urlTo = %s\", url.c_str());\n setUrlTo(url);\n } else {\n \/\/ If 'ctpServer' reg value is empty, extract the url from 'syncUrl'\n setUrlTo(getHostName(accessConfig.getSyncURL()));\n } \n delete [] tmp;\n\n\n delete node;\n node = NULL;\n }\n \n close();\n return;\n\n}\n\n\nvoid CTPConfig::saveCTPConfig() { \n \n ManagementNode* node = NULL;\n if (!open()) {\n return;\n }\n \n bool passwordEncoded = false;\n\n StringBuffer buffer;\n if (passwordEncoded) {\n buffer = encodePassword(accessConfig.getPassword());\n } else {\n buffer = accessConfig.getPassword();\n }\n accessConfig.setPassword(buffer.c_str());\n \/\/ Save the nonce: save AuthConfig properties\n char nodeName[DIM_MANAGEMENT_PATH];\n sprintf(nodeName, \"%s%s%s\", APPLICATION_URI, CONTEXT_SPDS_SYNCML, CONTEXT_AUTH);\n node = dmt->readManagementNode(nodeName);\n if (node) {\n saveAuthConfig(*syncMLNode, *node);\n delete node;\n }\n\n char* passDecoded;\n if (passwordEncoded) {\n#if 0\n \/\/ TODO FIXME\n passDecoded = decodePassword(accessConfig.getPassword());\n accessConfig.setPassword(passDecoded);\n delete [] passDecoded;\n#endif\n } else {\n accessConfig.setPassword(accessConfig.getPassword());\n }\n close();\n}\n \n\nStringBuffer CTPConfig::getHostName(StringBuffer syncUrl) {\n\n size_t start, end;\n StringBuffer host;\n \/\/ Extract the hostName from syncUrl: \"http:\/\/:8080\/funambol\/ds\" \n start = syncUrl.find(\":\/\/\", 0);\n if (start != StringBuffer::npos) {\n start += 3;\n } else {\n \/\/ try to extract hostname from :8080\/funambol\/ds\" \n start = 0;\n }\n \n end = syncUrl.find(\":\", start); \/\/ stop if \":\" or \"\/\" found\n if (end == StringBuffer::npos) {\n end = syncUrl.find(\"\/\", start);\n if (end == StringBuffer::npos) { \/\/ so the url is only \n end = syncUrl.length();\n }\n }\n\n if (end > start) {\n host = syncUrl.substr(start, end-start); \n } \n\n return host;\n}\n\nint CTPConfig::getHostPort(StringBuffer syncUrl) {\n\n size_t start, endSlash, endColon, urlLength;\n StringBuffer hostPort = \"\";\n urlLength = syncUrl.length();\n int port = 0;\n \/\/ Extract the port from syncUrl: \"http:\/\/:8080\/funambol\/ds\" \n start = syncUrl.find(\":\/\/\", 0);\n if (start != StringBuffer::npos) {\n start += 3;\n } else {\n \/\/ try to extract the port from :8080\/funambol\/ds\" \n start = 0;\n }\n \n endSlash = syncUrl.find(\"\/\", start); \/\/ stop if \":\" or \"\/\" found\n endColon = syncUrl.find(\":\", start); \/\/ stop if \":\" or \"\/\" found\n \n if (endSlash == StringBuffer::npos && endColon == StringBuffer::npos) {\n \/\/ there is no port\n \/\/ hostname\n } else if (endSlash != StringBuffer::npos && endColon == StringBuffer::npos) {\n \/\/ there is no port\n \/\/ hostname\/funambol\n } else if (endSlash == StringBuffer::npos && endColon != StringBuffer::npos) {\n \/\/ there is port\n \/\/ hostname:8080 \n hostPort = syncUrl.substr(endColon + 1, urlLength - start);\n } else {\n if (endSlash > endColon) {\n \/\/ there is port\n \/\/ hostname:8080\/funambol \n hostPort = syncUrl.substr(endColon + 1, endSlash - endColon - 1);\n }\n }\n \n if (hostPort != \"\") {\n port = atoi(hostPort.c_str());\n }\n\n return port;\n}\n \n\n\/\/\/ If passed 'url' contains \"prefix:\" the value is appended \n\/\/\/ next to the host name: is returned\n\/\/\/ (hostName is retrieved from SyncUrl)\n\/\/\/ Otherwise the passed 'url' is returned as StringBuffer.\nStringBuffer CTPConfig::checkPrefix(char* url) {\n\n StringBuffer ctpUrl = url;\n const StringBuffer prefix = \"prefix:\";\n\n size_t pos = ctpUrl.find(prefix, 0);\n if (pos == StringBuffer::npos) {\n \/\/ Not found: keep the url passed\n return ctpUrl;\n }\n\n \/\/ Go after the \":\" \n pos += prefix.length();\n if (pos != StringBuffer::npos) {\n \/\/ Add the prefix\n ctpUrl = ctpUrl.substr(pos, ctpUrl.length());\n \/\/ Append the syncUrl\n ctpUrl += getHostName(accessConfig.getSyncURL());\n }\n\n return ctpUrl;\n}\n\nfixed bug. don't use setVar(getVar()), the same pointer is deleted during the set operation\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more \n * details.\n * \n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite\n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably\n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/ \n\n#if 0\n#include \"base\/EncodingUtils.h\"\n#endif\n\n#include \"base\/util\/StringBuffer.h\"\n#include \"spdm\/constants.h\"\n#include \"push\/CTPConfig.h\" \n#include \"base\/globalsdef.h\"\n\nUSE_NAMESPACE\n\n#define CTP_QUEUE_PUSH \"queuePush\"\n#define CTP_RETRY \"ctpRetry\"\n#define CTP_MAX_RETRY_TIMEOUT \"maxCtpRetry\"\n#define CTP_CMD_TIMEOUT \"ctpCmdTimeout\"\n#define CTP_CONN_TIMEOUT \"ctpConnTimeout\"\n#define CTP_PORT \"ctpPort\"\n#define CTP_READY \"ctpReady\"\n#define PROPERTY_CTP_SERVER \"ctpServer\"\n#define PROPERTY_NOTIFY_TIMEOUT \"notifyTimeout\"\n\n\nCTPConfig::CTPConfig(const char* application_uri)\n : DMTClientConfig(application_uri) {\n}\n \nCTPConfig::~CTPConfig() {}\n\nchar* CTPConfig::decodePassword(const char* password) {\n \n char* decripted = NULL;\n#if 0\n \/\/ Encryption not supported yet!!! TODO FIXME\n if (password && strlen(password) > 0) {\n decripted = decryptData(password); \n } \n\n if (decripted == NULL || getLastErrorCode() == 801) {\n decripted = new char[1];\n decripted[0] = 0;\n setError(ERR_NONE, \"\");\n }\n#endif\n return decripted; \n}\n\nStringBuffer CTPConfig::encodePassword(const char* password) {\n \n StringBuffer buffer(\"\");\n#if 0\n \/\/ Encryption not supported yet!!! TODO FIXME\n if (password && strlen(password) > 0) {\n char* encoded = encryptData(password); \n buffer = encoded; \n } \n#endif\n return buffer; \n}\n \nvoid CTPConfig::readCTPConfig() {\n\n if (!open()) {\n LOG.error(\"Impossible read the ctp configuration. exit\");\n return;\n }\n\n if (readAccessConfig(*syncMLNode)) {\n setUsername(accessConfig.getUsername());\n \/\/ urlTo is loaded from 'ctpServer' key \n \/\/ nonce is read calling 'readAccessConfig()'\n }\n\n bool passEncoded = false;\n \/\/ TODO we should stringbuffer instead of malloc\/new strings\n char* passDecoded;\n if (passEncoded) {\n#if 0\n \/\/ FIXME TODO\n passDecoded = decodePassword(accessConfig.getPassword());\n accessConfig.setPassword(passDecoded);\n#endif\n } else {\n passDecoded = stringdup(accessConfig.getPassword());\n accessConfig.setPassword(passDecoded);\n }\n delete [] passDecoded;\n\n if (readDeviceConfig(*syncMLNode)) {\n setDeviceId(deviceConfig.getDevID());\n\n }\n \n \/\/ now read the single CTP properties\n ManagementNode* node;\n char nodeName[DIM_MANAGEMENT_PATH];\n nodeName[0] = 0;\n sprintf(nodeName, \"%s%s\", rootContext, CONTEXT_PUSH_CTP);\n \n\n node = dmt->readManagementNode(nodeName);\n if (node) \n {\n char* tmp; \n tmp = node->readPropertyValue(PROPERTY_PUSH_NOTIFICATION);\n if (tmp) {\n setPush(atoi(tmp));\n } else {\n setPush(0);\n } \n delete [] tmp;\n \n tmp = node->readPropertyValue(PROPERTY_POLLING_NOTIFICATION);\n if (tmp) {\n setPolling(atoi(tmp));\n } else {\n setPolling(0);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_QUEUE_PUSH);\n if (tmp) {\n setQueuePush(atoi(tmp) == 0 ? false : true);\n } else {\n setQueuePush(false);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(PROPERTY_NOTIFY_TIMEOUT);\n if (tmp) {\n setNotifyTimeout(atoi(tmp));\n } else {\n setNotifyTimeout(180);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_RETRY);\n if (tmp) {\n setCtpRetry(atoi(tmp));\n } else {\n setCtpRetry(5);\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_MAX_RETRY_TIMEOUT);\n if (tmp) {\n setMaxCtpRetry(atoi(tmp));\n } else {\n setMaxCtpRetry(900); \/\/ 15 min\n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_CMD_TIMEOUT);\n if (tmp) {\n setCtpCmdTimeout(atoi(tmp));\n } else {\n setCtpCmdTimeout(0); \n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_CONN_TIMEOUT);\n if (tmp) {\n setCtpConnTimeout(atoi(tmp));\n } else {\n setCtpConnTimeout(0); \n } \n delete [] tmp;\n\n tmp = node->readPropertyValue(CTP_PORT);\n if (tmp) {\n setCtpPort(atoi(tmp));\n } else {\n setCtpPort(0); \n } \n delete [] tmp;\n \n tmp = node->readPropertyValue(CTP_READY);\n if (tmp) {\n setCtpReady(atoi(tmp));\n } else {\n setCtpReady(5);\n } \n delete [] tmp;\n\n \/\/ server url is loaded from regstry key 'ctpServer'\n tmp = node->readPropertyValue(PROPERTY_CTP_SERVER);\n if (tmp && strlen(tmp)>0) {\n \/\/ *** workaround for prefix: remove this when not necessary! ***\n StringBuffer url = checkPrefix(tmp);\n LOG.debug(\"urlTo = %s\", url.c_str());\n setUrlTo(url);\n } else {\n \/\/ If 'ctpServer' reg value is empty, extract the url from 'syncUrl'\n setUrlTo(getHostName(accessConfig.getSyncURL()));\n } \n delete [] tmp;\n\n\n delete node;\n node = NULL;\n }\n \n close();\n return;\n\n}\n\n\nvoid CTPConfig::saveCTPConfig() { \n \n ManagementNode* node = NULL;\n if (!open()) {\n return;\n }\n \n bool passwordEncoded = false;\n\n StringBuffer buffer;\n if (passwordEncoded) {\n buffer = encodePassword(accessConfig.getPassword());\n } else {\n buffer = accessConfig.getPassword();\n }\n accessConfig.setPassword(buffer.c_str());\n \/\/ Save the nonce: save AuthConfig properties\n char nodeName[DIM_MANAGEMENT_PATH];\n sprintf(nodeName, \"%s%s%s\", APPLICATION_URI, CONTEXT_SPDS_SYNCML, CONTEXT_AUTH);\n node = dmt->readManagementNode(nodeName);\n if (node) {\n saveAuthConfig(*syncMLNode, *node);\n delete node;\n }\n\n char* passDecoded;\n if (passwordEncoded) {\n#if 0\n \/\/ TODO FIXME\n passDecoded = decodePassword(accessConfig.getPassword());\n accessConfig.setPassword(passDecoded);\n delete [] passDecoded;\n#endif\n } else {\n \/\/ Nothing to do: the password is already in clear text.\n }\n close();\n}\n \n\nStringBuffer CTPConfig::getHostName(StringBuffer syncUrl) {\n\n size_t start, end;\n StringBuffer host;\n \/\/ Extract the hostName from syncUrl: \"http:\/\/:8080\/funambol\/ds\" \n start = syncUrl.find(\":\/\/\", 0);\n if (start != StringBuffer::npos) {\n start += 3;\n } else {\n \/\/ try to extract hostname from :8080\/funambol\/ds\" \n start = 0;\n }\n \n end = syncUrl.find(\":\", start); \/\/ stop if \":\" or \"\/\" found\n if (end == StringBuffer::npos) {\n end = syncUrl.find(\"\/\", start);\n if (end == StringBuffer::npos) { \/\/ so the url is only \n end = syncUrl.length();\n }\n }\n\n if (end > start) {\n host = syncUrl.substr(start, end-start); \n } \n\n return host;\n}\n\nint CTPConfig::getHostPort(StringBuffer syncUrl) {\n\n size_t start, endSlash, endColon, urlLength;\n StringBuffer hostPort = \"\";\n urlLength = syncUrl.length();\n int port = 0;\n \/\/ Extract the port from syncUrl: \"http:\/\/:8080\/funambol\/ds\" \n start = syncUrl.find(\":\/\/\", 0);\n if (start != StringBuffer::npos) {\n start += 3;\n } else {\n \/\/ try to extract the port from :8080\/funambol\/ds\" \n start = 0;\n }\n \n endSlash = syncUrl.find(\"\/\", start); \/\/ stop if \":\" or \"\/\" found\n endColon = syncUrl.find(\":\", start); \/\/ stop if \":\" or \"\/\" found\n \n if (endSlash == StringBuffer::npos && endColon == StringBuffer::npos) {\n \/\/ there is no port\n \/\/ hostname\n } else if (endSlash != StringBuffer::npos && endColon == StringBuffer::npos) {\n \/\/ there is no port\n \/\/ hostname\/funambol\n } else if (endSlash == StringBuffer::npos && endColon != StringBuffer::npos) {\n \/\/ there is port\n \/\/ hostname:8080 \n hostPort = syncUrl.substr(endColon + 1, urlLength - start);\n } else {\n if (endSlash > endColon) {\n \/\/ there is port\n \/\/ hostname:8080\/funambol \n hostPort = syncUrl.substr(endColon + 1, endSlash - endColon - 1);\n }\n }\n \n if (hostPort != \"\") {\n port = atoi(hostPort.c_str());\n }\n\n return port;\n}\n \n\n\/\/\/ If passed 'url' contains \"prefix:\" the value is appended \n\/\/\/ next to the host name: is returned\n\/\/\/ (hostName is retrieved from SyncUrl)\n\/\/\/ Otherwise the passed 'url' is returned as StringBuffer.\nStringBuffer CTPConfig::checkPrefix(char* url) {\n\n StringBuffer ctpUrl = url;\n const StringBuffer prefix = \"prefix:\";\n\n size_t pos = ctpUrl.find(prefix, 0);\n if (pos == StringBuffer::npos) {\n \/\/ Not found: keep the url passed\n return ctpUrl;\n }\n\n \/\/ Go after the \":\" \n pos += prefix.length();\n if (pos != StringBuffer::npos) {\n \/\/ Add the prefix\n ctpUrl = ctpUrl.substr(pos, ctpUrl.length());\n \/\/ Append the syncUrl\n ctpUrl += getHostName(accessConfig.getSyncURL());\n }\n\n return ctpUrl;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nCAFFE2_DEFINE_string(init_net, \"res\/squeezenet_init_net.pb\",\n \"The given path to the init protobuffer.\");\nCAFFE2_DEFINE_string(predict_net, \"res\/squeezenet_predict_net.pb\",\n \"The given path to the predict protobuffer.\");\nCAFFE2_DEFINE_string(file, \"res\/image_file.jpg\", \"The image file.\");\nCAFFE2_DEFINE_string(classes, \"res\/imagenet_classes.txt\", \"The classes file.\");\nCAFFE2_DEFINE_int(size, 227, \"The image file.\");\n\nnamespace caffe2 {\n\nvoid run() {\n std::cout << std::endl;\n std::cout << \"## Caffe2 Loading Pre-Trained Models Tutorial ##\" << std::endl;\n std::cout << \"https:\/\/caffe2.ai\/docs\/zoo.html\" << std::endl;\n std::cout << \"https:\/\/caffe2.ai\/docs\/tutorial-loading-pre-trained-models.html\"\n << std::endl;\n std::cout << \"https:\/\/caffe2.ai\/docs\/tutorial-image-pre-processing.html\"\n << std::endl;\n std::cout << std::endl;\n\n if (!std::ifstream(FLAGS_init_net).good() ||\n !std::ifstream(FLAGS_predict_net).good()) {\n std::cerr << \"error: Squeezenet model file missing: \"\n << (std::ifstream(FLAGS_init_net).good() ? FLAGS_predict_net\n : FLAGS_init_net)\n << std::endl;\n std::cerr << \"Make sure to first run .\/script\/download_resource.sh\"\n << std::endl;\n return;\n }\n\n if (!std::ifstream(FLAGS_file).good()) {\n std::cerr << \"error: Image file missing: \" << FLAGS_file << std::endl;\n return;\n }\n\n if (!std::ifstream(FLAGS_classes).good()) {\n std::cerr << \"error: Classes file invalid: \" << FLAGS_classes << std::endl;\n return;\n }\n\n std::cout << \"init-net: \" << FLAGS_init_net << std::endl;\n std::cout << \"predict-net: \" << FLAGS_predict_net << std::endl;\n std::cout << \"file: \" << FLAGS_file << std::endl;\n std::cout << \"size: \" << FLAGS_size << std::endl;\n\n std::cout << std::endl;\n\n \/\/ >>> img =\n \/\/ skimage.img_as_float(skimage.io.imread(IMAGE_LOCATION)).astype(np.float32)\n auto image = cv::imread(FLAGS_file); \/\/ CV_8UC3\n std::cout << \"image size: \" << image.size() << std::endl;\n\n \/\/ scale image to fit\n cv::Size scale(std::max(FLAGS_size * image.cols \/ image.rows, FLAGS_size),\n std::max(FLAGS_size, FLAGS_size * image.rows \/ image.cols));\n cv::resize(image, image, scale);\n std::cout << \"scaled size: \" << image.size() << std::endl;\n\n \/\/ crop image to fit\n cv::Rect crop((image.cols - FLAGS_size) \/ 2, (image.rows - FLAGS_size) \/ 2,\n FLAGS_size, FLAGS_size);\n image = image(crop);\n std::cout << \"cropped size: \" << image.size() << std::endl;\n\n \/\/ convert to float, normalize to mean 128\n image.convertTo(image, CV_32FC3, 1.0, -128);\n std::cout << \"value range: (\"\n << *std::min_element((float *)image.datastart,\n (float *)image.dataend)\n << \", \"\n << *std::max_element((float *)image.datastart,\n (float *)image.dataend)\n << \")\" << std::endl;\n\n \/\/ convert NHWC to NCHW\n vector channels(3);\n cv::split(image, channels);\n std::vector data;\n for (auto &c : channels) {\n data.insert(data.end(), (float *)c.datastart, (float *)c.dataend);\n }\n std::vector dims({1, image.channels(), image.rows, image.cols});\n TensorCPU tensor(dims, data, NULL);\n\n \/\/ Load Squeezenet model\n NetDef init_net, predict_net;\n\n \/\/ >>> with open(path_to_INIT_NET) as f:\n CAFFE_ENFORCE(ReadProtoFromFile(FLAGS_init_net, &init_net));\n\n \/\/ >>> with open(path_to_PREDICT_NET) as f:\n CAFFE_ENFORCE(ReadProtoFromFile(FLAGS_predict_net, &predict_net));\n\n \/\/ >>> p = workspace.Predictor(init_net, predict_net)\n Workspace workspace(\"tmp\");\n CAFFE_ENFORCE(workspace.RunNetOnce(init_net));\n auto input = workspace.CreateBlob(\"data\")->GetMutable();\n input->ResizeLike(tensor);\n input->ShareData(tensor);\n CAFFE_ENFORCE(workspace.RunNetOnce(predict_net));\n\n \/\/ >>> results = p.run([img])\n auto output = workspace.GetBlob(\"softmaxout\")->Get();\n\n \/\/ sort top results\n const auto &probs = output.data();\n std::vector> pairs;\n for (auto i = 0; i < output.size(); i++) {\n if (probs[i] > 0.01) {\n pairs.push_back(std::make_pair(probs[i] * 100, i));\n }\n }\n\n std::sort(pairs.begin(), pairs.end());\n\n std::cout << std::endl;\n\n \/\/ read classes\n std::ifstream file(FLAGS_classes);\n std::string temp;\n std::vector classes;\n while (std::getline(file, temp)) {\n classes.push_back(temp);\n }\n\n \/\/ show results\n std::cout << \"output: \" << std::endl;\n for (auto pair : pairs) {\n std::cout << \" \" << pair.first << \"% '\" << classes[pair.second] << \"' (\"\n << pair.second << \")\" << std::endl;\n }\n}\n\n} \/\/ namespace caffe2\n\nint main(int argc, char **argv) {\n caffe2::GlobalInit(&argc, &argv);\n caffe2::run();\n google::protobuf::ShutdownProtobufLibrary();\n return 0;\n}\nfix pretrained on googlenet#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nCAFFE2_DEFINE_string(init_net, \"res\/squeezenet_init_net.pb\",\n \"The given path to the init protobuffer.\");\nCAFFE2_DEFINE_string(predict_net, \"res\/squeezenet_predict_net.pb\",\n \"The given path to the predict protobuffer.\");\nCAFFE2_DEFINE_string(file, \"res\/image_file.jpg\", \"The image file.\");\nCAFFE2_DEFINE_string(classes, \"res\/imagenet_classes.txt\", \"The classes file.\");\nCAFFE2_DEFINE_int(size, 227, \"The image file.\");\n\nnamespace caffe2 {\n\nvoid run() {\n std::cout << std::endl;\n std::cout << \"## Caffe2 Loading Pre-Trained Models Tutorial ##\" << std::endl;\n std::cout << \"https:\/\/caffe2.ai\/docs\/zoo.html\" << std::endl;\n std::cout << \"https:\/\/caffe2.ai\/docs\/tutorial-loading-pre-trained-models.html\"\n << std::endl;\n std::cout << \"https:\/\/caffe2.ai\/docs\/tutorial-image-pre-processing.html\"\n << std::endl;\n std::cout << std::endl;\n\n if (!std::ifstream(FLAGS_init_net).good() ||\n !std::ifstream(FLAGS_predict_net).good()) {\n std::cerr << \"error: Squeezenet model file missing: \"\n << (std::ifstream(FLAGS_init_net).good() ? FLAGS_predict_net\n : FLAGS_init_net)\n << std::endl;\n std::cerr << \"Make sure to first run .\/script\/download_resource.sh\"\n << std::endl;\n return;\n }\n\n if (!std::ifstream(FLAGS_file).good()) {\n std::cerr << \"error: Image file missing: \" << FLAGS_file << std::endl;\n return;\n }\n\n if (!std::ifstream(FLAGS_classes).good()) {\n std::cerr << \"error: Classes file invalid: \" << FLAGS_classes << std::endl;\n return;\n }\n\n std::cout << \"init-net: \" << FLAGS_init_net << std::endl;\n std::cout << \"predict-net: \" << FLAGS_predict_net << std::endl;\n std::cout << \"file: \" << FLAGS_file << std::endl;\n std::cout << \"size: \" << FLAGS_size << std::endl;\n\n std::cout << std::endl;\n\n \/\/ >>> img =\n \/\/ skimage.img_as_float(skimage.io.imread(IMAGE_LOCATION)).astype(np.float32)\n auto image = cv::imread(FLAGS_file); \/\/ CV_8UC3\n std::cout << \"image size: \" << image.size() << std::endl;\n\n \/\/ scale image to fit\n cv::Size scale(std::max(FLAGS_size * image.cols \/ image.rows, FLAGS_size),\n std::max(FLAGS_size, FLAGS_size * image.rows \/ image.cols));\n cv::resize(image, image, scale);\n std::cout << \"scaled size: \" << image.size() << std::endl;\n\n \/\/ crop image to fit\n cv::Rect crop((image.cols - FLAGS_size) \/ 2, (image.rows - FLAGS_size) \/ 2,\n FLAGS_size, FLAGS_size);\n image = image(crop);\n std::cout << \"cropped size: \" << image.size() << std::endl;\n\n \/\/ convert to float, normalize to mean 128\n image.convertTo(image, CV_32FC3, 1.0, -128);\n std::cout << \"value range: (\"\n << *std::min_element((float *)image.datastart,\n (float *)image.dataend)\n << \", \"\n << *std::max_element((float *)image.datastart,\n (float *)image.dataend)\n << \")\" << std::endl;\n\n \/\/ convert NHWC to NCHW\n vector channels(3);\n cv::split(image, channels);\n std::vector data;\n for (auto &c : channels) {\n data.insert(data.end(), (float *)c.datastart, (float *)c.dataend);\n }\n std::vector dims({1, image.channels(), image.rows, image.cols});\n TensorCPU tensor(dims, data, NULL);\n\n \/\/ Load Squeezenet model\n NetDef init_net, predict_net;\n\n \/\/ >>> with open(path_to_INIT_NET) as f:\n CAFFE_ENFORCE(ReadProtoFromFile(FLAGS_init_net, &init_net));\n\n \/\/ >>> with open(path_to_PREDICT_NET) as f:\n CAFFE_ENFORCE(ReadProtoFromFile(FLAGS_predict_net, &predict_net));\n\n \/\/ >>> p = workspace.Predictor(init_net, predict_net)\n Workspace workspace(\"tmp\");\n CAFFE_ENFORCE(workspace.RunNetOnce(init_net));\n auto input = workspace.CreateBlob(\"data\")->GetMutable();\n input->ResizeLike(tensor);\n input->ShareData(tensor);\n CAFFE_ENFORCE(workspace.RunNetOnce(predict_net));\n\n \/\/ >>> results = p.run([img])\n auto &output_name = predict_net.external_output(0);\n auto output = workspace.GetBlob(output_name)->Get();\n\n \/\/ sort top results\n const auto &probs = output.data();\n std::vector> pairs;\n for (auto i = 0; i < output.size(); i++) {\n if (probs[i] > 0.01) {\n pairs.push_back(std::make_pair(probs[i] * 100, i));\n }\n }\n\n std::sort(pairs.begin(), pairs.end());\n\n std::cout << std::endl;\n\n \/\/ read classes\n std::ifstream file(FLAGS_classes);\n std::string temp;\n std::vector classes;\n while (std::getline(file, temp)) {\n classes.push_back(temp);\n }\n\n \/\/ show results\n std::cout << \"output: \" << std::endl;\n for (auto pair : pairs) {\n std::cout << \" \" << pair.first << \"% '\" << classes[pair.second] << \"' (\"\n << pair.second << \")\" << std::endl;\n }\n}\n\n} \/\/ namespace caffe2\n\nint main(int argc, char **argv) {\n caffe2::GlobalInit(&argc, &argv);\n caffe2::run();\n google::protobuf::ShutdownProtobufLibrary();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mitkVolumeDataVtkMapper3D.h\"\n#include \"mitkLevelWindow.h\"\n#include \"mitkDataTreeNode.h\"\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkOpenGLRenderer.h\"\n#include \"mitkLookupTableProperty.h\"\n#include \"mitkTransferFunctionProperty.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nconst mitk::Image* mitk::VolumeDataVtkMapper3D::GetInput()\n{\n return static_cast ( GetData() );\n}\n\nmitk::VolumeDataVtkMapper3D::VolumeDataVtkMapper3D()\n{\n \/\/ m_VtkVolumeMapper = vtkVolumeRayCastMapper::New();\n\t\/\/ m_VtkVolumeMapper = vtkVolumeTextureMapper2D::New();\n\n m_LowResMapper = vtkVolumeTextureMapper2D::New();\n m_MedResMapper = vtkVolumeRayCastMapper::New();\n m_HiResMapper = vtkVolumeRayCastMapper::New();\n\n\n \/\/m_MedResMapper->AutoAdjustSampleDistancesOff();\n \/\/m_MedResMapper->SetImageSampleDistance(2.5);\n\n \/\/m_HiResMapper->AutoAdjustSampleDistancesOff();\n \/\/m_HiResMapper->SetImageSampleDistance(0.5);\n m_HiResMapper->SetMaximumImageSampleDistance(10.0);\n m_HiResMapper->SetMinimumImageSampleDistance(1.0);\n m_HiResMapper->IntermixIntersectingGeometryOn();\n m_HiResMapper->SetNumberOfThreads( itk::MultiThreader::GetGlobalDefaultNumberOfThreads() );\n\n vtkVolumeRayCastCompositeFunction* compositeFunction = vtkVolumeRayCastCompositeFunction::New();\n m_MedResMapper->SetVolumeRayCastFunction(compositeFunction);\n m_HiResMapper->SetVolumeRayCastFunction(compositeFunction);\n\/\/ compositeFunction->Delete();\n vtkFiniteDifferenceGradientEstimator* gradientEstimator = \n vtkFiniteDifferenceGradientEstimator::New();\n\/* if (dynamic_cast(m_VtkVolumeMapper)){ \n dynamic_cast(m_VtkVolumeMapper)->SetGradientEstimator(gradientEstimator);\n } else if (dynamic_cast(m_VtkVolumeMapper)){ \n dynamic_cast(m_VtkVolumeMapper)->SetGradientEstimator(gradientEstimator);\n } *\/ \n m_LowResMapper->SetGradientEstimator(gradientEstimator);\n m_MedResMapper->SetGradientEstimator(gradientEstimator);\n m_HiResMapper->SetGradientEstimator(gradientEstimator);\n\n gradientEstimator->Delete();\n\n m_VolumeProperty = vtkVolumeProperty::New();\n m_VolumeLOD = vtkLODProp3D::New();\n\n m_VolumeLOD->AddLOD(m_HiResMapper,m_VolumeProperty,0.0);\n m_VolumeLOD->AddLOD(m_MedResMapper,m_VolumeProperty,0.0);\n m_VolumeLOD->AddLOD(m_LowResMapper,m_VolumeProperty,0.0);\n \n m_Resampler = vtkImageResample::New();\n m_Resampler->SetAxisMagnificationFactor(0,0.5);\n m_Resampler->SetAxisMagnificationFactor(1,0.5);\n m_Resampler->SetAxisMagnificationFactor(2,0.5);\n \n \/\/m_Volume = vtkVolume::New();\n \/\/ m_Volume->SetMapper( m_VtkVolumeMapper );\n \/\/ m_Volume->SetProperty(m_VolumeProperty); \n \/\/ m_Prop3D = m_Volume;\n m_Prop3D = m_VolumeLOD;\n m_Prop3D->Register(NULL); \n \n m_ImageCast = vtkImageShiftScale::New(); \n m_ImageCast->SetOutputScalarTypeToUnsignedShort();\n m_ImageCast->ClampOverflowOn();\n\n m_UnitSpacingImageFilter = vtkImageChangeInformation::New();\n m_UnitSpacingImageFilter->SetInput(m_ImageCast->GetOutput());\n m_UnitSpacingImageFilter->SetOutputSpacing(1.0,1.0,1.0);\n}\n\n\nmitk::VolumeDataVtkMapper3D::~VolumeDataVtkMapper3D()\n{\n \/\/ m_VtkVolumeMapper->Delete();\n \/\/m_Volume->Delete();\n m_UnitSpacingImageFilter->Delete();\n m_ImageCast->Delete();\n m_LowResMapper->Delete();\n m_MedResMapper->Delete();\n m_HiResMapper->Delete();\n m_Resampler->Delete();\n m_VolumeProperty->Delete();\n m_VolumeLOD->Delete();\n}\nvoid mitk::VolumeDataVtkMapper3D::AbortCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata) {\n \/\/ std::cout << \"abort test called\" << std::endl;\n vtkRenderWindow* renWin = dynamic_cast(caller);\n assert(renWin);\n int foo=renWin->GetEventPending();\n if(foo!=0) \n {\n renWin->SetAbortRender(1);\n }\n \/\/ FIXME: qApp->hasPendingEvents is always true, renWin->GetEventPending is\n \/\/ always false. So aborting the render doesn't work this way.\n\n \/\/ if (\n \/\/ qApp->hasPendingEvents()\n \/\/ )\n \/\/ {\n \/\/ std::cout << \"setting abort render\" << std::endl;\n \/\/ renWin->SetAbortRender(1); \n \/\/ }\n}\n\nvoid mitk::VolumeDataVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer)\n{\n\n if(IsVisible(renderer)==false ||\n GetDataTreeNode() == NULL || \n dynamic_cast(GetDataTreeNode()->GetProperty(\"volumerendering\",renderer).GetPointer())==NULL || \n dynamic_cast(GetDataTreeNode()->GetProperty(\"volumerendering\",renderer).GetPointer())->GetValue() == false \n )\n {\n \/\/ FIXME: don't understand this \n if (m_Prop3D) {\n \/\/ std::cout << \"visibility off\" <VisibilityOff();\n }\n return;\n }\n if (m_Prop3D) {\n m_Prop3D->VisibilityOn();\n }\n\n mitk::Image* input = const_cast(this->GetInput());\n if((input==NULL) || (input->IsInitialized()==false))\n return;\n\n \/\/ FIXME: const_cast; maybe GetVtkImageData can be made const by using volatile \n const TimeSlicedGeometry* inputtimegeometry = input->GetTimeSlicedGeometry();\n assert(inputtimegeometry!=NULL);\n\n const Geometry3D* worldgeometry = renderer->GetCurrentWorldGeometry();\n\n assert(worldgeometry!=NULL);\n\n int timestep=0;\n ScalarType time = worldgeometry->GetTimeBounds()[0];\n if(time>-ScalarTypeNumericTraits::max())\n timestep = inputtimegeometry->MSToTimeStep(time);\n\n if(inputtimegeometry->IsValidTime(timestep)==false)\n return;\n\n vtkImageData* inputData = input->GetVtkImageData(timestep);\n if(inputData==NULL)\n return;\n\n m_ImageCast->SetInput( inputData );\n\n\/\/ m_ImageCast->Update(); \n\n \/\/trying to avoid update-problem, when size of input changed. Does not really help much.\n if(m_ImageCast->GetOutput()!=NULL)\n {\n int inputWE[6]; \n inputData->GetWholeExtent(inputWE);\n int * outputWE=m_UnitSpacingImageFilter->GetOutput()->GetExtent();\n if(m_ImageCast->GetOutput()!=NULL && memcmp(inputWE, outputWE,sizeof(int)*6) != 0)\n {\n\/\/ m_ImageCast->GetOutput()->SetUpdateExtentToWholeExtent();\n\/\/ m_UnitSpacingImageFilter->GetOutput()->SetUpdateExtentToWholeExtent();\n m_UnitSpacingImageFilter->GetOutput()->SetUpdateExtent(inputWE);\n m_UnitSpacingImageFilter->UpdateWholeExtent();\n }\n }\n\n \/\/m_VtkVolumeMapper->SetInput( m_UnitSpacingImageFilter->GetOutput() );\n \/\/m_Volume->SetMapper( m_VtkVolumeMapper );\n m_Resampler->SetInput(m_UnitSpacingImageFilter->GetOutput()); \n \n m_LowResMapper->SetInput(m_Resampler->GetOutput());\n m_MedResMapper->SetInput(m_UnitSpacingImageFilter->GetOutput());\n m_HiResMapper->SetInput(m_UnitSpacingImageFilter->GetOutput());\n \n vtkPiecewiseFunction *opacityTransferFunction;\n vtkColorTransferFunction* colorTransferFunction;\n\n opacityTransferFunction = vtkPiecewiseFunction::New();\n colorTransferFunction = vtkColorTransferFunction::New();\n\n m_ImageCast->SetShift(0);\n\n \nmitk::TransferFunctionProperty::Pointer tranferFunctionProp = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"TransferFunction\").GetPointer());\n if (tranferFunctionProp.IsNull()) {\n \/\/ create one\n mitk::TransferFunction::Pointer newTF = mitk::TransferFunction::New();\n newTF->InitializeByMitkImage(input);\n\/\/ newTF->SetMin(-10);\n\/\/ newTF->SetMax(+310);\n this->GetDataTreeNode()->SetProperty(\"TransferFunction\", new TransferFunctionProperty(newTF.GetPointer()));\n } \n \n mitk::LookupTableProperty::Pointer lookupTableProp;\n lookupTableProp = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"LookupTable\").GetPointer());\n mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"TransferFunction\").GetPointer());\n if (transferFunctionProp.IsNotNull() && transferFunctionProp->GetValue()->GetValid()) {\n\n opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction();\n colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction();\n } else if (lookupTableProp.IsNotNull() )\n {\n lookupTableProp->GetLookupTable().CreateColorTransferFunction(colorTransferFunction);\n colorTransferFunction->ClampingOn();\n lookupTableProp->GetLookupTable().CreateOpacityTransferFunction(opacityTransferFunction);\n opacityTransferFunction->ClampingOn();\n }\n else\n {\n mitk::LevelWindow levelWindow;\n int lw_min,lw_max;\n\n bool binary=false;\n GetDataTreeNode()->GetBoolProperty(\"binary\", binary, renderer);\n if(binary)\n {\n lw_min=0; lw_max=2;\n }\n else\n if(GetLevelWindow(levelWindow,renderer,\"levelWindow\") || GetLevelWindow(levelWindow,renderer))\n {\n lw_min = (int)levelWindow.GetMin();\n lw_max = (int)levelWindow.GetMax();\n \/\/ std::cout << \"levwin:\" << levelWindow << std::endl;\n if(lw_min<0)\n {\n m_ImageCast->SetShift(-lw_min);\n lw_max+=-lw_min;\n lw_min=0;\n }\n } \n else \n {\n lw_min = 0;\n lw_max = 255;\n }\n\n opacityTransferFunction->AddPoint( lw_min, 0.0 );\n opacityTransferFunction->AddPoint( lw_max, 0.8 );\n opacityTransferFunction->ClampingOn();\n\n \/\/colorTransferFunction->AddRGBPoint( lw_min, 0.0, 0.0, 1.0 );\n \/\/colorTransferFunction->AddRGBPoint( (lw_min+lw_max)\/2, 1.0, 0.0, 0.0 );\n \/\/colorTransferFunction->AddRGBPoint( lw_max, 0.0, 1.0, 0.0 );\n\n float rgb[3]={1.0f,1.0f,1.0f};\n \/\/ check for color prop and use it for rendering if it exists\n if(GetColor(rgb, renderer))\n {\n colorTransferFunction->AddRGBPoint( lw_min, 0.0, 0.0, 0.0 );\n colorTransferFunction->AddRGBPoint( (lw_min+lw_max)\/2, rgb[0], rgb[1], rgb[2] );\n colorTransferFunction->AddRGBPoint( lw_max, rgb[0], rgb[1], rgb[2] );\n }\n else\n {\n colorTransferFunction->AddRGBPoint( lw_min, 0.0, 0.0, 0.0 );\n colorTransferFunction->AddRGBPoint( (lw_min+lw_max)\/2, 1, 1, 0.0 );\n colorTransferFunction->AddRGBPoint( lw_max, 0.8, 0.2, 0 );\n }\n\n colorTransferFunction->ClampingOn();\n }\n \n m_VolumeProperty->SetColor( colorTransferFunction );\n m_VolumeProperty->SetScalarOpacity( opacityTransferFunction ); \n m_VolumeProperty->SetDiffuse(0.2);\n m_VolumeProperty->SetAmbient(0.9);\n m_VolumeProperty->ShadeOn();\n\n mitk::OpenGLRenderer* openGlRenderer = dynamic_cast(renderer);\n assert(openGlRenderer);\n vtkRenderWindow* vtkRendWin = dynamic_cast(openGlRenderer->GetVtkRenderWindow());\n if (vtkRendWin) {\n\/\/ vtkRendWin->SetDesiredUpdateRate(25.0);\n vtkRenderWindowInteractor* interactor = vtkRendWin->GetInteractor();\n interactor->SetDesiredUpdateRate(50000.0);\n interactor->SetStillUpdateRate(0.0001);\n\n vtkCallbackCommand* cbc = vtkCallbackCommand::New(); \n cbc->SetCallback(mitk::VolumeDataVtkMapper3D::AbortCallback); \n vtkRendWin->AddObserver(vtkCommand::AbortCheckEvent,cbc); \n\n } else {\n std::cout << \"no vtk renderwindow\" << std::endl;\n }\n \/\/m_Volume->Update();\n \/\/ m_VolumeLOD->Update();\n \/\/ m_Prop3D = m_Volume;\n\n \/\/ now add an AbortCheckEvent callback for cancelling the rendering \n\n\/\/ colorTransferFunction->Delete();\n\/\/ opacityTransferFunction->Delete();\n}\n\nvoid mitk::VolumeDataVtkMapper3D::ApplyProperties(vtkActor* actor, mitk::BaseRenderer* renderer)\n{\n\n}\nCHG: removed obsolete validity check of transfer function\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mitkVolumeDataVtkMapper3D.h\"\n#include \"mitkLevelWindow.h\"\n#include \"mitkDataTreeNode.h\"\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkOpenGLRenderer.h\"\n#include \"mitkLookupTableProperty.h\"\n#include \"mitkTransferFunctionProperty.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nconst mitk::Image* mitk::VolumeDataVtkMapper3D::GetInput()\n{\n return static_cast ( GetData() );\n}\n\nmitk::VolumeDataVtkMapper3D::VolumeDataVtkMapper3D()\n{\n \/\/ m_VtkVolumeMapper = vtkVolumeRayCastMapper::New();\n\t\/\/ m_VtkVolumeMapper = vtkVolumeTextureMapper2D::New();\n\n m_LowResMapper = vtkVolumeTextureMapper2D::New();\n m_MedResMapper = vtkVolumeRayCastMapper::New();\n m_HiResMapper = vtkVolumeRayCastMapper::New();\n\n\n \/\/m_MedResMapper->AutoAdjustSampleDistancesOff();\n \/\/m_MedResMapper->SetImageSampleDistance(2.5);\n\n \/\/m_HiResMapper->AutoAdjustSampleDistancesOff();\n \/\/m_HiResMapper->SetImageSampleDistance(0.5);\n m_HiResMapper->SetMaximumImageSampleDistance(10.0);\n m_HiResMapper->SetMinimumImageSampleDistance(1.0);\n m_HiResMapper->IntermixIntersectingGeometryOn();\n m_HiResMapper->SetNumberOfThreads( itk::MultiThreader::GetGlobalDefaultNumberOfThreads() );\n\n vtkVolumeRayCastCompositeFunction* compositeFunction = vtkVolumeRayCastCompositeFunction::New();\n m_MedResMapper->SetVolumeRayCastFunction(compositeFunction);\n m_HiResMapper->SetVolumeRayCastFunction(compositeFunction);\n\/\/ compositeFunction->Delete();\n vtkFiniteDifferenceGradientEstimator* gradientEstimator = \n vtkFiniteDifferenceGradientEstimator::New();\n\/* if (dynamic_cast(m_VtkVolumeMapper)){ \n dynamic_cast(m_VtkVolumeMapper)->SetGradientEstimator(gradientEstimator);\n } else if (dynamic_cast(m_VtkVolumeMapper)){ \n dynamic_cast(m_VtkVolumeMapper)->SetGradientEstimator(gradientEstimator);\n } *\/ \n m_LowResMapper->SetGradientEstimator(gradientEstimator);\n m_MedResMapper->SetGradientEstimator(gradientEstimator);\n m_HiResMapper->SetGradientEstimator(gradientEstimator);\n\n gradientEstimator->Delete();\n\n m_VolumeProperty = vtkVolumeProperty::New();\n m_VolumeLOD = vtkLODProp3D::New();\n\n m_VolumeLOD->AddLOD(m_HiResMapper,m_VolumeProperty,0.0);\n m_VolumeLOD->AddLOD(m_MedResMapper,m_VolumeProperty,0.0);\n m_VolumeLOD->AddLOD(m_LowResMapper,m_VolumeProperty,0.0);\n \n m_Resampler = vtkImageResample::New();\n m_Resampler->SetAxisMagnificationFactor(0,0.5);\n m_Resampler->SetAxisMagnificationFactor(1,0.5);\n m_Resampler->SetAxisMagnificationFactor(2,0.5);\n \n \/\/m_Volume = vtkVolume::New();\n \/\/ m_Volume->SetMapper( m_VtkVolumeMapper );\n \/\/ m_Volume->SetProperty(m_VolumeProperty); \n \/\/ m_Prop3D = m_Volume;\n m_Prop3D = m_VolumeLOD;\n m_Prop3D->Register(NULL); \n \n m_ImageCast = vtkImageShiftScale::New(); \n m_ImageCast->SetOutputScalarTypeToUnsignedShort();\n m_ImageCast->ClampOverflowOn();\n\n m_UnitSpacingImageFilter = vtkImageChangeInformation::New();\n m_UnitSpacingImageFilter->SetInput(m_ImageCast->GetOutput());\n m_UnitSpacingImageFilter->SetOutputSpacing(1.0,1.0,1.0);\n}\n\n\nmitk::VolumeDataVtkMapper3D::~VolumeDataVtkMapper3D()\n{\n \/\/ m_VtkVolumeMapper->Delete();\n \/\/m_Volume->Delete();\n m_UnitSpacingImageFilter->Delete();\n m_ImageCast->Delete();\n m_LowResMapper->Delete();\n m_MedResMapper->Delete();\n m_HiResMapper->Delete();\n m_Resampler->Delete();\n m_VolumeProperty->Delete();\n m_VolumeLOD->Delete();\n}\nvoid mitk::VolumeDataVtkMapper3D::AbortCallback(vtkObject *caller, unsigned long eid, void *clientdata, void *calldata) {\n \/\/ std::cout << \"abort test called\" << std::endl;\n vtkRenderWindow* renWin = dynamic_cast(caller);\n assert(renWin);\n int foo=renWin->GetEventPending();\n if(foo!=0) \n {\n renWin->SetAbortRender(1);\n }\n \/\/ FIXME: qApp->hasPendingEvents is always true, renWin->GetEventPending is\n \/\/ always false. So aborting the render doesn't work this way.\n\n \/\/ if (\n \/\/ qApp->hasPendingEvents()\n \/\/ )\n \/\/ {\n \/\/ std::cout << \"setting abort render\" << std::endl;\n \/\/ renWin->SetAbortRender(1); \n \/\/ }\n}\n\nvoid mitk::VolumeDataVtkMapper3D::GenerateData(mitk::BaseRenderer* renderer)\n{\n\n if(IsVisible(renderer)==false ||\n GetDataTreeNode() == NULL || \n dynamic_cast(GetDataTreeNode()->GetProperty(\"volumerendering\",renderer).GetPointer())==NULL || \n dynamic_cast(GetDataTreeNode()->GetProperty(\"volumerendering\",renderer).GetPointer())->GetValue() == false \n )\n {\n \/\/ FIXME: don't understand this \n if (m_Prop3D) {\n \/\/ std::cout << \"visibility off\" <VisibilityOff();\n }\n return;\n }\n if (m_Prop3D) {\n m_Prop3D->VisibilityOn();\n }\n\n mitk::Image* input = const_cast(this->GetInput());\n if((input==NULL) || (input->IsInitialized()==false))\n return;\n\n \/\/ FIXME: const_cast; maybe GetVtkImageData can be made const by using volatile \n const TimeSlicedGeometry* inputtimegeometry = input->GetTimeSlicedGeometry();\n assert(inputtimegeometry!=NULL);\n\n const Geometry3D* worldgeometry = renderer->GetCurrentWorldGeometry();\n\n assert(worldgeometry!=NULL);\n\n int timestep=0;\n ScalarType time = worldgeometry->GetTimeBounds()[0];\n if(time>-ScalarTypeNumericTraits::max())\n timestep = inputtimegeometry->MSToTimeStep(time);\n\n if(inputtimegeometry->IsValidTime(timestep)==false)\n return;\n\n vtkImageData* inputData = input->GetVtkImageData(timestep);\n if(inputData==NULL)\n return;\n\n m_ImageCast->SetInput( inputData );\n\n\/\/ m_ImageCast->Update(); \n\n \/\/trying to avoid update-problem, when size of input changed. Does not really help much.\n if(m_ImageCast->GetOutput()!=NULL)\n {\n int inputWE[6]; \n inputData->GetWholeExtent(inputWE);\n int * outputWE=m_UnitSpacingImageFilter->GetOutput()->GetExtent();\n if(m_ImageCast->GetOutput()!=NULL && memcmp(inputWE, outputWE,sizeof(int)*6) != 0)\n {\n\/\/ m_ImageCast->GetOutput()->SetUpdateExtentToWholeExtent();\n\/\/ m_UnitSpacingImageFilter->GetOutput()->SetUpdateExtentToWholeExtent();\n m_UnitSpacingImageFilter->GetOutput()->SetUpdateExtent(inputWE);\n m_UnitSpacingImageFilter->UpdateWholeExtent();\n }\n }\n\n \/\/m_VtkVolumeMapper->SetInput( m_UnitSpacingImageFilter->GetOutput() );\n \/\/m_Volume->SetMapper( m_VtkVolumeMapper );\n m_Resampler->SetInput(m_UnitSpacingImageFilter->GetOutput()); \n \n m_LowResMapper->SetInput(m_Resampler->GetOutput());\n m_MedResMapper->SetInput(m_UnitSpacingImageFilter->GetOutput());\n m_HiResMapper->SetInput(m_UnitSpacingImageFilter->GetOutput());\n \n vtkPiecewiseFunction *opacityTransferFunction;\n vtkColorTransferFunction* colorTransferFunction;\n\n opacityTransferFunction = vtkPiecewiseFunction::New();\n colorTransferFunction = vtkColorTransferFunction::New();\n\n m_ImageCast->SetShift(0);\n\n \nmitk::TransferFunctionProperty::Pointer tranferFunctionProp = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"TransferFunction\").GetPointer());\n if (tranferFunctionProp.IsNull()) {\n \/\/ create one\n mitk::TransferFunction::Pointer newTF = mitk::TransferFunction::New();\n newTF->InitializeByMitkImage(input);\n this->GetDataTreeNode()->SetProperty(\"TransferFunction\", new TransferFunctionProperty(newTF.GetPointer()));\n } \n \n mitk::LookupTableProperty::Pointer lookupTableProp;\n lookupTableProp = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"LookupTable\").GetPointer());\n mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"TransferFunction\").GetPointer());\n if ( transferFunctionProp.IsNotNull() ) {\n\n opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction();\n colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction();\n } else if (lookupTableProp.IsNotNull() )\n {\n lookupTableProp->GetLookupTable().CreateColorTransferFunction(colorTransferFunction);\n colorTransferFunction->ClampingOn();\n lookupTableProp->GetLookupTable().CreateOpacityTransferFunction(opacityTransferFunction);\n opacityTransferFunction->ClampingOn();\n }\n else\n {\n mitk::LevelWindow levelWindow;\n int lw_min,lw_max;\n\n bool binary=false;\n GetDataTreeNode()->GetBoolProperty(\"binary\", binary, renderer);\n if(binary)\n {\n lw_min=0; lw_max=2;\n }\n else\n if(GetLevelWindow(levelWindow,renderer,\"levelWindow\") || GetLevelWindow(levelWindow,renderer))\n {\n lw_min = (int)levelWindow.GetMin();\n lw_max = (int)levelWindow.GetMax();\n \/\/ std::cout << \"levwin:\" << levelWindow << std::endl;\n if(lw_min<0)\n {\n m_ImageCast->SetShift(-lw_min);\n lw_max+=-lw_min;\n lw_min=0;\n }\n } \n else \n {\n lw_min = 0;\n lw_max = 255;\n }\n\n opacityTransferFunction->AddPoint( lw_min, 0.0 );\n opacityTransferFunction->AddPoint( lw_max, 0.8 );\n opacityTransferFunction->ClampingOn();\n\n \/\/colorTransferFunction->AddRGBPoint( lw_min, 0.0, 0.0, 1.0 );\n \/\/colorTransferFunction->AddRGBPoint( (lw_min+lw_max)\/2, 1.0, 0.0, 0.0 );\n \/\/colorTransferFunction->AddRGBPoint( lw_max, 0.0, 1.0, 0.0 );\n\n float rgb[3]={1.0f,1.0f,1.0f};\n \/\/ check for color prop and use it for rendering if it exists\n if(GetColor(rgb, renderer))\n {\n colorTransferFunction->AddRGBPoint( lw_min, 0.0, 0.0, 0.0 );\n colorTransferFunction->AddRGBPoint( (lw_min+lw_max)\/2, rgb[0], rgb[1], rgb[2] );\n colorTransferFunction->AddRGBPoint( lw_max, rgb[0], rgb[1], rgb[2] );\n }\n else\n {\n colorTransferFunction->AddRGBPoint( lw_min, 0.0, 0.0, 0.0 );\n colorTransferFunction->AddRGBPoint( (lw_min+lw_max)\/2, 1, 1, 0.0 );\n colorTransferFunction->AddRGBPoint( lw_max, 0.8, 0.2, 0 );\n }\n\n colorTransferFunction->ClampingOn();\n }\n m_VolumeProperty->SetColor( colorTransferFunction );\n m_VolumeProperty->SetScalarOpacity( opacityTransferFunction ); \n m_VolumeProperty->SetDiffuse(0.2);\n m_VolumeProperty->SetAmbient(0.9);\n m_VolumeProperty->ShadeOn();\n\n mitk::OpenGLRenderer* openGlRenderer = dynamic_cast(renderer);\n assert(openGlRenderer);\n vtkRenderWindow* vtkRendWin = dynamic_cast(openGlRenderer->GetVtkRenderWindow());\n if (vtkRendWin) {\n\/\/ vtkRendWin->SetDesiredUpdateRate(25.0);\n vtkRenderWindowInteractor* interactor = vtkRendWin->GetInteractor();\n interactor->SetDesiredUpdateRate(50000.0);\n interactor->SetStillUpdateRate(0.0001);\n\n vtkCallbackCommand* cbc = vtkCallbackCommand::New(); \n cbc->SetCallback(mitk::VolumeDataVtkMapper3D::AbortCallback); \n vtkRendWin->AddObserver(vtkCommand::AbortCheckEvent,cbc); \n\n } else {\n std::cout << \"no vtk renderwindow\" << std::endl;\n }\n \/\/m_Volume->Update();\n \/\/ m_VolumeLOD->Update();\n \/\/ m_Prop3D = m_Volume;\n\n \/\/ now add an AbortCheckEvent callback for cancelling the rendering \n\n\/\/ colorTransferFunction->Delete();\n\/\/ opacityTransferFunction->Delete();\n}\n\nvoid mitk::VolumeDataVtkMapper3D::ApplyProperties(vtkActor* actor, mitk::BaseRenderer* renderer)\n{\n\n}\n<|endoftext|>"} {"text":"#include \"mex.h\"\n#include \n#include \"drakeUtil.h\"\n#include \"RigidBodyManipulator.h\"\n#include \n#include \n#include \"drake\/ExponentialPlusPiecewisePolynomial.h\"\n#include \"math.h\"\n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXd expm(const MatrixXd& A) {\n MatrixXd F;\n MatrixExponential(A).compute(F);\n return F;\n}\n\nPiecewisePolynomial matlabPPFormToPiecewisePolynomial(const mxArray* pp)\n{\n vector breaks = matlabToStdVector(mxGetFieldSafe(pp, \"breaks\"));\n size_t num_segments = breaks.size() - 1; \/\/ l\n\n const mxArray* coefs_mex = mxGetFieldSafe(pp, \"coefs\"); \/\/ a d*l x k matrix\n const size_t* coefs_mex_dims = mxGetDimensions(coefs_mex);\n int num_coefs_mex_dims = mxGetNumberOfDimensions(coefs_mex);\n\n size_t number_of_elements = mxGetNumberOfElements(coefs_mex);\n\n const mxArray* dim_mex = mxGetFieldSafe(pp, \"dim\");\n int num_dims_mex = mxGetNumberOfElements(dim_mex);\n if (num_dims_mex == 0 | num_dims_mex > 2)\n throw runtime_error(\"case not handled\"); \/\/ because PiecewisePolynomial can't currently handle it\n const int num_dims = 2;\n mwSize dims[num_dims];\n for (int i = 0; i < num_dims_mex; i++) {\n dims[i] = static_cast(mxGetPr(dim_mex)[i]);\n }\n for (int i = num_dims_mex; i < num_dims; i++)\n dims[i] = 1;\n\n size_t product_of_dimensions = dims[0]; \/\/ d\n for (int i = 1; i < num_dims; ++i) {\n product_of_dimensions *= dims[i];\n }\n\n size_t num_coefficients = number_of_elements \/ (num_segments * product_of_dimensions); \/\/ k\n\n vector::PolynomialMatrix> polynomial_matrices;\n polynomial_matrices.reserve(num_segments);\n for (mwSize segment_index = 0; segment_index < num_segments; segment_index++) {\n PiecewisePolynomial::PolynomialMatrix polynomial_matrix(dims[0], dims[1]);\n for (mwSize i = 0; i < product_of_dimensions; i++) {\n VectorXd coefficients(num_coefficients);\n mwSize row = segment_index * product_of_dimensions + i;\n for (mwSize coefficient_index = 0; coefficient_index < num_coefficients; coefficient_index++) {\n mwSize sub[] = {row, num_coefficients - coefficient_index - 1}; \/\/ Matlab's reverse coefficient indexing...\n coefficients[coefficient_index] = *(mxGetPr(coefs_mex) + sub2ind(num_coefs_mex_dims, coefs_mex_dims, sub));\n }\n polynomial_matrix(i) = Polynomial(coefficients);\n }\n polynomial_matrices.push_back(polynomial_matrix);\n }\n\n return PiecewisePolynomial(polynomial_matrices, breaks);\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) \n{\n\n PiecewisePolynomial pp; \/\/this needs to come in as input\n pp = matlabPPFormToPiecewisePolynomial(prhs[0]);\n Map A(mxGetPrSafe(prhs[1]));\n Map B(mxGetPrSafe(prhs[2]), 4, 2);\n Map C(mxGetPrSafe(prhs[3]), 2, 4);\n Map D(mxGetPrSafe(prhs[4]));\n Map Q(mxGetPrSafe(prhs[5]));\n Map R(mxGetPrSafe(prhs[6]));\n Map Q1(mxGetPrSafe(prhs[7]));\n Map R1(mxGetPrSafe(prhs[8]));\n Map N(mxGetPrSafe(prhs[9]), 4, 2);\n Map S(mxGetPrSafe(prhs[10]));\n\n size_t n = static_cast(pp.getNumberOfSegments());\n \n int d = pp.getSegmentPolynomialDegree(0);\n\n for (size_t i = 1; i < n; i++) {\n assert(pp.getSegmentPolynomialDegree(i) == d);\n }\n\n VectorXd dt(n);\n\n std::vector breaks = pp.getSegmentTimes();\n\n for(size_t i = 0; i < n; i++) {\n dt(i) = breaks[i + 1] - breaks[i];\n }\n\n size_t k = d + 1;\n \n MatrixXd zmp_tf = pp.value(pp.getEndTime());\n\n \n PiecewisePolynomial zbar_pp = pp - zmp_tf;\n\n Matrix2d R1i = R1.inverse();\n\n MatrixXd NB = N.transpose() + B.transpose() * S; \/\/2 x 4\n Matrix4d A2 = NB.transpose() * R1i * B.transpose() - A.transpose();\n MatrixXd B2 = 2 * (C.transpose() - NB.transpose() * R1i * D) * Q; \/\/4 x 2\n\n Matrix4d A2i = A2.inverse();\n\n\n MatrixXd alpha = MatrixXd::Zero(4, n);\n\n vector beta;\n\n for(size_t i = 0; i < n ; i++) {\n beta.push_back(MatrixXd::Zero(4, k));\n }\n\n VectorXd s1dt;\n for (int j = n - 1; j >= 0; j--) { \n \n auto poly_mat = zbar_pp.getPolynomialMatrix(j);\n size_t nq = poly_mat.rows();\n MatrixXd poly_coeffs = MatrixXd::Zero(nq, k);\n\n for (size_t x = 0; x < nq; x++) {\n poly_coeffs.row(x) = poly_mat(x).getCoefficients().transpose();\n } \n \n beta[j].col(k - 1) = -A2i * B2 * poly_coeffs.col(k - 1); \/\/correct\n \n for (int i = k - 2; i >= 0; i--) {\n beta[j].col(i) = A2i * ((i+1) * beta[j].col(i + 1) - B2 * poly_coeffs.col(i)); \/\/correct\n }\n \n if(j == n - 1) {\n s1dt = VectorXd::Zero(4);\n } else {\n s1dt = alpha.col(j+1) + beta[j + 1].col(0);\n }\n\n VectorXd dtpow(k - 1);\n for(size_t p = 0; p < k; p++) { \n dtpow(p) = pow(dt(j), p);\n }\n\n alpha.col(j) = expm(A2*dt(j)).inverse() * (s1dt - beta[j]*dtpow);\n }\n\n cout << alpha << endl;\n\n return;\n\n \/\/matlabPPFormToPiecewisePolynomial\n\n \/\/const mxArray* mex_breaks = mxGetFieldOrPropertySafe(array, \"breaks\");\n \/\/const mxArray* mex_coefs = mxGetFieldOrPropertySafe(array, \"gamma\");\n \/\/PiecewisePolynomial piecewise_polynomial_part = matlabCoefsAndBreaksToPiecewisePolynomial(mex_coefs, mex_breaks, false);\n \n \/\/ExpPlusPPTrajectory(breaks,K,A,alpha,gamma)\n \/\/ExponentialPlusPiecewisePolynomial(Matrix4d::Identity)\n \/\/ExponentialPlusPiecewisePolynomial(const Eigen::MatrixBase& K, const Eigen::MatrixBase& A, const Eigen::MatrixBase& alpha, const PiecewisePolynomial& piecewise_polynomial_part)\n \/\/s1traj = ExpPlusPPTrajectory(breaks,eye(4),A2,alpha,beta);\n \/\/build ExponentialPlusPiecewisePolynomial with alpha and beta here....\n\n}\nbuilds s1traj as an ExponentialPlusPiecewisePolynomial trajectory using alpha and beta#include \"mex.h\"\n#include \n#include \"drakeUtil.h\"\n#include \"RigidBodyManipulator.h\"\n#include \n#include \n#include \"drake\/ExponentialPlusPiecewisePolynomial.h\"\n#include \"math.h\"\n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXd expm(const MatrixXd& A) {\n MatrixXd F;\n MatrixExponential(A).compute(F);\n return F;\n}\n\nPiecewisePolynomial matlabPPFormToPiecewisePolynomial(const mxArray* pp)\n{\n vector breaks = matlabToStdVector(mxGetFieldSafe(pp, \"breaks\"));\n size_t num_segments = breaks.size() - 1; \/\/ l\n\n const mxArray* coefs_mex = mxGetFieldSafe(pp, \"coefs\"); \/\/ a d*l x k matrix\n const size_t* coefs_mex_dims = mxGetDimensions(coefs_mex);\n int num_coefs_mex_dims = mxGetNumberOfDimensions(coefs_mex);\n\n size_t number_of_elements = mxGetNumberOfElements(coefs_mex);\n\n const mxArray* dim_mex = mxGetFieldSafe(pp, \"dim\");\n int num_dims_mex = mxGetNumberOfElements(dim_mex);\n if (num_dims_mex == 0 | num_dims_mex > 2)\n throw runtime_error(\"case not handled\"); \/\/ because PiecewisePolynomial can't currently handle it\n const int num_dims = 2;\n mwSize dims[num_dims];\n for (int i = 0; i < num_dims_mex; i++) {\n dims[i] = static_cast(mxGetPr(dim_mex)[i]);\n }\n for (int i = num_dims_mex; i < num_dims; i++)\n dims[i] = 1;\n\n size_t product_of_dimensions = dims[0]; \/\/ d\n for (int i = 1; i < num_dims; ++i) {\n product_of_dimensions *= dims[i];\n }\n\n size_t num_coefficients = number_of_elements \/ (num_segments * product_of_dimensions); \/\/ k\n\n vector::PolynomialMatrix> polynomial_matrices;\n polynomial_matrices.reserve(num_segments);\n for (mwSize segment_index = 0; segment_index < num_segments; segment_index++) {\n PiecewisePolynomial::PolynomialMatrix polynomial_matrix(dims[0], dims[1]);\n for (mwSize i = 0; i < product_of_dimensions; i++) {\n VectorXd coefficients(num_coefficients);\n mwSize row = segment_index * product_of_dimensions + i;\n for (mwSize coefficient_index = 0; coefficient_index < num_coefficients; coefficient_index++) {\n mwSize sub[] = {row, num_coefficients - coefficient_index - 1}; \/\/ Matlab's reverse coefficient indexing...\n coefficients[coefficient_index] = *(mxGetPr(coefs_mex) + sub2ind(num_coefs_mex_dims, coefs_mex_dims, sub));\n }\n polynomial_matrix(i) = Polynomial(coefficients);\n }\n polynomial_matrices.push_back(polynomial_matrix);\n }\n\n return PiecewisePolynomial(polynomial_matrices, breaks);\n}\n\n\/\/func sig: \n\/\/computeS1Trajmex(dZMP.pp, A, B, C, D, Q, R, Q1, R1, N, S); \n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) \n{\n auto pp = matlabPPFormToPiecewisePolynomial(prhs[0]);\n Map A(mxGetPrSafe(prhs[1]));\n Map B(mxGetPrSafe(prhs[2]), 4, 2);\n Map C(mxGetPrSafe(prhs[3]), 2, 4);\n Map D(mxGetPrSafe(prhs[4]));\n Map Q(mxGetPrSafe(prhs[5]));\n Map R(mxGetPrSafe(prhs[6]));\n Map Q1(mxGetPrSafe(prhs[7]));\n Map R1(mxGetPrSafe(prhs[8]));\n Map N(mxGetPrSafe(prhs[9]), 4, 2);\n Map S(mxGetPrSafe(prhs[10]));\n\n size_t n = static_cast(pp.getNumberOfSegments());\n int d = pp.getSegmentPolynomialDegree(0);\n size_t k = d + 1;\n\n for (size_t i = 1; i < n; i++) {\n assert(pp.getSegmentPolynomialDegree(i) == d);\n }\n\n VectorXd dt(n);\n std::vector breaks = pp.getSegmentTimes();\n\n for (size_t i = 0; i < n; i++) {\n dt(i) = breaks[i + 1] - breaks[i];\n } \n \n MatrixXd zmp_tf = pp.value(pp.getEndTime());\n PiecewisePolynomial zbar_pp = pp - zmp_tf;\n\n Matrix2d R1i = R1.inverse();\n MatrixXd NB = N.transpose() + B.transpose() * S; \/\/2 x 4\n Matrix4d A2 = NB.transpose() * R1i * B.transpose() - A.transpose();\n MatrixXd B2 = 2 * (C.transpose() - NB.transpose() * R1i * D) * Q; \/\/4 x 2\n Matrix4d A2i = A2.inverse();\n\n\n MatrixXd alpha = MatrixXd::Zero(4, n);\n\n vector beta;\n VectorXd s1dt;\n \n for (size_t i = 0; i < n ; i++) {\n beta.push_back(MatrixXd::Zero(4, k));\n }\n\n for (int j = n - 1; j >= 0; j--) { \n\n auto poly_mat = zbar_pp.getPolynomialMatrix(j);\n size_t nq = poly_mat.rows();\n MatrixXd poly_coeffs = MatrixXd::Zero(nq, k);\n\n for (size_t x = 0; x < nq; x++) {\n poly_coeffs.row(x) = poly_mat(x).getCoefficients().transpose();\n } \n \n beta[j].col(k - 1) = -A2i * B2 * poly_coeffs.col(k - 1);\n \n for (int i = k - 2; i >= 0; i--) {\n beta[j].col(i) = A2i * ((i+1) * beta[j].col(i + 1) - B2 * poly_coeffs.col(i));\n }\n \n if (j == n - 1) {\n s1dt = VectorXd::Zero(4);\n } else {\n s1dt = alpha.col(j+1) + beta[j + 1].col(0);\n }\n\n VectorXd dtpow(k - 1);\n for (size_t p = 0; p < k; p++) { \n dtpow(p) = pow(dt(j), p);\n }\n\n alpha.col(j) = expm(A2*dt(j)).inverse() * (s1dt - beta[j]*dtpow);\n }\n \n vector::PolynomialMatrix> polynomial_matrices;\n for (int segment = 0; segment < n ; segment++) {\n PiecewisePolynomial::PolynomialMatrix polynomial_matrix(4, 1);\n for(int row = 0; row < 4; row++) {\n polynomial_matrix(row) = Polynomial(beta[segment].row(row));\n }\n polynomial_matrices.push_back(polynomial_matrix);\n }\n\n PiecewisePolynomial pp_part = PiecewisePolynomial(polynomial_matrices, breaks);\n auto s1traj = ExponentialPlusPiecewisePolynomial(Matrix4d::Identity(), A2, alpha, pp_part);\n cout << s1traj.value(0) << endl;\n \/\/do stuff with s1traj\n}\n<|endoftext|>"} {"text":"\/*\n * pHashTest.cpp\n *\n * Created on: 25 Jul 2013\n * Author: nicholas\n *\/\n\n#include \n#include \n#include \"..\/..\/include\/hash\/ImagePHash.hpp\"\n#include \n\n\nusing namespace Magick;\n\nTEST(ImagePHashTest, hashImage) {\n\tImagePHash iph;\n\tlong pHash = iph.getLongHash(\"src\/test\/hash\/testImage.jpg\");\n\tASSERT_EQ(7655956633439617023,pHash);\n}\n\nint main(int argc, char **argv) {\n\t BasicConfigurator config;\n\t config.configure();\n::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n\nUpdated ImagePHash test\/*\n * pHashTest.cpp\n *\n * Created on: 25 Jul 2013\n * Author: nicholas\n *\/\n\n#include \n#include \n#include \"..\/..\/include\/hash\/ImagePHash.hpp\"\n#include \n\n\nusing namespace Magick;\n\nTEST(ImagePHashTest, hashImage) {\n\tImagePHash iph;\n\tlong pHash = iph.getLongHash(\"src\/test\/hash\/testImage.jpg\");\n\tASSERT_EQ(1061781947002206,pHash);\n}\n\nint main(int argc, char **argv) {\n\t BasicConfigurator config;\n\t config.configure();\n::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#ifndef __APPLE__\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"platform\/platform.h\"\n#include \"platformPOSIX\/platformPOSIX.h\"\n#include \"platform\/platformCPUCount.h\"\n\n#include \"console\/console.h\"\n\n#include \n\nPlatform::SystemInfo_struct Platform::SystemInfo;\n\nstatic inline void rtrim(std::string &s)\n{\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n}\n\nstatic inline void ltrim(std::string &s)\n{\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n}\n\nvoid getCPUInformation()\n{\n std::string vendorString;\n std::string brandString;\n\n std::ifstream cpuInfo(\"\/proc\/cpuinfo\");\n\n U32 logicalCoreCount = 0;\n U32 physicalCoreCount = 1;\n\n if (cpuInfo.is_open())\n {\n \/\/ Load every line of the CPU Info\n std::string line;\n\n while (std::getline(cpuInfo, line))\n {\n std::string fieldName = line.substr(0, line.find(\":\"));\n rtrim(fieldName);\n\n \/\/ Entries are newline separated\n if (fieldName == \"\")\n {\n ++logicalCoreCount;\n continue;\n }\n\n std::string fieldValue = line.substr(line.find(\":\") + 1, line.length());\n ltrim(fieldValue);\n rtrim(fieldValue);\n\n \/\/ Load fields\n if (fieldName == \"vendor_id\")\n {\n vendorString = fieldValue.c_str();\n }\n else if (fieldName == \"model name\")\n {\n brandString = fieldValue.c_str();\n }\n else if (fieldName == \"cpu cores\")\n {\n physicalCoreCount = dAtoui(fieldValue.c_str());\n }\n else if (fieldName == \"flags\")\n {\n std::vector flags;\n std::istringstream flagStream(fieldValue);\n\n std::string currentFlag;\n while (std::getline(flagStream, currentFlag, ' '))\n {\n flags.push_back(currentFlag);\n }\n\n \/\/ Set CPU flags\n if (std::find(flags.begin(), flags.end(), \"fpu\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_FPU;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse3\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE3;\n }\n\n if (std::find(flags.begin(), flags.end(), \"avx\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_AVX;\n }\n\n if (std::find(flags.begin(), flags.end(), \"ssse3\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE3ex;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse2\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE2;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse4_1\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE4_1;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse4_2\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE4_2;\n }\n\n if (std::find(flags.begin(), flags.end(), \"mmx\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_MMX;\n }\n }\n }\n\n cpuInfo.close();\n }\n else\n {\n logicalCoreCount = 1;\n }\n\n Platform::SystemInfo.processor.numLogicalProcessors = logicalCoreCount;\n Platform::SystemInfo.processor.numPhysicalProcessors = physicalCoreCount;\n Platform::SystemInfo.processor.isHyperThreaded = logicalCoreCount != physicalCoreCount;\n Platform::SystemInfo.processor.isMultiCore = physicalCoreCount != 1;\n Platform::SystemInfo.processor.numLogicalProcessors = logicalCoreCount;\n Platform::SystemInfo.processor.numPhysicalProcessors = physicalCoreCount;\n if (Platform::SystemInfo.processor.isMultiCore)\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_MP;\n }\n\n \/\/ Load processor base frequency\n std::ifstream baseFrequencyStream(\"\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/base_frequency\");\n if (baseFrequencyStream.is_open())\n {\n U32 baseFrequencyKHz = 0;\n baseFrequencyStream >> baseFrequencyKHz;\n\n Platform::SystemInfo.processor.mhz = baseFrequencyKHz \/ 1000;\n baseFrequencyStream.close();\n }\n\n SetProcessorInfo(Platform::SystemInfo.processor, vendorString.c_str(), brandString.c_str());\n}\n\nvoid Processor::init() \n{\n getCPUInformation();\n\n#if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_X32)\n \/\/ Set sane default information\n Platform::SystemInfo.processor.properties |= CPU_PROP_C | CPU_PROP_FPU | CPU_PROP_LE ;\n\n#elif defined(TORQUE_CPU_ARM32) || defined(TORQUE_CPU_ARM64)\n Platform::SystemInfo.processor.type = CPU_ArmCompatible;\n Platform::SystemInfo.processor.name = StringTable->insert(\"Unknown ARM Processor\");\n Platform::SystemInfo.processor.properties = CPU_PROP_C;\n#else\n#warning Unsupported CPU\n#endif\n\n \/\/ Set 64bit flag\n#if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)\n Platform::SystemInfo.processor.properties |= CPU_PROP_64bit;\n#endif\n\n \/\/ Once CPU information is resolved, produce an output like Windows does\n Con::printf(\"Processor Init:\");\n Con::printf(\" Processor: %s\", Platform::SystemInfo.processor.name);\n if (Platform::SystemInfo.processor.properties & CPU_PROP_MMX)\n Con::printf(\" MMX detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE)\n Con::printf(\" SSE detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE2)\n Con::printf(\" SSE2 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3)\n Con::printf(\" SSE3 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_1)\n Con::printf(\" SSE4.1 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_2)\n Con::printf(\" SSE4.2 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_AVX)\n Con::printf(\" AVX detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3ex)\n Con::printf(\" SSE3ex detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_MP)\n Con::printf(\" MultiCore CPU detected [%i cores, %i logical]\", Platform::SystemInfo.processor.numPhysicalProcessors, Platform::SystemInfo.processor.numLogicalProcessors);\n\n Con::printf(\" \");\n}\n\nnamespace CPUInfo\n{\n EConfig CPUCount(U32 &logical, U32 &physical)\n {\n \/\/ We don't set logical or physical here because it's already been determined by this point\n if (Platform::SystemInfo.processor.isHyperThreaded && Platform::SystemInfo.processor.numPhysicalProcessors == 1)\n {\n return CONFIG_SingleCoreHTEnabled;\n }\n else if (!Platform::SystemInfo.processor.isHyperThreaded && Platform::SystemInfo.processor.numPhysicalProcessors > 1)\n {\n return CONFIG_MultiCoreAndHTNotCapable;\n }\n else if (!Platform::SystemInfo.processor.isHyperThreaded && Platform::SystemInfo.processor.numPhysicalProcessors == 1)\n {\n return CONFIG_SingleCoreAndHTNotCapable; \n }\n\n return CONFIG_MultiCoreAndHTEnabled;\n }\n}; \/\/ namespace CPUInfo\n\n#endif* Adjustment: Add static keyword to getCPUInformation in POSIXCPUInfo.\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#ifndef __APPLE__\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"platform\/platform.h\"\n#include \"platformPOSIX\/platformPOSIX.h\"\n#include \"platform\/platformCPUCount.h\"\n\n#include \"console\/console.h\"\n\n#include \n\nPlatform::SystemInfo_struct Platform::SystemInfo;\n\nstatic inline void rtrim(std::string &s)\n{\n s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun(std::isspace))).base(), s.end());\n}\n\nstatic inline void ltrim(std::string &s)\n{\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun(std::isspace))));\n}\n\nstatic void getCPUInformation()\n{\n std::string vendorString;\n std::string brandString;\n\n std::ifstream cpuInfo(\"\/proc\/cpuinfo\");\n\n U32 logicalCoreCount = 0;\n U32 physicalCoreCount = 1;\n\n if (cpuInfo.is_open())\n {\n \/\/ Load every line of the CPU Info\n std::string line;\n\n while (std::getline(cpuInfo, line))\n {\n std::string fieldName = line.substr(0, line.find(\":\"));\n rtrim(fieldName);\n\n \/\/ Entries are newline separated\n if (fieldName == \"\")\n {\n ++logicalCoreCount;\n continue;\n }\n\n std::string fieldValue = line.substr(line.find(\":\") + 1, line.length());\n ltrim(fieldValue);\n rtrim(fieldValue);\n\n \/\/ Load fields\n if (fieldName == \"vendor_id\")\n {\n vendorString = fieldValue.c_str();\n }\n else if (fieldName == \"model name\")\n {\n brandString = fieldValue.c_str();\n }\n else if (fieldName == \"cpu cores\")\n {\n physicalCoreCount = dAtoui(fieldValue.c_str());\n }\n else if (fieldName == \"flags\")\n {\n std::vector flags;\n std::istringstream flagStream(fieldValue);\n\n std::string currentFlag;\n while (std::getline(flagStream, currentFlag, ' '))\n {\n flags.push_back(currentFlag);\n }\n\n \/\/ Set CPU flags\n if (std::find(flags.begin(), flags.end(), \"fpu\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_FPU;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse3\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE3;\n }\n\n if (std::find(flags.begin(), flags.end(), \"avx\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_AVX;\n }\n\n if (std::find(flags.begin(), flags.end(), \"ssse3\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE3ex;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse2\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE2;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse4_1\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE4_1;\n }\n\n if (std::find(flags.begin(), flags.end(), \"sse4_2\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_SSE4_2;\n }\n\n if (std::find(flags.begin(), flags.end(), \"mmx\") != flags.end())\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_MMX;\n }\n }\n }\n\n cpuInfo.close();\n }\n else\n {\n logicalCoreCount = 1;\n }\n\n Platform::SystemInfo.processor.numLogicalProcessors = logicalCoreCount;\n Platform::SystemInfo.processor.numPhysicalProcessors = physicalCoreCount;\n Platform::SystemInfo.processor.isHyperThreaded = logicalCoreCount != physicalCoreCount;\n Platform::SystemInfo.processor.isMultiCore = physicalCoreCount != 1;\n Platform::SystemInfo.processor.numLogicalProcessors = logicalCoreCount;\n Platform::SystemInfo.processor.numPhysicalProcessors = physicalCoreCount;\n if (Platform::SystemInfo.processor.isMultiCore)\n {\n Platform::SystemInfo.processor.properties |= CPU_PROP_MP;\n }\n\n \/\/ Load processor base frequency\n std::ifstream baseFrequencyStream(\"\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/base_frequency\");\n if (baseFrequencyStream.is_open())\n {\n U32 baseFrequencyKHz = 0;\n baseFrequencyStream >> baseFrequencyKHz;\n\n Platform::SystemInfo.processor.mhz = baseFrequencyKHz \/ 1000;\n baseFrequencyStream.close();\n }\n\n SetProcessorInfo(Platform::SystemInfo.processor, vendorString.c_str(), brandString.c_str());\n}\n\nvoid Processor::init() \n{\n getCPUInformation();\n\n#if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_X32)\n \/\/ Set sane default information\n Platform::SystemInfo.processor.properties |= CPU_PROP_C | CPU_PROP_FPU | CPU_PROP_LE ;\n\n#elif defined(TORQUE_CPU_ARM32) || defined(TORQUE_CPU_ARM64)\n Platform::SystemInfo.processor.type = CPU_ArmCompatible;\n Platform::SystemInfo.processor.name = StringTable->insert(\"Unknown ARM Processor\");\n Platform::SystemInfo.processor.properties = CPU_PROP_C;\n#else\n#warning Unsupported CPU\n#endif\n\n \/\/ Set 64bit flag\n#if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)\n Platform::SystemInfo.processor.properties |= CPU_PROP_64bit;\n#endif\n\n \/\/ Once CPU information is resolved, produce an output like Windows does\n Con::printf(\"Processor Init:\");\n Con::printf(\" Processor: %s\", Platform::SystemInfo.processor.name);\n if (Platform::SystemInfo.processor.properties & CPU_PROP_MMX)\n Con::printf(\" MMX detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE)\n Con::printf(\" SSE detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE2)\n Con::printf(\" SSE2 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3)\n Con::printf(\" SSE3 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_1)\n Con::printf(\" SSE4.1 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE4_2)\n Con::printf(\" SSE4.2 detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_AVX)\n Con::printf(\" AVX detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE3ex)\n Con::printf(\" SSE3ex detected\" );\n if (Platform::SystemInfo.processor.properties & CPU_PROP_MP)\n Con::printf(\" MultiCore CPU detected [%i cores, %i logical]\", Platform::SystemInfo.processor.numPhysicalProcessors, Platform::SystemInfo.processor.numLogicalProcessors);\n\n Con::printf(\" \");\n}\n\nnamespace CPUInfo\n{\n EConfig CPUCount(U32 &logical, U32 &physical)\n {\n \/\/ We don't set logical or physical here because it's already been determined by this point\n if (Platform::SystemInfo.processor.isHyperThreaded && Platform::SystemInfo.processor.numPhysicalProcessors == 1)\n {\n return CONFIG_SingleCoreHTEnabled;\n }\n else if (!Platform::SystemInfo.processor.isHyperThreaded && Platform::SystemInfo.processor.numPhysicalProcessors > 1)\n {\n return CONFIG_MultiCoreAndHTNotCapable;\n }\n else if (!Platform::SystemInfo.processor.isHyperThreaded && Platform::SystemInfo.processor.numPhysicalProcessors == 1)\n {\n return CONFIG_SingleCoreAndHTNotCapable; \n }\n\n return CONFIG_MultiCoreAndHTEnabled;\n }\n}; \/\/ namespace CPUInfo\n\n#endif<|endoftext|>"} {"text":"\/*\nCopyright (c) 2013, 2014, Ilja Honkonen\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this\n list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n* Neither the name of copyright holders nor the names of their contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifndef GET_VAR_DATATYPE_HPP\n#define GET_VAR_DATATYPE_HPP\n\n#if defined(MPI_VERSION) && (MPI_VERSION >= 2)\n\n#include \"boost\/function_types\/property_tags.hpp\"\n#include \"boost\/mpl\/vector.hpp\"\n#include \"boost\/tti\/has_member_function.hpp\"\n#include \"complex\"\n#include \"cstddef\"\n#include \"cstdint\"\n#include \"mpi.h\"\n#include \"tuple\"\n\n\nnamespace gensimcell {\nnamespace detail {\n\n\nBOOST_TTI_HAS_MEMBER_FUNCTION(get_mpi_datatype)\n\n\n\/*!\nReturns the mpi transfer info of given\nvariable with a get_mpi_datatype function.\n*\/\ntemplate <\n\tclass Variable_T,\n\tstd::size_t Number_Of_Items = 0\n> std::tuple<\n\tvoid*,\n\tint,\n\tMPI_Datatype\n> get_var_datatype(const Variable_T& variable)\n{\n\tstatic_assert(\n\t\thas_member_function_get_mpi_datatype<\n\t\t\tVariable_T,\n\t\t\tstd::tuple\n\t\t>::value\n\t\tor\n\t\thas_member_function_get_mpi_datatype<\n\t\t\tVariable_T,\n\t\t\tstd::tuple,\n\t\t\tboost::mpl::vector<>,\n\t\t\tboost::function_types::const_qualified\n\t\t>::value,\n\t\t\"Given Variable_T does not have a get_mpi_datatype() \"\n\t\t\"member function that must specify the data to be \"\n\t\t\"transferred by MPI, see the Particles class in \"\n\t\t\"gensimcell\/examples\/particle_propagation\/parallel\/particle_variables.hpp \"\n\t\t\"for an example.\"\n\t);\n\treturn variable.get_mpi_datatype();\n}\n\n\n\/*!\nSpecializations of get_var_datatype for\nstandard C++ types with an MPI equivalent.\n*\/\n#define GENSIMCELL_GET_VAR_DATATYPE(GIVEN_CPP_TYPE, GIVEN_MPI_TYPE) \\\ntemplate <> std::tuple< \\\n\tvoid*, \\\n\tint, \\\n\tMPI_Datatype \\\n> get_var_datatype(const GIVEN_CPP_TYPE& variable) \\\n{ \\\n\treturn std::make_tuple((void*) &variable, 1, GIVEN_MPI_TYPE); \\\n}\n\nGENSIMCELL_GET_VAR_DATATYPE(bool, MPI_CXX_BOOL)\nGENSIMCELL_GET_VAR_DATATYPE(char, MPI_CHAR)\nGENSIMCELL_GET_VAR_DATATYPE(double, MPI_DOUBLE)\nGENSIMCELL_GET_VAR_DATATYPE(float, MPI_FLOAT)\nGENSIMCELL_GET_VAR_DATATYPE(long double, MPI_LONG_DOUBLE)\nGENSIMCELL_GET_VAR_DATATYPE(signed char, MPI_SIGNED_CHAR)\nGENSIMCELL_GET_VAR_DATATYPE(signed int, MPI_INT)\nGENSIMCELL_GET_VAR_DATATYPE(signed long int, MPI_LONG)\nGENSIMCELL_GET_VAR_DATATYPE(signed long long int, MPI_LONG_LONG_INT)\nGENSIMCELL_GET_VAR_DATATYPE(signed short int, MPI_SHORT)\nGENSIMCELL_GET_VAR_DATATYPE(std::complex, MPI_CXX_FLOAT_COMPLEX)\nGENSIMCELL_GET_VAR_DATATYPE(std::complex, MPI_CXX_DOUBLE_COMPLEX)\nGENSIMCELL_GET_VAR_DATATYPE(std::complex, MPI_CXX_LONG_DOUBLE_COMPLEX)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned char, MPI_UNSIGNED_CHAR)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned int, MPI_UNSIGNED)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned long int, MPI_UNSIGNED_LONG)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned long long int, MPI_UNSIGNED_LONG_LONG)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned short int, MPI_UNSIGNED_SHORT)\nGENSIMCELL_GET_VAR_DATATYPE(wchar_t, MPI_WCHAR)\n\n\n\/*!\nSpecializations of get_var_datatype for standard\nC++ types with an MPI equivalent inside an array.\n*\/\n#define GENSIMCELL_GET_ARRAY_VAR_DATATYPE(GIVEN_CPP_TYPE, GIVEN_MPI_TYPE) \\\ntemplate < \\\n\tstd::size_t Number_Of_Items \\\n> std::tuple< \\\n\tvoid*, \\\n\tint, \\\n\tMPI_Datatype \\\n> get_var_datatype( \\\n\tconst std::array< \\\n\t\tGIVEN_CPP_TYPE, \\\n\t\tNumber_Of_Items \\\n\t>& variable \\\n) { \\\n\treturn std::make_tuple( \\\n\t\t(void*) variable.data(), \\\n\t\tNumber_Of_Items, \\\n\t\tGIVEN_MPI_TYPE \\\n\t); \\\n}\n\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(bool, MPI_CXX_BOOL)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(char, MPI_CHAR)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(double, MPI_DOUBLE)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(float, MPI_FLOAT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(long double, MPI_LONG_DOUBLE)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed char, MPI_SIGNED_CHAR)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed int, MPI_INT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed long int, MPI_LONG)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed long long int, MPI_LONG_LONG_INT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed short int, MPI_SHORT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(std::complex, MPI_CXX_FLOAT_COMPLEX)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(std::complex, MPI_CXX_DOUBLE_COMPLEX)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(std::complex, MPI_CXX_LONG_DOUBLE_COMPLEX)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned char, MPI_UNSIGNED_CHAR)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned int, MPI_UNSIGNED)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned long int, MPI_UNSIGNED_LONG)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned long long int, MPI_UNSIGNED_LONG_LONG)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned short int, MPI_UNSIGNED_SHORT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(wchar_t, MPI_WCHAR)\n\n\n} \/\/ namespace detail\n} \/\/ namespace gensimcell\n\n#endif \/\/ ifdef MPI_VERSION\n\n#endif \/\/ ifndef GET_VAR_DATATYPE_HPP\nPut C++ types behind ifdefs in get_var_datatype().\/*\nFunctions that return the MPI transfer information of some C++ types.\n\nCopyright (c) 2013, 2014, Ilja Honkonen\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this\n list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n* Neither the name of copyright holders nor the names of their contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#ifndef GET_VAR_DATATYPE_HPP\n#define GET_VAR_DATATYPE_HPP\n\n#if defined(MPI_VERSION) && (MPI_VERSION >= 2)\n\n#include \"boost\/function_types\/property_tags.hpp\"\n#include \"boost\/mpl\/vector.hpp\"\n#include \"boost\/tti\/has_member_function.hpp\"\n#include \"complex\"\n#include \"cstddef\"\n#include \"cstdint\"\n#include \"mpi.h\"\n#include \"tuple\"\n\n\nnamespace gensimcell {\nnamespace detail {\n\n\nBOOST_TTI_HAS_MEMBER_FUNCTION(get_mpi_datatype)\n\n\n\/*!\nReturns the mpi transfer info of given\nvariable with a get_mpi_datatype function.\n*\/\ntemplate <\n\tclass Variable_T,\n\tstd::size_t Number_Of_Items = 0\n> std::tuple<\n\tvoid*,\n\tint,\n\tMPI_Datatype\n> get_var_datatype(const Variable_T& variable)\n{\n\tstatic_assert(\n\t\thas_member_function_get_mpi_datatype<\n\t\t\tVariable_T,\n\t\t\tstd::tuple\n\t\t>::value\n\t\tor\n\t\thas_member_function_get_mpi_datatype<\n\t\t\tVariable_T,\n\t\t\tstd::tuple,\n\t\t\tboost::mpl::vector<>,\n\t\t\tboost::function_types::const_qualified\n\t\t>::value,\n\t\t\"Given Variable_T does not have a get_mpi_datatype() \"\n\t\t\"member function that must specify the data to be \"\n\t\t\"transferred by MPI, see the Particles class in \"\n\t\t\"gensimcell\/examples\/particle_propagation\/parallel\/particle_variables.hpp \"\n\t\t\"for an example.\"\n\t);\n\treturn variable.get_mpi_datatype();\n}\n\n\n\/*!\nSpecializations of get_var_datatype for\nstandard C++ types with an MPI equivalent.\n*\/\n#define GENSIMCELL_GET_VAR_DATATYPE(GIVEN_CPP_TYPE, GIVEN_MPI_TYPE) \\\ntemplate <> std::tuple< \\\n\tvoid*, \\\n\tint, \\\n\tMPI_Datatype \\\n> get_var_datatype(const GIVEN_CPP_TYPE& variable) \\\n{ \\\n\treturn std::make_tuple((void*) &variable, 1, GIVEN_MPI_TYPE); \\\n}\n\nGENSIMCELL_GET_VAR_DATATYPE(char, MPI_CHAR)\nGENSIMCELL_GET_VAR_DATATYPE(double, MPI_DOUBLE)\nGENSIMCELL_GET_VAR_DATATYPE(float, MPI_FLOAT)\nGENSIMCELL_GET_VAR_DATATYPE(long double, MPI_LONG_DOUBLE)\nGENSIMCELL_GET_VAR_DATATYPE(signed char, MPI_SIGNED_CHAR)\nGENSIMCELL_GET_VAR_DATATYPE(signed int, MPI_INT)\nGENSIMCELL_GET_VAR_DATATYPE(signed long int, MPI_LONG)\nGENSIMCELL_GET_VAR_DATATYPE(signed long long int, MPI_LONG_LONG_INT)\nGENSIMCELL_GET_VAR_DATATYPE(signed short int, MPI_SHORT)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned char, MPI_UNSIGNED_CHAR)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned int, MPI_UNSIGNED)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned long int, MPI_UNSIGNED_LONG)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned long long int, MPI_UNSIGNED_LONG_LONG)\nGENSIMCELL_GET_VAR_DATATYPE(unsigned short int, MPI_UNSIGNED_SHORT)\nGENSIMCELL_GET_VAR_DATATYPE(wchar_t, MPI_WCHAR)\n\n#ifdef MPI_CXX_BOOL\nGENSIMCELL_GET_VAR_DATATYPE(bool, MPI_CXX_BOOL)\n#endif\n\n#ifdef MPI_CXX_FLOAT_COMPLEX\nGENSIMCELL_GET_VAR_DATATYPE(std::complex, MPI_CXX_FLOAT_COMPLEX)\n#endif\n\n#ifdef MPI_CXX_DOUBLE_COMPLEX\nGENSIMCELL_GET_VAR_DATATYPE(std::complex, MPI_CXX_DOUBLE_COMPLEX)\n#endif\n\n#ifdef MPI_CXX_LONG_DOUBLE_COMPLEX\nGENSIMCELL_GET_VAR_DATATYPE(std::complex, MPI_CXX_LONG_DOUBLE_COMPLEX)\n#endif\n\n\n\/*!\nSpecializations of get_var_datatype for standard\nC++ types with an MPI equivalent inside an array.\n*\/\n#define GENSIMCELL_GET_ARRAY_VAR_DATATYPE(GIVEN_CPP_TYPE, GIVEN_MPI_TYPE) \\\ntemplate < \\\n\tstd::size_t Number_Of_Items \\\n> std::tuple< \\\n\tvoid*, \\\n\tint, \\\n\tMPI_Datatype \\\n> get_var_datatype( \\\n\tconst std::array< \\\n\t\tGIVEN_CPP_TYPE, \\\n\t\tNumber_Of_Items \\\n\t>& variable \\\n) { \\\n\treturn std::make_tuple( \\\n\t\t(void*) variable.data(), \\\n\t\tNumber_Of_Items, \\\n\t\tGIVEN_MPI_TYPE \\\n\t); \\\n}\n\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(char, MPI_CHAR)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(double, MPI_DOUBLE)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(float, MPI_FLOAT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(long double, MPI_LONG_DOUBLE)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed char, MPI_SIGNED_CHAR)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed int, MPI_INT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed long int, MPI_LONG)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed long long int, MPI_LONG_LONG_INT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(signed short int, MPI_SHORT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned char, MPI_UNSIGNED_CHAR)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned int, MPI_UNSIGNED)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned long int, MPI_UNSIGNED_LONG)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned long long int, MPI_UNSIGNED_LONG_LONG)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(unsigned short int, MPI_UNSIGNED_SHORT)\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(wchar_t, MPI_WCHAR)\n\n#ifdef MPI_CXX_BOOL\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(bool, MPI_CXX_BOOL)\n#endif\n\n#ifdef MPI_CXX_FLOAT_COMPLEX\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(std::complex, MPI_CXX_FLOAT_COMPLEX)\n#endif\n\n#ifdef MPI_CXX_DOUBLE_COMPLEX\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(std::complex, MPI_CXX_DOUBLE_COMPLEX)\n#endif\n\n#ifdef MPI_CXX_LONG_DOUBLE_COMPLEX\nGENSIMCELL_GET_ARRAY_VAR_DATATYPE(std::complex, MPI_CXX_LONG_DOUBLE_COMPLEX)\n#endif\n\n\n} \/\/ namespace detail\n} \/\/ namespace gensimcell\n\n#endif \/\/ ifdef MPI_VERSION\n\n#endif \/\/ ifndef GET_VAR_DATATYPE_HPP\n<|endoftext|>"} {"text":"\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_LOOP_HPP__\n#define __PROCESS_LOOP_HPP__\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace process {\n\n\/\/ Provides an asynchronous \"loop\" abstraction. This abstraction is\n\/\/ helpful for code that would have synchronously been written as a\n\/\/ loop but asynchronously ends up being a recursive set of functions\n\/\/ which depending on the compiler may result in a stack overflow\n\/\/ (i.e., a compiler that can't do sufficient tail call optimization\n\/\/ may add stack frames for each recursive call).\n\/\/\n\/\/ The loop abstraction takes an optional PID `pid` and uses it as the\n\/\/ execution context to run the loop. The implementation does a\n\/\/ `defer` on this `pid` to \"pop\" the stack when it needs to\n\/\/ asynchronously recurse. This also lets callers synchronize\n\/\/ execution with other code dispatching and deferring using `pid`. If\n\/\/ `None` is passed for `pid` then no `defer` is done and the stack\n\/\/ will still \"pop\" but be restarted from the execution context\n\/\/ wherever the blocked future is completed. This is usually very safe\n\/\/ when that blocked future will be completed by the IO thread, but\n\/\/ should not be used if it's completed by another process (because\n\/\/ you'll block that process until the next time the loop blocks).\n\/\/\n\/\/ The two functions passed to the loop represent the loop \"iterate\"\n\/\/ step and the loop \"body\" step respectively. Each invocation of\n\/\/ \"iterate\" returns the next value and the \"body\" returns whether or\n\/\/ not to continue looping (as well as any other processing necessary\n\/\/ of course). You can think of this synchronously as:\n\/\/\n\/\/ bool condition = true;\n\/\/ do {\n\/\/ condition = body(iterate());\n\/\/ } while (condition);\n\/\/\n\/\/ Asynchronously using recursion this might look like:\n\/\/\n\/\/ Future loop()\n\/\/ {\n\/\/ return iterate()\n\/\/ .then([](T t) {\n\/\/ return body(t)\n\/\/ .then([](bool condition) {\n\/\/ if (condition) {\n\/\/ return loop();\n\/\/ } else {\n\/\/ return Nothing();\n\/\/ }\n\/\/ });\n\/\/ });\n\/\/ }\n\/\/\n\/\/ And asynchronously using `pid` as the execution context:\n\/\/\n\/\/ Future loop()\n\/\/ {\n\/\/ return iterate()\n\/\/ .then(defer(pid, [](T t) {\n\/\/ return body(t)\n\/\/ .then(defer(pid, [](bool condition) {\n\/\/ if (condition) {\n\/\/ return loop();\n\/\/ } else {\n\/\/ return Nothing();\n\/\/ }\n\/\/ }));\n\/\/ }));\n\/\/ }\n\/\/\n\/\/ And now what this looks like using `loop`:\n\/\/\n\/\/ loop(pid,\n\/\/ []() {\n\/\/ return iterate();\n\/\/ },\n\/\/ [](T t) {\n\/\/ return body(t);\n\/\/ });\n\/\/\n\/\/ One difference between the `loop` version of the \"body\" versus the\n\/\/ other non-loop examples above is the return value is not `bool` or\n\/\/ `Future` but rather `ControlFlow` or\n\/\/ `Future>`. This enables you to return values out of\n\/\/ the loop via a `Break(...)`, for example:\n\/\/\n\/\/ loop(pid,\n\/\/ []() {\n\/\/ return iterate();\n\/\/ },\n\/\/ [](T t) {\n\/\/ if (finished(t)) {\n\/\/ return Break(SomeValue());\n\/\/ }\n\/\/ return Continue();\n\/\/ });\ntemplate ::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename CF = typename internal::unwrap::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename V = typename CF::ValueType>\nFuture loop(const Option& pid, Iterate&& iterate, Body&& body);\n\n\n\/\/ A helper for `loop` which creates a Process for us to provide an\n\/\/ execution context for running the loop.\ntemplate ::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename CF = typename internal::unwrap::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename V = typename CF::ValueType>\nFuture loop(Iterate&& iterate, Body&& body)\n{\n ProcessBase* process = new ProcessBase();\n return loop(\n spawn(process, true), \/\/ Have libprocess free `process`.\n std::forward(iterate),\n std::forward(body))\n .onAny([=]() {\n terminate(process);\n \/\/ NOTE: no need to `wait` or `delete` since the `spawn` above\n \/\/ put libprocess in control of garbage collection.\n });\n}\n\n\n\/\/ Generic \"control flow\" construct that is leveraged by\n\/\/ implementations such as `loop`. At a high-level a `ControlFlow`\n\/\/ represents some control flow statement such as `continue` or\n\/\/ `break`, however, these statements can both have values or be\n\/\/ value-less (i.e., these are meant to be composed \"functionally\" so\n\/\/ the representation of `break` captures a value that \"exits the\n\/\/ current function\" but the representation of `continue` does not).\n\/\/\n\/\/ The pattern here is to define the type\/representation of control\n\/\/ flow statements within the `ControlFlow` class (e.g.,\n\/\/ `ControlFlow::Continue` and `ControlFlow::Break`) but also provide\n\/\/ \"syntactic sugar\" to make it easier to use at the call site (e.g.,\n\/\/ the functions `Continue()` and `Break(...)`).\ntemplate \nclass ControlFlow\n{\npublic:\n using ValueType = T;\n\n enum class Statement\n {\n CONTINUE,\n BREAK\n };\n\n class Continue\n {\n public:\n Continue() = default;\n\n template \n operator ControlFlow() const\n {\n return ControlFlow(ControlFlow::Statement::CONTINUE, None());\n }\n };\n\n class Break\n {\n public:\n Break(T t) : t(std::move(t)) {}\n\n template \n operator ControlFlow() const &\n {\n return ControlFlow(ControlFlow::Statement::BREAK, t);\n }\n\n template \n operator ControlFlow() &&\n {\n return ControlFlow(ControlFlow::Statement::BREAK, std::move(t));\n }\n\n private:\n T t;\n };\n\n ControlFlow(Statement s, Option t) : s(s), t(std::move(t)) {}\n\n Statement statement() const { return s; }\n\n T& value() & { return t.get(); }\n const T& value() const & { return t.get(); }\n T&& value() && { return t.get(); }\n const T&& value() const && { return t.get(); }\n\nprivate:\n Statement s;\n Option t;\n};\n\n\n\/\/ Provides \"syntactic sugar\" for creating a `ControlFlow::Continue`.\nstruct Continue\n{\n Continue() = default;\n\n template \n operator ControlFlow() const\n {\n return typename ControlFlow::Continue();\n }\n};\n\n\n\/\/ Provides \"syntactic sugar\" for creating a `ControlFlow::Break`.\ntemplate \ntypename ControlFlow::type>::Break Break(T&& t)\n{\n return typename ControlFlow::type>::Break(\n std::forward(t));\n}\n\n\ninline ControlFlow::Break Break()\n{\n return ControlFlow::Break(Nothing());\n}\n\n\nnamespace internal {\n\ntemplate \nclass Loop : public std::enable_shared_from_this>\n{\npublic:\n Loop(const Option& pid, const Iterate& iterate, const Body& body)\n : pid(pid), iterate(iterate), body(body) {}\n\n Loop(const Option& pid, Iterate&& iterate, Body&& body)\n : pid(pid), iterate(std::move(iterate)), body(std::move(body)) {}\n\n std::shared_ptr shared()\n {\n \/\/ Must fully specify `shared_from_this` because we're templated.\n return std::enable_shared_from_this::shared_from_this();\n }\n\n std::weak_ptr weak()\n {\n return std::weak_ptr(shared());\n }\n\n Future start()\n {\n auto self = shared();\n auto weak_self = weak();\n\n \/\/ Propagating discards:\n \/\/\n \/\/ When the caller does a discard we need to propagate it to\n \/\/ either the future returned from `iterate` or the future\n \/\/ returned from `body`. One easy way to do this would be to add\n \/\/ an `onAny` callback for every future returned from `iterate`\n \/\/ and `body`, but that would be a slow memory leak that would\n \/\/ grow over time, especially if the loop was actually\n \/\/ infinite. Instead, we capture the current future that needs to\n \/\/ be discarded within a `discard` function that we'll invoke when\n \/\/ we get a discard. Because there is a race setting the `discard`\n \/\/ function and reading it out to invoke we have to synchronize\n \/\/ access using a mutex. An alternative strategy would be to use\n \/\/ something like `atomic_load` and `atomic_store` with\n \/\/ `shared_ptr` so that we can swap the current future(s)\n \/\/ atomically.\n promise.future().onDiscard([weak_self]() {\n auto self = weak_self.lock();\n if (self) {\n \/\/ We need to make a copy of the current `discard` function so\n \/\/ that we can invoke it outside of the `synchronized` block\n \/\/ in the event that discarding invokes causes the `onAny`\n \/\/ callbacks that we have added in `run` to execute which may\n \/\/ deadlock attempting to re-acquire `mutex`!\n std::function f = []() {};\n synchronized (self->mutex) {\n f = self->discard;\n }\n f();\n }\n });\n\n if (pid.isSome()) {\n \/\/ Start the loop using `pid` as the execution context.\n dispatch(pid.get(), [self]() {\n self->run(self->iterate());\n });\n } else {\n run(iterate());\n }\n\n return promise.future();\n }\n\n void run(Future next)\n {\n auto self = shared();\n\n \/\/ Reset `discard` so that we're not delaying cleanup of any\n \/\/ captured futures longer than necessary.\n \/\/\n \/\/ TODO(benh): Use `WeakFuture` in `discard` functions instead.\n synchronized (mutex) {\n discard = []() {};\n }\n\n while (next.isReady()) {\n Future> flow = body(next.get());\n if (flow.isReady()) {\n switch (flow->statement()) {\n case ControlFlow::Statement::CONTINUE: {\n next = iterate();\n continue;\n }\n case ControlFlow::Statement::BREAK: {\n promise.set(flow->value());\n return;\n }\n }\n } else {\n auto continuation = [self](const Future>& flow) {\n if (flow.isReady()) {\n switch (flow->statement()) {\n case ControlFlow::Statement::CONTINUE: {\n self->run(self->iterate());\n break;\n }\n case ControlFlow::Statement::BREAK: {\n self->promise.set(flow->value());\n break;\n }\n }\n } else if (flow.isFailed()) {\n self->promise.fail(flow.failure());\n } else if (flow.isDiscarded()) {\n self->promise.discard();\n }\n };\n\n if (pid.isSome()) {\n flow.onAny(defer(pid.get(), continuation));\n } else {\n flow.onAny(continuation);\n }\n\n if (!promise.future().hasDiscard()) {\n synchronized (mutex) {\n self->discard = [=]() mutable { flow.discard(); };\n }\n }\n\n \/\/ There's a race between when a discard occurs and the\n \/\/ `discard` function gets invoked and therefore we must\n \/\/ explicitly always do a discard. In addition, after a\n \/\/ discard occurs we'll need to explicitly do discards for\n \/\/ each new future that blocks.\n if (promise.future().hasDiscard()) {\n flow.discard();\n }\n\n return;\n }\n }\n\n auto continuation = [self](const Future& next) {\n if (next.isReady()) {\n self->run(next);\n } else if (next.isFailed()) {\n self->promise.fail(next.failure());\n } else if (next.isDiscarded()) {\n self->promise.discard();\n }\n };\n\n if (pid.isSome()) {\n next.onAny(defer(pid.get(), continuation));\n } else {\n next.onAny(continuation);\n }\n\n if (!promise.future().hasDiscard()) {\n synchronized (mutex) {\n discard = [=]() mutable { next.discard(); };\n }\n }\n\n \/\/ See comment above as to why we need to explicitly discard\n \/\/ regardless of the path the if statement took above.\n if (promise.future().hasDiscard()) {\n next.discard();\n }\n }\n\nprivate:\n const Option pid;\n Iterate iterate;\n Body body;\n Promise promise;\n\n \/\/ In order to discard the loop safely we capture the future that\n \/\/ needs to be discarded within the `discard` function and reading\n \/\/ and writing that function with a mutex.\n std::mutex mutex;\n std::function discard = []() {};\n};\n\n} \/\/ namespace internal {\n\n\ntemplate \nFuture loop(const Option& pid, Iterate&& iterate, Body&& body)\n{\n using Loop = internal::Loop<\n typename std::decay::type,\n typename std::decay::type,\n T,\n V>;\n\n std::shared_ptr loop(\n new Loop(pid, std::forward(iterate), std::forward(body)));\n\n return loop->start();\n}\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_LOOP_HPP__\nFixed unsafe usage of process pointer in loop.hpp.\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_LOOP_HPP__\n#define __PROCESS_LOOP_HPP__\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace process {\n\n\/\/ Provides an asynchronous \"loop\" abstraction. This abstraction is\n\/\/ helpful for code that would have synchronously been written as a\n\/\/ loop but asynchronously ends up being a recursive set of functions\n\/\/ which depending on the compiler may result in a stack overflow\n\/\/ (i.e., a compiler that can't do sufficient tail call optimization\n\/\/ may add stack frames for each recursive call).\n\/\/\n\/\/ The loop abstraction takes an optional PID `pid` and uses it as the\n\/\/ execution context to run the loop. The implementation does a\n\/\/ `defer` on this `pid` to \"pop\" the stack when it needs to\n\/\/ asynchronously recurse. This also lets callers synchronize\n\/\/ execution with other code dispatching and deferring using `pid`. If\n\/\/ `None` is passed for `pid` then no `defer` is done and the stack\n\/\/ will still \"pop\" but be restarted from the execution context\n\/\/ wherever the blocked future is completed. This is usually very safe\n\/\/ when that blocked future will be completed by the IO thread, but\n\/\/ should not be used if it's completed by another process (because\n\/\/ you'll block that process until the next time the loop blocks).\n\/\/\n\/\/ The two functions passed to the loop represent the loop \"iterate\"\n\/\/ step and the loop \"body\" step respectively. Each invocation of\n\/\/ \"iterate\" returns the next value and the \"body\" returns whether or\n\/\/ not to continue looping (as well as any other processing necessary\n\/\/ of course). You can think of this synchronously as:\n\/\/\n\/\/ bool condition = true;\n\/\/ do {\n\/\/ condition = body(iterate());\n\/\/ } while (condition);\n\/\/\n\/\/ Asynchronously using recursion this might look like:\n\/\/\n\/\/ Future loop()\n\/\/ {\n\/\/ return iterate()\n\/\/ .then([](T t) {\n\/\/ return body(t)\n\/\/ .then([](bool condition) {\n\/\/ if (condition) {\n\/\/ return loop();\n\/\/ } else {\n\/\/ return Nothing();\n\/\/ }\n\/\/ });\n\/\/ });\n\/\/ }\n\/\/\n\/\/ And asynchronously using `pid` as the execution context:\n\/\/\n\/\/ Future loop()\n\/\/ {\n\/\/ return iterate()\n\/\/ .then(defer(pid, [](T t) {\n\/\/ return body(t)\n\/\/ .then(defer(pid, [](bool condition) {\n\/\/ if (condition) {\n\/\/ return loop();\n\/\/ } else {\n\/\/ return Nothing();\n\/\/ }\n\/\/ }));\n\/\/ }));\n\/\/ }\n\/\/\n\/\/ And now what this looks like using `loop`:\n\/\/\n\/\/ loop(pid,\n\/\/ []() {\n\/\/ return iterate();\n\/\/ },\n\/\/ [](T t) {\n\/\/ return body(t);\n\/\/ });\n\/\/\n\/\/ One difference between the `loop` version of the \"body\" versus the\n\/\/ other non-loop examples above is the return value is not `bool` or\n\/\/ `Future` but rather `ControlFlow` or\n\/\/ `Future>`. This enables you to return values out of\n\/\/ the loop via a `Break(...)`, for example:\n\/\/\n\/\/ loop(pid,\n\/\/ []() {\n\/\/ return iterate();\n\/\/ },\n\/\/ [](T t) {\n\/\/ if (finished(t)) {\n\/\/ return Break(SomeValue());\n\/\/ }\n\/\/ return Continue();\n\/\/ });\ntemplate ::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename CF = typename internal::unwrap::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename V = typename CF::ValueType>\nFuture loop(const Option& pid, Iterate&& iterate, Body&& body);\n\n\n\/\/ A helper for `loop` which creates a Process for us to provide an\n\/\/ execution context for running the loop.\ntemplate ::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename CF = typename internal::unwrap::type>::type, \/\/ NOLINT(whitespace\/line_length)\n typename V = typename CF::ValueType>\nFuture loop(Iterate&& iterate, Body&& body)\n{\n \/\/ Have libprocess own and free the new `ProcessBase`.\n UPID process = spawn(new ProcessBase(), true);\n\n return loop(\n process,\n std::forward(iterate),\n std::forward(body))\n .onAny([=]() {\n terminate(process);\n \/\/ NOTE: no need to `wait` or `delete` since the `spawn` above\n \/\/ put libprocess in control of garbage collection.\n });\n}\n\n\n\/\/ Generic \"control flow\" construct that is leveraged by\n\/\/ implementations such as `loop`. At a high-level a `ControlFlow`\n\/\/ represents some control flow statement such as `continue` or\n\/\/ `break`, however, these statements can both have values or be\n\/\/ value-less (i.e., these are meant to be composed \"functionally\" so\n\/\/ the representation of `break` captures a value that \"exits the\n\/\/ current function\" but the representation of `continue` does not).\n\/\/\n\/\/ The pattern here is to define the type\/representation of control\n\/\/ flow statements within the `ControlFlow` class (e.g.,\n\/\/ `ControlFlow::Continue` and `ControlFlow::Break`) but also provide\n\/\/ \"syntactic sugar\" to make it easier to use at the call site (e.g.,\n\/\/ the functions `Continue()` and `Break(...)`).\ntemplate \nclass ControlFlow\n{\npublic:\n using ValueType = T;\n\n enum class Statement\n {\n CONTINUE,\n BREAK\n };\n\n class Continue\n {\n public:\n Continue() = default;\n\n template \n operator ControlFlow() const\n {\n return ControlFlow(ControlFlow::Statement::CONTINUE, None());\n }\n };\n\n class Break\n {\n public:\n Break(T t) : t(std::move(t)) {}\n\n template \n operator ControlFlow() const &\n {\n return ControlFlow(ControlFlow::Statement::BREAK, t);\n }\n\n template \n operator ControlFlow() &&\n {\n return ControlFlow(ControlFlow::Statement::BREAK, std::move(t));\n }\n\n private:\n T t;\n };\n\n ControlFlow(Statement s, Option t) : s(s), t(std::move(t)) {}\n\n Statement statement() const { return s; }\n\n T& value() & { return t.get(); }\n const T& value() const & { return t.get(); }\n T&& value() && { return t.get(); }\n const T&& value() const && { return t.get(); }\n\nprivate:\n Statement s;\n Option t;\n};\n\n\n\/\/ Provides \"syntactic sugar\" for creating a `ControlFlow::Continue`.\nstruct Continue\n{\n Continue() = default;\n\n template \n operator ControlFlow() const\n {\n return typename ControlFlow::Continue();\n }\n};\n\n\n\/\/ Provides \"syntactic sugar\" for creating a `ControlFlow::Break`.\ntemplate \ntypename ControlFlow::type>::Break Break(T&& t)\n{\n return typename ControlFlow::type>::Break(\n std::forward(t));\n}\n\n\ninline ControlFlow::Break Break()\n{\n return ControlFlow::Break(Nothing());\n}\n\n\nnamespace internal {\n\ntemplate \nclass Loop : public std::enable_shared_from_this>\n{\npublic:\n Loop(const Option& pid, const Iterate& iterate, const Body& body)\n : pid(pid), iterate(iterate), body(body) {}\n\n Loop(const Option& pid, Iterate&& iterate, Body&& body)\n : pid(pid), iterate(std::move(iterate)), body(std::move(body)) {}\n\n std::shared_ptr shared()\n {\n \/\/ Must fully specify `shared_from_this` because we're templated.\n return std::enable_shared_from_this::shared_from_this();\n }\n\n std::weak_ptr weak()\n {\n return std::weak_ptr(shared());\n }\n\n Future start()\n {\n auto self = shared();\n auto weak_self = weak();\n\n \/\/ Propagating discards:\n \/\/\n \/\/ When the caller does a discard we need to propagate it to\n \/\/ either the future returned from `iterate` or the future\n \/\/ returned from `body`. One easy way to do this would be to add\n \/\/ an `onAny` callback for every future returned from `iterate`\n \/\/ and `body`, but that would be a slow memory leak that would\n \/\/ grow over time, especially if the loop was actually\n \/\/ infinite. Instead, we capture the current future that needs to\n \/\/ be discarded within a `discard` function that we'll invoke when\n \/\/ we get a discard. Because there is a race setting the `discard`\n \/\/ function and reading it out to invoke we have to synchronize\n \/\/ access using a mutex. An alternative strategy would be to use\n \/\/ something like `atomic_load` and `atomic_store` with\n \/\/ `shared_ptr` so that we can swap the current future(s)\n \/\/ atomically.\n promise.future().onDiscard([weak_self]() {\n auto self = weak_self.lock();\n if (self) {\n \/\/ We need to make a copy of the current `discard` function so\n \/\/ that we can invoke it outside of the `synchronized` block\n \/\/ in the event that discarding invokes causes the `onAny`\n \/\/ callbacks that we have added in `run` to execute which may\n \/\/ deadlock attempting to re-acquire `mutex`!\n std::function f = []() {};\n synchronized (self->mutex) {\n f = self->discard;\n }\n f();\n }\n });\n\n if (pid.isSome()) {\n \/\/ Start the loop using `pid` as the execution context.\n dispatch(pid.get(), [self]() {\n self->run(self->iterate());\n });\n } else {\n run(iterate());\n }\n\n return promise.future();\n }\n\n void run(Future next)\n {\n auto self = shared();\n\n \/\/ Reset `discard` so that we're not delaying cleanup of any\n \/\/ captured futures longer than necessary.\n \/\/\n \/\/ TODO(benh): Use `WeakFuture` in `discard` functions instead.\n synchronized (mutex) {\n discard = []() {};\n }\n\n while (next.isReady()) {\n Future> flow = body(next.get());\n if (flow.isReady()) {\n switch (flow->statement()) {\n case ControlFlow::Statement::CONTINUE: {\n next = iterate();\n continue;\n }\n case ControlFlow::Statement::BREAK: {\n promise.set(flow->value());\n return;\n }\n }\n } else {\n auto continuation = [self](const Future>& flow) {\n if (flow.isReady()) {\n switch (flow->statement()) {\n case ControlFlow::Statement::CONTINUE: {\n self->run(self->iterate());\n break;\n }\n case ControlFlow::Statement::BREAK: {\n self->promise.set(flow->value());\n break;\n }\n }\n } else if (flow.isFailed()) {\n self->promise.fail(flow.failure());\n } else if (flow.isDiscarded()) {\n self->promise.discard();\n }\n };\n\n if (pid.isSome()) {\n flow.onAny(defer(pid.get(), continuation));\n } else {\n flow.onAny(continuation);\n }\n\n if (!promise.future().hasDiscard()) {\n synchronized (mutex) {\n self->discard = [=]() mutable { flow.discard(); };\n }\n }\n\n \/\/ There's a race between when a discard occurs and the\n \/\/ `discard` function gets invoked and therefore we must\n \/\/ explicitly always do a discard. In addition, after a\n \/\/ discard occurs we'll need to explicitly do discards for\n \/\/ each new future that blocks.\n if (promise.future().hasDiscard()) {\n flow.discard();\n }\n\n return;\n }\n }\n\n auto continuation = [self](const Future& next) {\n if (next.isReady()) {\n self->run(next);\n } else if (next.isFailed()) {\n self->promise.fail(next.failure());\n } else if (next.isDiscarded()) {\n self->promise.discard();\n }\n };\n\n if (pid.isSome()) {\n next.onAny(defer(pid.get(), continuation));\n } else {\n next.onAny(continuation);\n }\n\n if (!promise.future().hasDiscard()) {\n synchronized (mutex) {\n discard = [=]() mutable { next.discard(); };\n }\n }\n\n \/\/ See comment above as to why we need to explicitly discard\n \/\/ regardless of the path the if statement took above.\n if (promise.future().hasDiscard()) {\n next.discard();\n }\n }\n\nprivate:\n const Option pid;\n Iterate iterate;\n Body body;\n Promise promise;\n\n \/\/ In order to discard the loop safely we capture the future that\n \/\/ needs to be discarded within the `discard` function and reading\n \/\/ and writing that function with a mutex.\n std::mutex mutex;\n std::function discard = []() {};\n};\n\n} \/\/ namespace internal {\n\n\ntemplate \nFuture loop(const Option& pid, Iterate&& iterate, Body&& body)\n{\n using Loop = internal::Loop<\n typename std::decay::type,\n typename std::decay::type,\n T,\n V>;\n\n std::shared_ptr loop(\n new Loop(pid, std::forward(iterate), std::forward(body)));\n\n return loop->start();\n}\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_LOOP_HPP__\n<|endoftext|>"} {"text":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace http = process::http;\n\nusing process::Future;\nusing process::Owned;\nusing process::Process;\nusing process::ProcessBase;\nusing process::Promise;\nusing process::UPID;\n\nusing std::cout;\nusing std::endl;\nusing std::list;\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\n\nint main(int argc, char** argv)\n{\n \/\/ Initialize Google Mock\/Test.\n testing::InitGoogleMock(&argc, argv);\n\n \/\/ Add the libprocess test event listeners.\n ::testing::TestEventListeners& listeners =\n ::testing::UnitTest::GetInstance()->listeners();\n\n listeners.Append(process::ClockTestEventListener::instance());\n listeners.Append(process::FilterTestEventListener::instance());\n\n return RUN_ALL_TESTS();\n}\n\n\/\/ TODO(jmlvanre): Factor out the client \/ server behavior so that we\n\/\/ can make separate binaries for the client and server. This is\n\/\/ useful to attach performance tools to them separately.\n\n\/\/ A process that emulates the 'client' side of a ping pong game.\n\/\/ An HTTP '\/run' request performs a run and returns the time elapsed.\nclass ClientProcess : public Process\n{\npublic:\n ClientProcess()\n : requests(0),\n responses(0),\n totalRequests(0),\n concurrency(0) {}\n\n virtual ~ClientProcess() {}\n\nprotected:\n virtual void initialize()\n {\n install(\"pong\", &ClientProcess::pong);\n\n route(\"\/run\", None(), &ClientProcess::run);\n }\n\nprivate:\n Future run(const http::Request& request)\n {\n if (duration.get() != nullptr) {\n return http::BadRequest(\"A run is already in progress\");\n }\n\n hashmap> parameters {\n {\"server\", request.url.query.get(\"server\")},\n {\"messageSize\", request.url.query.get(\"messageSize\")},\n {\"requests\", request.url.query.get(\"requests\")},\n {\"concurrency\", request.url.query.get(\"concurrency\")},\n };\n\n \/\/ Ensure all parameters were provided.\n foreachpair (const string& parameter,\n const Option& value,\n parameters) {\n if (value.isNone()) {\n return http::BadRequest(\"Missing '\" + parameter + \"' parameter\");\n }\n }\n\n server = UPID(parameters[\"server\"].get());\n link(server);\n\n Try messageSize = Bytes::parse(parameters[\"messageSize\"].get());\n if (messageSize.isError()) {\n return http::BadRequest(\"Invalid 'messageSize': \" + messageSize.error());\n }\n message = string(messageSize.get().bytes(), '1');\n\n Try numify_ = numify(parameters[\"requests\"].get());\n if (numify_.isError()) {\n return http::BadRequest(\"Invalid 'requests': \" + numify_.error());\n }\n totalRequests = numify_.get();\n\n numify_ = numify(parameters[\"concurrency\"].get());\n if (numify_.isError()) {\n return http::BadRequest(\"Invalid 'concurrency': \" + numify_.error());\n }\n concurrency = numify_.get();\n\n if (concurrency > totalRequests) {\n concurrency = totalRequests;\n }\n\n return _run()\n .then([](const Duration& duration) -> Future {\n return http::OK(stringify(duration));\n });\n }\n\n Future _run()\n {\n duration = Owned>(new Promise());\n\n watch.start();\n\n while (requests < concurrency) {\n send(server, \"ping\", message.c_str(), message.size());\n ++requests;\n }\n\n return duration->future();\n }\n\n void pong(const UPID& from, const string& body)\n {\n ++responses;\n\n if (responses == totalRequests) {\n duration->set(watch.elapsed());\n duration.reset();\n } else if (requests < totalRequests) {\n send(server, \"ping\", message.c_str(), message.size());\n ++requests;\n }\n }\n\n \/\/ The address of the ponger (server).\n UPID server;\n\n Stopwatch watch;\n\n Owned> duration;\n\n string message;\n\n size_t requests;\n size_t responses;\n\n size_t totalRequests;\n size_t concurrency;\n};\n\n\n\/\/ A process that emulates the 'server' side of a ping pong game.\n\/\/ Note that the server links to any clients communicating to it.\nclass ServerProcess : public Process\n{\npublic:\n virtual ~ServerProcess() {}\n\nprotected:\n virtual void initialize()\n {\n install(\"ping\", &ServerProcess::ping);\n }\n\nprivate:\n void ping(const UPID& from, const string& body)\n {\n if (!links.contains(from)) {\n link(from);\n links.insert(from);\n }\n\n send(from, \"pong\", body.c_str(), body.size());\n }\n\n hashset links;\n};\n\n\/\/ TODO(bmahler): Since there is no forking here, libprocess\n\/\/ avoids going through sockets for local messages. Either fork\n\/\/ or have the ability to disable local messages in libprocess.\n\n\/\/ Launches many clients against a central server and measures\n\/\/ client throughput.\nTEST(ProcessTest, Process_BENCHMARK_ClientServer)\n{\n const size_t numRequests = 10000;\n const size_t concurrency = 250;\n const size_t numClients = 8;\n const Bytes messageSize = Bytes(3);\n\n ServerProcess server;\n const UPID serverPid = spawn(&server);\n\n \/\/ Launch the clients.\n vector> clients;\n for (size_t i = 0; i < numClients; i++) {\n clients.push_back(Owned(new ClientProcess()));\n spawn(clients.back().get());\n }\n\n \/\/ Start the ping \/ pongs!\n const string query = strings::join(\n \"&\",\n \"server=\" + stringify(serverPid),\n \"requests=\" + stringify(numRequests),\n \"concurrency=\" + stringify(concurrency),\n \"messageSize=\" + stringify(messageSize));\n\n Stopwatch watch;\n watch.start();\n\n list> futures;\n foreach (const Owned& client, clients) {\n futures.push_back(http::get(client->self(), \"run\", query));\n }\n\n Future> responses = collect(futures);\n AWAIT_READY(responses);\n\n Duration elapsed = watch.elapsed();\n\n \/\/ Print the throughput of each client.\n size_t i = 0;\n foreach (const http::Response& response, responses.get()) {\n ASSERT_EQ(http::Status::OK, response.code);\n ASSERT_EQ(http::Status::string(http::Status::OK), response.status);\n\n Try elapsed = Duration::parse(response.body);\n ASSERT_SOME(elapsed);\n double throughput = numRequests \/ elapsed.get().secs();\n\n cout << \"Client \" << i << \": \" << throughput << \" rpcs \/ sec\" << endl;\n\n i++;\n }\n\n double throughput = (numRequests * numClients) \/ elapsed.secs();\n cout << \"Estimated Total: \" << throughput << \" rpcs \/ sec\" << endl;\n\n foreach (const Owned& client, clients) {\n terminate(*client);\n wait(*client);\n }\n\n terminate(server);\n wait(server);\n\n return;\n}\n\n\nclass LinkerProcess : public Process\n{\npublic:\n LinkerProcess(const UPID& _to) : to(_to) {}\n\n virtual void initialize()\n {\n link(to);\n }\n\nprivate:\n UPID to;\n};\n\n\nclass EphemeralProcess : public Process\n{\npublic:\n void terminate()\n {\n process::terminate(self());\n }\n};\n\n\n\/\/ Simulate the scenario discussed in MESOS-2182. We first establish a\n\/\/ large number of links by creating many linker-linkee pairs. And\n\/\/ then, we introduce a large amount of ephemeral process exits as\n\/\/ well as event dispatches.\nTEST(ProcessTest, Process_BENCHMARK_LargeNumberOfLinks)\n{\n int links = 5000;\n int iterations = 10000;\n\n \/\/ Keep track of all the linked processes we created.\n vector processes;\n\n \/\/ Establish a large number of links.\n for (int i = 0; i < links; i++) {\n ProcessBase* linkee = new ProcessBase();\n LinkerProcess* linker = new LinkerProcess(linkee->self());\n\n processes.push_back(linkee);\n processes.push_back(linker);\n\n spawn(linkee);\n spawn(linker);\n }\n\n \/\/ Generate large number of dispatches and process exits by spawning\n \/\/ and then terminating EphemeralProcesses.\n vector ephemeralProcesses;\n\n Stopwatch watch;\n watch.start();\n\n for (int i = 0; i < iterations ; i++) {\n EphemeralProcess* process = new EphemeralProcess();\n ephemeralProcesses.push_back(process);\n\n spawn(process);\n\n \/\/ NOTE: We let EphemeralProcess terminate itself to make sure all\n \/\/ dispatches are actually executed (otherwise, 'wait' below will\n \/\/ be blocked).\n dispatch(process->self(), &EphemeralProcess::terminate);\n }\n\n foreach (ProcessBase* process, ephemeralProcesses) {\n wait(process);\n delete process;\n }\n\n cout << \"Elapsed: \" << watch.elapsed() << endl;\n\n foreach (ProcessBase* process, processes) {\n terminate(process);\n wait(process);\n delete process;\n }\n}\nRemoved a redundant `return` statement in libprocess.\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace http = process::http;\n\nusing process::Future;\nusing process::Owned;\nusing process::Process;\nusing process::ProcessBase;\nusing process::Promise;\nusing process::UPID;\n\nusing std::cout;\nusing std::endl;\nusing std::list;\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\n\nint main(int argc, char** argv)\n{\n \/\/ Initialize Google Mock\/Test.\n testing::InitGoogleMock(&argc, argv);\n\n \/\/ Add the libprocess test event listeners.\n ::testing::TestEventListeners& listeners =\n ::testing::UnitTest::GetInstance()->listeners();\n\n listeners.Append(process::ClockTestEventListener::instance());\n listeners.Append(process::FilterTestEventListener::instance());\n\n return RUN_ALL_TESTS();\n}\n\n\/\/ TODO(jmlvanre): Factor out the client \/ server behavior so that we\n\/\/ can make separate binaries for the client and server. This is\n\/\/ useful to attach performance tools to them separately.\n\n\/\/ A process that emulates the 'client' side of a ping pong game.\n\/\/ An HTTP '\/run' request performs a run and returns the time elapsed.\nclass ClientProcess : public Process\n{\npublic:\n ClientProcess()\n : requests(0),\n responses(0),\n totalRequests(0),\n concurrency(0) {}\n\n virtual ~ClientProcess() {}\n\nprotected:\n virtual void initialize()\n {\n install(\"pong\", &ClientProcess::pong);\n\n route(\"\/run\", None(), &ClientProcess::run);\n }\n\nprivate:\n Future run(const http::Request& request)\n {\n if (duration.get() != nullptr) {\n return http::BadRequest(\"A run is already in progress\");\n }\n\n hashmap> parameters {\n {\"server\", request.url.query.get(\"server\")},\n {\"messageSize\", request.url.query.get(\"messageSize\")},\n {\"requests\", request.url.query.get(\"requests\")},\n {\"concurrency\", request.url.query.get(\"concurrency\")},\n };\n\n \/\/ Ensure all parameters were provided.\n foreachpair (const string& parameter,\n const Option& value,\n parameters) {\n if (value.isNone()) {\n return http::BadRequest(\"Missing '\" + parameter + \"' parameter\");\n }\n }\n\n server = UPID(parameters[\"server\"].get());\n link(server);\n\n Try messageSize = Bytes::parse(parameters[\"messageSize\"].get());\n if (messageSize.isError()) {\n return http::BadRequest(\"Invalid 'messageSize': \" + messageSize.error());\n }\n message = string(messageSize.get().bytes(), '1');\n\n Try numify_ = numify(parameters[\"requests\"].get());\n if (numify_.isError()) {\n return http::BadRequest(\"Invalid 'requests': \" + numify_.error());\n }\n totalRequests = numify_.get();\n\n numify_ = numify(parameters[\"concurrency\"].get());\n if (numify_.isError()) {\n return http::BadRequest(\"Invalid 'concurrency': \" + numify_.error());\n }\n concurrency = numify_.get();\n\n if (concurrency > totalRequests) {\n concurrency = totalRequests;\n }\n\n return _run()\n .then([](const Duration& duration) -> Future {\n return http::OK(stringify(duration));\n });\n }\n\n Future _run()\n {\n duration = Owned>(new Promise());\n\n watch.start();\n\n while (requests < concurrency) {\n send(server, \"ping\", message.c_str(), message.size());\n ++requests;\n }\n\n return duration->future();\n }\n\n void pong(const UPID& from, const string& body)\n {\n ++responses;\n\n if (responses == totalRequests) {\n duration->set(watch.elapsed());\n duration.reset();\n } else if (requests < totalRequests) {\n send(server, \"ping\", message.c_str(), message.size());\n ++requests;\n }\n }\n\n \/\/ The address of the ponger (server).\n UPID server;\n\n Stopwatch watch;\n\n Owned> duration;\n\n string message;\n\n size_t requests;\n size_t responses;\n\n size_t totalRequests;\n size_t concurrency;\n};\n\n\n\/\/ A process that emulates the 'server' side of a ping pong game.\n\/\/ Note that the server links to any clients communicating to it.\nclass ServerProcess : public Process\n{\npublic:\n virtual ~ServerProcess() {}\n\nprotected:\n virtual void initialize()\n {\n install(\"ping\", &ServerProcess::ping);\n }\n\nprivate:\n void ping(const UPID& from, const string& body)\n {\n if (!links.contains(from)) {\n link(from);\n links.insert(from);\n }\n\n send(from, \"pong\", body.c_str(), body.size());\n }\n\n hashset links;\n};\n\n\/\/ TODO(bmahler): Since there is no forking here, libprocess\n\/\/ avoids going through sockets for local messages. Either fork\n\/\/ or have the ability to disable local messages in libprocess.\n\n\/\/ Launches many clients against a central server and measures\n\/\/ client throughput.\nTEST(ProcessTest, Process_BENCHMARK_ClientServer)\n{\n const size_t numRequests = 10000;\n const size_t concurrency = 250;\n const size_t numClients = 8;\n const Bytes messageSize = Bytes(3);\n\n ServerProcess server;\n const UPID serverPid = spawn(&server);\n\n \/\/ Launch the clients.\n vector> clients;\n for (size_t i = 0; i < numClients; i++) {\n clients.push_back(Owned(new ClientProcess()));\n spawn(clients.back().get());\n }\n\n \/\/ Start the ping \/ pongs!\n const string query = strings::join(\n \"&\",\n \"server=\" + stringify(serverPid),\n \"requests=\" + stringify(numRequests),\n \"concurrency=\" + stringify(concurrency),\n \"messageSize=\" + stringify(messageSize));\n\n Stopwatch watch;\n watch.start();\n\n list> futures;\n foreach (const Owned& client, clients) {\n futures.push_back(http::get(client->self(), \"run\", query));\n }\n\n Future> responses = collect(futures);\n AWAIT_READY(responses);\n\n Duration elapsed = watch.elapsed();\n\n \/\/ Print the throughput of each client.\n size_t i = 0;\n foreach (const http::Response& response, responses.get()) {\n ASSERT_EQ(http::Status::OK, response.code);\n ASSERT_EQ(http::Status::string(http::Status::OK), response.status);\n\n Try elapsed = Duration::parse(response.body);\n ASSERT_SOME(elapsed);\n double throughput = numRequests \/ elapsed.get().secs();\n\n cout << \"Client \" << i << \": \" << throughput << \" rpcs \/ sec\" << endl;\n\n i++;\n }\n\n double throughput = (numRequests * numClients) \/ elapsed.secs();\n cout << \"Estimated Total: \" << throughput << \" rpcs \/ sec\" << endl;\n\n foreach (const Owned& client, clients) {\n terminate(*client);\n wait(*client);\n }\n\n terminate(server);\n wait(server);\n}\n\n\nclass LinkerProcess : public Process\n{\npublic:\n LinkerProcess(const UPID& _to) : to(_to) {}\n\n virtual void initialize()\n {\n link(to);\n }\n\nprivate:\n UPID to;\n};\n\n\nclass EphemeralProcess : public Process\n{\npublic:\n void terminate()\n {\n process::terminate(self());\n }\n};\n\n\n\/\/ Simulate the scenario discussed in MESOS-2182. We first establish a\n\/\/ large number of links by creating many linker-linkee pairs. And\n\/\/ then, we introduce a large amount of ephemeral process exits as\n\/\/ well as event dispatches.\nTEST(ProcessTest, Process_BENCHMARK_LargeNumberOfLinks)\n{\n int links = 5000;\n int iterations = 10000;\n\n \/\/ Keep track of all the linked processes we created.\n vector processes;\n\n \/\/ Establish a large number of links.\n for (int i = 0; i < links; i++) {\n ProcessBase* linkee = new ProcessBase();\n LinkerProcess* linker = new LinkerProcess(linkee->self());\n\n processes.push_back(linkee);\n processes.push_back(linker);\n\n spawn(linkee);\n spawn(linker);\n }\n\n \/\/ Generate large number of dispatches and process exits by spawning\n \/\/ and then terminating EphemeralProcesses.\n vector ephemeralProcesses;\n\n Stopwatch watch;\n watch.start();\n\n for (int i = 0; i < iterations ; i++) {\n EphemeralProcess* process = new EphemeralProcess();\n ephemeralProcesses.push_back(process);\n\n spawn(process);\n\n \/\/ NOTE: We let EphemeralProcess terminate itself to make sure all\n \/\/ dispatches are actually executed (otherwise, 'wait' below will\n \/\/ be blocked).\n dispatch(process->self(), &EphemeralProcess::terminate);\n }\n\n foreach (ProcessBase* process, ephemeralProcesses) {\n wait(process);\n delete process;\n }\n\n cout << \"Elapsed: \" << watch.elapsed() << endl;\n\n foreach (ProcessBase* process, processes) {\n terminate(process);\n wait(process);\n delete process;\n }\n}\n<|endoftext|>"} {"text":"\/*\r\nCopyright 2016 Colin Girling\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*\/\r\n\r\n#include \"..\/Test.hpp\"\r\n#include \"..\/TestConverterUtility.hpp\"\r\n#include \"..\/TestMemoryUtility.hpp\"\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, bool_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef bool type;\r\n\r\n TEST_OVERRIDE_ARGS(\"bool,size_type\");\r\n\r\n type value = true;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"true\");\r\n CHECK_EQUAL(length, 4U);\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n value = false;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"false\");\r\n CHECK_EQUAL(length, 5U);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, char_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef char type;\r\n\r\n TEST_OVERRIDE_ARGS(\"char,size_type\");\r\n\r\n type value = '1';\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"1\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_char_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef signed char type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed char,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_char_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef unsigned char type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned char,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_short_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef signed short type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed short,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_short_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef unsigned short type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned short,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_int_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef signed int type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed int,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_int_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef unsigned int type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned int,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_long_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef signed long type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed long,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_long_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef unsigned long type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned long,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\nAdded unit tests for min\/max ranges for all integer types for TestConverterUtility class.\/*\r\nCopyright 2016 Colin Girling\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n*\/\r\n\r\n#include \"..\/Test.hpp\"\r\n#include \"..\/TestConverterUtility.hpp\"\r\n#include \"..\/TestMemoryUtility.hpp\"\r\n#include \"..\/TestStringUtility.hpp\"\r\n#include \"..\/TestMinMax.hpp\"\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, bool_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef bool type;\r\n\r\n TEST_OVERRIDE_ARGS(\"bool,size_type\");\r\n\r\n type value = true;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"true\");\r\n CHECK_EQUAL(length, 4U);\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n value = false;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"false\");\r\n CHECK_EQUAL(length, 5U);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, char_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n typedef unsigned int size_type;\r\n typedef char type;\r\n\r\n TEST_OVERRIDE_ARGS(\"char,size_type\");\r\n\r\n type value = '1';\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"1\");\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_char_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef signed char type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed char,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* min_str = TestStringUtility::GetMinSignedIntAsString(sizeof(type));\r\n value = TestMinMax::min_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, min_str);\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxSignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_char_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef unsigned char type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned char,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxUnsignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_short_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef signed short type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed short,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* min_str = TestStringUtility::GetMinSignedIntAsString(sizeof(type));\r\n value = TestMinMax::min_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, min_str);\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxSignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_short_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef unsigned short type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned short,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxUnsignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_int_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef signed int type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed int,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* min_str = TestStringUtility::GetMinSignedIntAsString(sizeof(type));\r\n value = TestMinMax::min_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, min_str);\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxSignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_int_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef unsigned int type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned int,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxUnsignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, signed_long_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef signed long type;\r\n\r\n TEST_OVERRIDE_ARGS(\"signed long,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* min_str = TestStringUtility::GetMinSignedIntAsString(sizeof(type));\r\n value = TestMinMax::min_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, min_str);\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxSignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n\r\nTEST_MEMBER_FUNCTION(TestConverterUtility, GetString, unsigned_long_size_type)\r\n{\r\n using ocl::TestConverterUtility;\r\n using ocl::TestMemoryUtility;\r\n using ocl::TestStringUtility;\r\n using ocl::TestMinMax;\r\n typedef unsigned int size_type;\r\n typedef unsigned long type;\r\n\r\n TEST_OVERRIDE_ARGS(\"unsigned long,size_type\");\r\n\r\n type value = 0;\r\n size_type length = 0U;\r\n char* str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, \"0\");\r\n TestMemoryUtility::SafeFree(str);\r\n\r\n char const* max_str = TestStringUtility::GetMaxUnsignedIntAsString(sizeof(type));\r\n value = TestMinMax::max_value;\r\n length = 0;\r\n str = TestConverterUtility::GetString(value, length);\r\n CHECK_NOT_NULL(str);\r\n CHECK_STRCMP(str, max_str);\r\n TestMemoryUtility::SafeFree(str);\r\n}\r\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * TIGHTDB CONFIDENTIAL\n * __________________\n *\n * [2011] - [2012] TightDB Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of TightDB Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to TightDB Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from TightDB Incorporated.\n *\n **************************************************************************\/\n#ifndef TIGHTDB_COLUMN_BASIC_TPL_HPP\n#define TIGHTDB_COLUMN_BASIC_TPL_HPP\n\n#include \n\n\nnamespace tightdb {\n\n\/\/ Predeclarations from query_engine.hpp\nclass ParentNode;\ntemplate class BasicNode;\ntemplate class SequentialGetter;\n\n\ntemplate\nBasicColumn::BasicColumn(Allocator& alloc)\n{\n m_array = new BasicArray(NULL, 0, alloc);\n}\n\ntemplate\nBasicColumn::BasicColumn(size_t ref, ArrayParent* parent, size_t pndx, Allocator& alloc)\n{\n const bool isNode = is_node_from_ref(ref, alloc);\n if (isNode)\n m_array = new Array(ref, parent, pndx, alloc);\n else\n m_array = new BasicArray(ref, parent, pndx, alloc);\n}\n\ntemplate\nBasicColumn::~BasicColumn()\n{\n if (IsNode())\n delete m_array;\n else\n delete static_cast*>(m_array);\n}\n\ntemplate\nvoid BasicColumn::Destroy()\n{\n if (IsNode())\n m_array->Destroy();\n else\n static_cast*>(m_array)->Destroy();\n}\n\n\ntemplate\nvoid BasicColumn::UpdateRef(size_t ref)\n{\n TIGHTDB_ASSERT(is_node_from_ref(ref, m_array->GetAllocator())); \/\/ Can only be called when creating node\n\n if (IsNode())\n m_array->UpdateRef(ref);\n else {\n ArrayParent* const parent = m_array->GetParent();\n const size_t pndx = m_array->GetParentNdx();\n\n \/\/ Replace the generic array with int array for node\n Array* array = new Array(ref, parent, pndx, m_array->GetAllocator());\n delete m_array;\n m_array = array;\n\n \/\/ Update ref in parent\n if (parent)\n parent->update_child_ref(pndx, ref);\n }\n}\n\ntemplate\nbool BasicColumn::is_empty() const TIGHTDB_NOEXCEPT\n{\n if (IsNode()) {\n const Array offsets = NodeGetOffsets();\n return offsets.is_empty();\n }\n else {\n return static_cast*>(m_array)->is_empty();\n }\n}\n\ntemplate\nsize_t BasicColumn::Size() const TIGHTDB_NOEXCEPT\n{\n if (IsNode()) {\n const Array offsets = NodeGetOffsets();\n const size_t size = offsets.is_empty() ? 0 : size_t(offsets.back());\n return size;\n }\n else {\n return m_array->size();\n }\n}\n\ntemplate\nvoid BasicColumn::Clear()\n{\n if (m_array->IsNode()) {\n ArrayParent *const parent = m_array->GetParent();\n const size_t pndx = m_array->GetParentNdx();\n\n \/\/ Revert to generic array\n BasicArray* array = new BasicArray(parent, pndx, m_array->GetAllocator());\n if (parent)\n parent->update_child_ref(pndx, array->GetRef());\n\n \/\/ Remove original node\n m_array->Destroy();\n delete m_array;\n\n m_array = array;\n }\n else\n static_cast*>(m_array)->Clear();\n}\n\ntemplate\nvoid BasicColumn::Resize(size_t ndx)\n{\n TIGHTDB_ASSERT(!IsNode()); \/\/ currently only available on leaf level (used by b-tree code)\n TIGHTDB_ASSERT(ndx < Size());\n static_cast*>(m_array)->Resize(ndx);\n}\n\ntemplate\nT BasicColumn::Get(size_t ndx) const TIGHTDB_NOEXCEPT\n{\n TIGHTDB_ASSERT(ndx < Size());\n return BasicArray::column_get(m_array, ndx);\n}\n\ntemplate\nvoid BasicColumn::Set(size_t ndx, T value)\n{\n TIGHTDB_ASSERT(ndx < Size());\n TreeSet >(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::add(T value)\n{\n Insert(Size(), value);\n}\n\ntemplate\nvoid BasicColumn::Insert(size_t ndx, T value)\n{\n TIGHTDB_ASSERT(ndx <= Size());\n TreeInsert >(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::fill(size_t count)\n{\n TIGHTDB_ASSERT(is_empty());\n\n \/\/ Fill column with default values\n \/\/ TODO: this is a very naive approach\n \/\/ we could speedup by creating full nodes directly\n for (size_t i = 0; i < count; ++i) {\n TreeInsert >(i, 0);\n }\n\n#ifdef TIGHTDB_DEBUG\n Verify();\n#endif\n}\n\ntemplate\nbool BasicColumn::compare(const BasicColumn& c) const\n{\n const size_t n = Size();\n if (c.Size() != n)\n return false;\n for (size_t i=0; i\nvoid BasicColumn::Delete(size_t ndx)\n{\n TIGHTDB_ASSERT(ndx < Size());\n TreeDelete >(ndx);\n}\n\ntemplate\nT BasicColumn::LeafGet(size_t ndx) const TIGHTDB_NOEXCEPT\n{\n return static_cast*>(m_array)->Get(ndx);\n}\n\ntemplate\nvoid BasicColumn::LeafSet(size_t ndx, T value)\n{\n static_cast*>(m_array)->Set(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::LeafInsert(size_t ndx, T value)\n{\n static_cast*>(m_array)->Insert(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::LeafDelete(size_t ndx)\n{\n static_cast*>(m_array)->Delete(ndx);\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\ntemplate\nvoid BasicColumn::LeafToDot(std::ostream& out, const Array& array) const\n{\n \/\/ Rebuild array to get correct type\n const size_t ref = array.GetRef();\n const BasicArray newArray(ref, NULL, 0, array.GetAllocator());\n\n newArray.ToDot(out);\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n\n\ntemplate template\nsize_t BasicColumn::LeafFind(T value, size_t start, size_t end) const\n{\n return static_cast*>(m_array)->find_first(value, start, end);\n}\n\ntemplate\nvoid BasicColumn::LeafFindAll(Array &result, T value, size_t add_offset, size_t start, size_t end) const\n{\n return static_cast*>(m_array)->find_all(result, value, add_offset, start, end);\n}\n\ntemplate\nsize_t BasicColumn::find_first(T value, size_t start, size_t end) const\n{\n TIGHTDB_ASSERT(value);\n\n return TreeFind, Equal>(value, start, end);\n}\n\ntemplate\nvoid BasicColumn::find_all(Array &result, T value, size_t start, size_t end) const\n{\n TIGHTDB_ASSERT(value);\n\n TreeFindAll >(result, value, 0, start, end);\n}\n\n\n#if 1\n\ntemplate\nsize_t BasicColumn::count(T target) const\n{\n return size_t(ColumnBase::aggregate(target, 0, Size(), NULL));\n}\n\ntemplate\ntypename BasicColumn::SumType BasicColumn::sum(size_t start, size_t end) const\n{\n return ColumnBase::aggregate(0, start, end, NULL);\n}\n\ntemplate\ndouble BasicColumn::average(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n size_t size = end - start;\n double sum1 = ColumnBase::aggregate(0, start, end, NULL);\n double avg = sum1 \/ ( size == 0 ? 1 : size );\n return avg;\n}\n\ntemplate\nT BasicColumn::minimum(size_t start, size_t end) const\n{\n return ColumnBase::aggregate(0, start, end, NULL);\n}\n\ntemplate\nT BasicColumn::maximum(size_t start, size_t end) const\n{\n return ColumnBase::aggregate(0, start, end, NULL);\n}\n\n\/*\ntemplate\nvoid BasicColumn::sort(size_t start, size_t end)\n{\n \/\/ TODO\n assert(0);\n}\n*\/\n\n#else\n\n\/\/ Alternative 'naive' reference implementation - useful for reference performance testing.\n\/\/ TODO: test performance of column aggregates\n\ntemplate\nsize_t BasicColumn::count(T target) const\n{\n size_t count = 0;\n\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = 0; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n\n count += col.count(target);\n }\n }\n else {\n count += ((BasicArray*)m_array)->count(target);\n }\n return count;\n}\n\ntemplate\nT BasicColumn::sum(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n\n double sum = 0;\n\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = start; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n\n sum += col.sum(start, end);\n }\n }\n else {\n sum += ((BasicArray*)m_array)->sum(start, end);\n }\n return sum;\n}\n\ntemplate\ndouble BasicColumn::average(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n size_t size = end - start;\n double sum2 = sum(start, end);\n double avg = sum2 \/ double( size == 0 ? 1 : size );\n return avg;\n}\n\n\/\/ #include \n\ntemplate\nT BasicColumn::minimum(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n\n T min_val = T(987.0);\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = start; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n T val = col.minimum(start, end);\n if (val < min_val || i == start) {\n \/\/std::cout << \"Min \" << i << \": \" << min_val << \" new val: \" << val << \"\\n\";\n val = min_val;\n }\n }\n }\n else {\n \/\/ std::cout << \"array-min before: \" << min_val;\n ((BasicArray*)m_array)->minimum(min_val, start, end);\n \/\/ std::cout << \" after: \" << min_val << \"\\n\";\n }\n return min_val;\n}\n\ntemplate\nT BasicColumn::maximum(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n\n T max_val = T(0.0);\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = start; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n T val = col.maximum(start, end);\n if (val > max_val || i == start)\n val = max_val;\n }\n }\n else {\n ((BasicArray*)m_array)->maximum(max_val, start, end);\n }\n return max_val;\n}\n\n#endif \/\/ reference implementation of aggregates\n\n} \/\/ namespace tightdb\n\n#endif \/\/ TIGHTDB_COLUMN_BASIC_TPL_HPP\nFixed bug i float: was asserting in find_all and find_first when value was 0!\/*************************************************************************\n *\n * TIGHTDB CONFIDENTIAL\n * __________________\n *\n * [2011] - [2012] TightDB Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of TightDB Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to TightDB Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from TightDB Incorporated.\n *\n **************************************************************************\/\n#ifndef TIGHTDB_COLUMN_BASIC_TPL_HPP\n#define TIGHTDB_COLUMN_BASIC_TPL_HPP\n\n#include \n\n\nnamespace tightdb {\n\n\/\/ Predeclarations from query_engine.hpp\nclass ParentNode;\ntemplate class BasicNode;\ntemplate class SequentialGetter;\n\n\ntemplate\nBasicColumn::BasicColumn(Allocator& alloc)\n{\n m_array = new BasicArray(NULL, 0, alloc);\n}\n\ntemplate\nBasicColumn::BasicColumn(size_t ref, ArrayParent* parent, size_t pndx, Allocator& alloc)\n{\n const bool isNode = is_node_from_ref(ref, alloc);\n if (isNode)\n m_array = new Array(ref, parent, pndx, alloc);\n else\n m_array = new BasicArray(ref, parent, pndx, alloc);\n}\n\ntemplate\nBasicColumn::~BasicColumn()\n{\n if (IsNode())\n delete m_array;\n else\n delete static_cast*>(m_array);\n}\n\ntemplate\nvoid BasicColumn::Destroy()\n{\n if (IsNode())\n m_array->Destroy();\n else\n static_cast*>(m_array)->Destroy();\n}\n\n\ntemplate\nvoid BasicColumn::UpdateRef(size_t ref)\n{\n TIGHTDB_ASSERT(is_node_from_ref(ref, m_array->GetAllocator())); \/\/ Can only be called when creating node\n\n if (IsNode())\n m_array->UpdateRef(ref);\n else {\n ArrayParent* const parent = m_array->GetParent();\n const size_t pndx = m_array->GetParentNdx();\n\n \/\/ Replace the generic array with int array for node\n Array* array = new Array(ref, parent, pndx, m_array->GetAllocator());\n delete m_array;\n m_array = array;\n\n \/\/ Update ref in parent\n if (parent)\n parent->update_child_ref(pndx, ref);\n }\n}\n\ntemplate\nbool BasicColumn::is_empty() const TIGHTDB_NOEXCEPT\n{\n if (IsNode()) {\n const Array offsets = NodeGetOffsets();\n return offsets.is_empty();\n }\n else {\n return static_cast*>(m_array)->is_empty();\n }\n}\n\ntemplate\nsize_t BasicColumn::Size() const TIGHTDB_NOEXCEPT\n{\n if (IsNode()) {\n const Array offsets = NodeGetOffsets();\n const size_t size = offsets.is_empty() ? 0 : size_t(offsets.back());\n return size;\n }\n else {\n return m_array->size();\n }\n}\n\ntemplate\nvoid BasicColumn::Clear()\n{\n if (m_array->IsNode()) {\n ArrayParent *const parent = m_array->GetParent();\n const size_t pndx = m_array->GetParentNdx();\n\n \/\/ Revert to generic array\n BasicArray* array = new BasicArray(parent, pndx, m_array->GetAllocator());\n if (parent)\n parent->update_child_ref(pndx, array->GetRef());\n\n \/\/ Remove original node\n m_array->Destroy();\n delete m_array;\n\n m_array = array;\n }\n else\n static_cast*>(m_array)->Clear();\n}\n\ntemplate\nvoid BasicColumn::Resize(size_t ndx)\n{\n TIGHTDB_ASSERT(!IsNode()); \/\/ currently only available on leaf level (used by b-tree code)\n TIGHTDB_ASSERT(ndx < Size());\n static_cast*>(m_array)->Resize(ndx);\n}\n\ntemplate\nT BasicColumn::Get(size_t ndx) const TIGHTDB_NOEXCEPT\n{\n TIGHTDB_ASSERT(ndx < Size());\n return BasicArray::column_get(m_array, ndx);\n}\n\ntemplate\nvoid BasicColumn::Set(size_t ndx, T value)\n{\n TIGHTDB_ASSERT(ndx < Size());\n TreeSet >(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::add(T value)\n{\n Insert(Size(), value);\n}\n\ntemplate\nvoid BasicColumn::Insert(size_t ndx, T value)\n{\n TIGHTDB_ASSERT(ndx <= Size());\n TreeInsert >(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::fill(size_t count)\n{\n TIGHTDB_ASSERT(is_empty());\n\n \/\/ Fill column with default values\n \/\/ TODO: this is a very naive approach\n \/\/ we could speedup by creating full nodes directly\n for (size_t i = 0; i < count; ++i) {\n TreeInsert >(i, 0);\n }\n\n#ifdef TIGHTDB_DEBUG\n Verify();\n#endif\n}\n\ntemplate\nbool BasicColumn::compare(const BasicColumn& c) const\n{\n const size_t n = Size();\n if (c.Size() != n)\n return false;\n for (size_t i=0; i\nvoid BasicColumn::Delete(size_t ndx)\n{\n TIGHTDB_ASSERT(ndx < Size());\n TreeDelete >(ndx);\n}\n\ntemplate\nT BasicColumn::LeafGet(size_t ndx) const TIGHTDB_NOEXCEPT\n{\n return static_cast*>(m_array)->Get(ndx);\n}\n\ntemplate\nvoid BasicColumn::LeafSet(size_t ndx, T value)\n{\n static_cast*>(m_array)->Set(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::LeafInsert(size_t ndx, T value)\n{\n static_cast*>(m_array)->Insert(ndx, value);\n}\n\ntemplate\nvoid BasicColumn::LeafDelete(size_t ndx)\n{\n static_cast*>(m_array)->Delete(ndx);\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\ntemplate\nvoid BasicColumn::LeafToDot(std::ostream& out, const Array& array) const\n{\n \/\/ Rebuild array to get correct type\n const size_t ref = array.GetRef();\n const BasicArray newArray(ref, NULL, 0, array.GetAllocator());\n\n newArray.ToDot(out);\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n\n\ntemplate template\nsize_t BasicColumn::LeafFind(T value, size_t start, size_t end) const\n{\n return static_cast*>(m_array)->find_first(value, start, end);\n}\n\ntemplate\nvoid BasicColumn::LeafFindAll(Array &result, T value, size_t add_offset, size_t start, size_t end) const\n{\n return static_cast*>(m_array)->find_all(result, value, add_offset, start, end);\n}\n\ntemplate\nsize_t BasicColumn::find_first(T value, size_t start, size_t end) const\n{\n return TreeFind, Equal>(value, start, end);\n}\n\ntemplate\nvoid BasicColumn::find_all(Array &result, T value, size_t start, size_t end) const\n{\n TreeFindAll >(result, value, 0, start, end);\n}\n\n\n#if 1\n\ntemplate\nsize_t BasicColumn::count(T target) const\n{\n return size_t(ColumnBase::aggregate(target, 0, Size(), NULL));\n}\n\ntemplate\ntypename BasicColumn::SumType BasicColumn::sum(size_t start, size_t end) const\n{\n return ColumnBase::aggregate(0, start, end, NULL);\n}\n\ntemplate\ndouble BasicColumn::average(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n size_t size = end - start;\n double sum1 = ColumnBase::aggregate(0, start, end, NULL);\n double avg = sum1 \/ ( size == 0 ? 1 : size );\n return avg;\n}\n\ntemplate\nT BasicColumn::minimum(size_t start, size_t end) const\n{\n return ColumnBase::aggregate(0, start, end, NULL);\n}\n\ntemplate\nT BasicColumn::maximum(size_t start, size_t end) const\n{\n return ColumnBase::aggregate(0, start, end, NULL);\n}\n\n\/*\ntemplate\nvoid BasicColumn::sort(size_t start, size_t end)\n{\n \/\/ TODO\n assert(0);\n}\n*\/\n\n#else\n\n\/\/ Alternative 'naive' reference implementation - useful for reference performance testing.\n\/\/ TODO: test performance of column aggregates\n\ntemplate\nsize_t BasicColumn::count(T target) const\n{\n size_t count = 0;\n\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = 0; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n\n count += col.count(target);\n }\n }\n else {\n count += ((BasicArray*)m_array)->count(target);\n }\n return count;\n}\n\ntemplate\nT BasicColumn::sum(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n\n double sum = 0;\n\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = start; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n\n sum += col.sum(start, end);\n }\n }\n else {\n sum += ((BasicArray*)m_array)->sum(start, end);\n }\n return sum;\n}\n\ntemplate\ndouble BasicColumn::average(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n size_t size = end - start;\n double sum2 = sum(start, end);\n double avg = sum2 \/ double( size == 0 ? 1 : size );\n return avg;\n}\n\n\/\/ #include \n\ntemplate\nT BasicColumn::minimum(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n\n T min_val = T(987.0);\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = start; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n T val = col.minimum(start, end);\n if (val < min_val || i == start) {\n \/\/std::cout << \"Min \" << i << \": \" << min_val << \" new val: \" << val << \"\\n\";\n val = min_val;\n }\n }\n }\n else {\n \/\/ std::cout << \"array-min before: \" << min_val;\n ((BasicArray*)m_array)->minimum(min_val, start, end);\n \/\/ std::cout << \" after: \" << min_val << \"\\n\";\n }\n return min_val;\n}\n\ntemplate\nT BasicColumn::maximum(size_t start, size_t end) const\n{\n if (end == size_t(-1))\n end = Size();\n\n T max_val = T(0.0);\n if (m_array->IsNode()) {\n const Array refs = NodeGetRefs();\n const size_t n = refs.size();\n\n for (size_t i = start; i < n; ++i) {\n const size_t ref = refs.GetAsRef(i);\n const BasicColumn col(ref, NULL, 0, m_array->GetAllocator());\n T val = col.maximum(start, end);\n if (val > max_val || i == start)\n val = max_val;\n }\n }\n else {\n ((BasicArray*)m_array)->maximum(max_val, start, end);\n }\n return max_val;\n}\n\n#endif \/\/ reference implementation of aggregates\n\n} \/\/ namespace tightdb\n\n#endif \/\/ TIGHTDB_COLUMN_BASIC_TPL_HPP\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"ast.h\"\n#include \"bpftrace.h\"\n#include \"log.h\"\n#include \"struct.h\"\n#include \"tracepoint_format_parser.h\"\n\nnamespace bpftrace {\n\nstd::set TracepointFormatParser::struct_list;\n\nbool TracepointFormatParser::parse(ast::Program *program, BPFtrace &bpftrace)\n{\n std::vector probes_with_tracepoint;\n for (ast::Probe *probe : *program->probes)\n for (ast::AttachPoint *ap : *probe->attach_points)\n if (ap->provider == \"tracepoint\") {\n probes_with_tracepoint.push_back(probe);\n continue;\n }\n\n if (probes_with_tracepoint.empty())\n return true;\n\n ast::TracepointArgsVisitor n{};\n if (!bpftrace.btf_.has_data())\n program->c_definitions += \"#include \\n\";\n for (ast::Probe *probe : probes_with_tracepoint)\n {\n n.visit(*probe);\n\n for (ast::AttachPoint *ap : *probe->attach_points)\n {\n if (ap->provider == \"tracepoint\")\n {\n std::string &category = ap->target;\n std::string &event_name = ap->func;\n std::string format_file_path = \"\/sys\/kernel\/debug\/tracing\/events\/\" + category + \"\/\" + event_name + \"\/format\";\n glob_t glob_result;\n\n if (has_wildcard(category) || has_wildcard(event_name))\n {\n \/\/ tracepoint wildcard expansion, part 1 of 3. struct definitions.\n memset(&glob_result, 0, sizeof(glob_result));\n int ret = glob(format_file_path.c_str(), 0, NULL, &glob_result);\n if (ret != 0)\n {\n if (ret == GLOB_NOMATCH)\n {\n LOG(ERROR, ap->loc, std::cerr)\n << \"tracepoints not found: \" << category << \":\" << event_name;\n \/\/ helper message:\n if (category == \"syscall\")\n LOG(ERROR, ap->loc, std::cerr)\n << \"Did you mean syscalls:\" << event_name << \"?\";\n if (bt_verbose) {\n LOG(ERROR) << strerror(errno) << \": \" << format_file_path;\n }\n return false;\n }\n else\n {\n \/\/ unexpected error\n LOG(ERROR, ap->loc, std::cerr) << std::string(strerror(errno));\n return false;\n }\n }\n\n if (probe->tp_args_structs_level <= 0)\n continue;\n\n for (size_t i = 0; i < glob_result.gl_pathc; ++i) {\n std::string filename(glob_result.gl_pathv[i]);\n std::ifstream format_file(filename);\n std::string prefix(\"\/sys\/kernel\/debug\/tracing\/events\/\");\n size_t pos = prefix.length();\n std::string real_category = filename.substr(\n pos, filename.find('\/', pos) - pos);\n pos = prefix.length() + real_category.length() + 1;\n std::string real_event = filename.substr(\n pos, filename.length() - std::string(\"\/format\").length() - pos);\n\n \/\/ Check to avoid adding the same struct more than once to definitions\n std::string struct_name = get_struct_name(real_category,\n real_event);\n if (!TracepointFormatParser::struct_list.count(struct_name))\n {\n program->c_definitions += get_tracepoint_struct(\n format_file, real_category, real_event, bpftrace);\n TracepointFormatParser::struct_list.insert(struct_name);\n }\n }\n globfree(&glob_result);\n }\n else\n {\n \/\/ single tracepoint\n std::ifstream format_file(format_file_path.c_str());\n if (format_file.fail())\n {\n \/\/ Errno might get clobbered by LOG().\n int saved_errno = errno;\n\n LOG(ERROR, ap->loc, std::cerr)\n << \"tracepoint not found: \" << category << \":\" << event_name;\n \/\/ helper message:\n if (category == \"syscall\")\n LOG(WARNING, ap->loc, std::cerr)\n << \"Did you mean syscalls:\" << event_name << \"?\";\n if (bt_verbose) {\n \/\/ Having the location info isn't really useful here, so no\n \/\/ bpftrace.error\n LOG(ERROR) << strerror(saved_errno) << \": \" << format_file_path;\n }\n return false;\n }\n\n if (probe->tp_args_structs_level <= 0)\n continue;\n\n \/\/ Check to avoid adding the same struct more than once to definitions\n std::string struct_name = get_struct_name(category, event_name);\n if (TracepointFormatParser::struct_list.insert(struct_name).second)\n program->c_definitions += get_tracepoint_struct(\n format_file, category, event_name, bpftrace);\n }\n }\n }\n }\n return true;\n}\n\nstd::string TracepointFormatParser::get_struct_name(const std::string &category, const std::string &event_name)\n{\n return \"struct _tracepoint_\" + category + \"_\" + event_name;\n}\n\nstd::string TracepointFormatParser::get_struct_name(const std::string &probe_id)\n{\n \/\/ probe_id has format category:event\n std::string event_name = probe_id;\n std::string category = erase_prefix(event_name);\n return get_struct_name(category, event_name);\n}\n\nstd::string TracepointFormatParser::parse_field(const std::string &line,\n int *last_offset,\n BPFtrace &bpftrace)\n{\n std::string extra = \"\";\n\n auto field_pos = line.find(\"field:\");\n if (field_pos == std::string::npos)\n return \"\";\n\n auto field_semi_pos = line.find(';', field_pos);\n if (field_semi_pos == std::string::npos)\n return \"\";\n\n auto offset_pos = line.find(\"offset:\", field_semi_pos);\n if (offset_pos == std::string::npos)\n return \"\";\n\n auto offset_semi_pos = line.find(';', offset_pos);\n if (offset_semi_pos == std::string::npos)\n return \"\";\n\n auto size_pos = line.find(\"size:\", offset_semi_pos);\n if (size_pos == std::string::npos)\n return \"\";\n\n auto size_semi_pos = line.find(';', size_pos);\n if (size_semi_pos == std::string::npos)\n return \"\";\n\n int size = std::stoi(line.substr(size_pos + 5, size_semi_pos - size_pos - 5));\n int offset = std::stoi(\n line.substr(offset_pos + 7, offset_semi_pos - offset_pos - 7));\n\n \/\/ If there'a gap between last field and this one,\n \/\/ generate padding fields\n if (offset && *last_offset)\n {\n int i, gap = offset - *last_offset;\n\n for (i = 0; i < gap; i++)\n {\n extra += \" char __pad_\" + std::to_string(offset - gap + i) + \";\\n\";\n }\n }\n\n *last_offset = offset + size;\n\n std::string field = line.substr(field_pos + 6, field_semi_pos - field_pos - 6);\n auto field_type_end_pos = field.find_last_of(\"\\t \");\n if (field_type_end_pos == std::string::npos)\n return \"\";\n std::string field_type = field.substr(0, field_type_end_pos);\n std::string field_name = field.substr(field_type_end_pos+1);\n\n if (field_type.find(\"__data_loc\") != std::string::npos)\n {\n \/\/ Note that the type here (ie `int`) does not matter. Later during parse\n \/\/ time the parser will rewrite this field type to a u64 so that it can\n \/\/ hold the pointer to the actual location of the data.\n field_type = R\"_(__attribute__((annotate(\"tp_data_loc\"))) int)_\";\n }\n\n \/\/ Only adjust field types for non-arrays\n if (field_name.find(\"[\") == std::string::npos)\n field_type = adjust_integer_types(field_type, size);\n\n \/\/ With --btf on, we try not to use any header files, including\n \/\/ . That means we must request all the types we need\n \/\/ from BTF. Note we don't need to gate this on --btf because the\n \/\/ expensive type reslution is already gated on --btf (adding to a set\n \/\/ is cheap).\n bpftrace.btf_set_.emplace(field_type);\n\n return extra + \" \" + field_type + \" \" + field_name + \";\\n\";\n}\n\nstd::string TracepointFormatParser::adjust_integer_types(const std::string &field_type, int size)\n{\n std::string new_type = field_type;\n \/\/ Adjust integer fields to correctly sized types\n if (size == 8)\n {\n if (field_type == \"int\")\n new_type = \"s64\";\n if (field_type == \"unsigned int\" || field_type == \"unsigned\" ||\n field_type == \"u32\" || field_type == \"pid_t\" ||\n field_type == \"uid_t\" || field_type == \"gid_t\")\n new_type = \"u64\";\n }\n\n return new_type;\n}\n\nstd::string TracepointFormatParser::get_tracepoint_struct(\n std::istream &format_file,\n const std::string &category,\n const std::string &event_name,\n BPFtrace &bpftrace)\n{\n std::string format_struct = get_struct_name(category, event_name) + \"\\n{\\n\";\n int last_offset = 0;\n\n for (std::string line; getline(format_file, line); )\n {\n format_struct += parse_field(line, &last_offset, bpftrace);\n }\n\n format_struct += \"};\\n\";\n return format_struct;\n}\n\n} \/\/ namespace bpftrace\nFix memory leak in tracepoint parser#include \n#include \n#include \n#include \n\n#include \"ast.h\"\n#include \"bpftrace.h\"\n#include \"log.h\"\n#include \"struct.h\"\n#include \"tracepoint_format_parser.h\"\n\nnamespace bpftrace {\n\nstd::set TracepointFormatParser::struct_list;\n\nbool TracepointFormatParser::parse(ast::Program *program, BPFtrace &bpftrace)\n{\n std::vector probes_with_tracepoint;\n for (ast::Probe *probe : *program->probes)\n for (ast::AttachPoint *ap : *probe->attach_points)\n if (ap->provider == \"tracepoint\") {\n probes_with_tracepoint.push_back(probe);\n continue;\n }\n\n if (probes_with_tracepoint.empty())\n return true;\n\n ast::TracepointArgsVisitor n{};\n if (!bpftrace.btf_.has_data())\n program->c_definitions += \"#include \\n\";\n for (ast::Probe *probe : probes_with_tracepoint)\n {\n n.visit(*probe);\n\n for (ast::AttachPoint *ap : *probe->attach_points)\n {\n if (ap->provider == \"tracepoint\")\n {\n std::string &category = ap->target;\n std::string &event_name = ap->func;\n std::string format_file_path = \"\/sys\/kernel\/debug\/tracing\/events\/\" + category + \"\/\" + event_name + \"\/format\";\n glob_t glob_result;\n\n if (has_wildcard(category) || has_wildcard(event_name))\n {\n \/\/ tracepoint wildcard expansion, part 1 of 3. struct definitions.\n memset(&glob_result, 0, sizeof(glob_result));\n int ret = glob(format_file_path.c_str(), 0, NULL, &glob_result);\n if (ret != 0)\n {\n if (ret == GLOB_NOMATCH)\n {\n LOG(ERROR, ap->loc, std::cerr)\n << \"tracepoints not found: \" << category << \":\" << event_name;\n \/\/ helper message:\n if (category == \"syscall\")\n LOG(ERROR, ap->loc, std::cerr)\n << \"Did you mean syscalls:\" << event_name << \"?\";\n if (bt_verbose) {\n LOG(ERROR) << strerror(errno) << \": \" << format_file_path;\n }\n return false;\n }\n else\n {\n \/\/ unexpected error\n LOG(ERROR, ap->loc, std::cerr) << std::string(strerror(errno));\n return false;\n }\n }\n\n if (probe->tp_args_structs_level <= 0)\n {\n globfree(&glob_result);\n continue;\n }\n\n for (size_t i = 0; i < glob_result.gl_pathc; ++i) {\n std::string filename(glob_result.gl_pathv[i]);\n std::ifstream format_file(filename);\n std::string prefix(\"\/sys\/kernel\/debug\/tracing\/events\/\");\n size_t pos = prefix.length();\n std::string real_category = filename.substr(\n pos, filename.find('\/', pos) - pos);\n pos = prefix.length() + real_category.length() + 1;\n std::string real_event = filename.substr(\n pos, filename.length() - std::string(\"\/format\").length() - pos);\n\n \/\/ Check to avoid adding the same struct more than once to definitions\n std::string struct_name = get_struct_name(real_category,\n real_event);\n if (!TracepointFormatParser::struct_list.count(struct_name))\n {\n program->c_definitions += get_tracepoint_struct(\n format_file, real_category, real_event, bpftrace);\n TracepointFormatParser::struct_list.insert(struct_name);\n }\n }\n globfree(&glob_result);\n }\n else\n {\n \/\/ single tracepoint\n std::ifstream format_file(format_file_path.c_str());\n if (format_file.fail())\n {\n \/\/ Errno might get clobbered by LOG().\n int saved_errno = errno;\n\n LOG(ERROR, ap->loc, std::cerr)\n << \"tracepoint not found: \" << category << \":\" << event_name;\n \/\/ helper message:\n if (category == \"syscall\")\n LOG(WARNING, ap->loc, std::cerr)\n << \"Did you mean syscalls:\" << event_name << \"?\";\n if (bt_verbose) {\n \/\/ Having the location info isn't really useful here, so no\n \/\/ bpftrace.error\n LOG(ERROR) << strerror(saved_errno) << \": \" << format_file_path;\n }\n return false;\n }\n\n if (probe->tp_args_structs_level <= 0)\n continue;\n\n \/\/ Check to avoid adding the same struct more than once to definitions\n std::string struct_name = get_struct_name(category, event_name);\n if (TracepointFormatParser::struct_list.insert(struct_name).second)\n program->c_definitions += get_tracepoint_struct(\n format_file, category, event_name, bpftrace);\n }\n }\n }\n }\n return true;\n}\n\nstd::string TracepointFormatParser::get_struct_name(const std::string &category, const std::string &event_name)\n{\n return \"struct _tracepoint_\" + category + \"_\" + event_name;\n}\n\nstd::string TracepointFormatParser::get_struct_name(const std::string &probe_id)\n{\n \/\/ probe_id has format category:event\n std::string event_name = probe_id;\n std::string category = erase_prefix(event_name);\n return get_struct_name(category, event_name);\n}\n\nstd::string TracepointFormatParser::parse_field(const std::string &line,\n int *last_offset,\n BPFtrace &bpftrace)\n{\n std::string extra = \"\";\n\n auto field_pos = line.find(\"field:\");\n if (field_pos == std::string::npos)\n return \"\";\n\n auto field_semi_pos = line.find(';', field_pos);\n if (field_semi_pos == std::string::npos)\n return \"\";\n\n auto offset_pos = line.find(\"offset:\", field_semi_pos);\n if (offset_pos == std::string::npos)\n return \"\";\n\n auto offset_semi_pos = line.find(';', offset_pos);\n if (offset_semi_pos == std::string::npos)\n return \"\";\n\n auto size_pos = line.find(\"size:\", offset_semi_pos);\n if (size_pos == std::string::npos)\n return \"\";\n\n auto size_semi_pos = line.find(';', size_pos);\n if (size_semi_pos == std::string::npos)\n return \"\";\n\n int size = std::stoi(line.substr(size_pos + 5, size_semi_pos - size_pos - 5));\n int offset = std::stoi(\n line.substr(offset_pos + 7, offset_semi_pos - offset_pos - 7));\n\n \/\/ If there'a gap between last field and this one,\n \/\/ generate padding fields\n if (offset && *last_offset)\n {\n int i, gap = offset - *last_offset;\n\n for (i = 0; i < gap; i++)\n {\n extra += \" char __pad_\" + std::to_string(offset - gap + i) + \";\\n\";\n }\n }\n\n *last_offset = offset + size;\n\n std::string field = line.substr(field_pos + 6, field_semi_pos - field_pos - 6);\n auto field_type_end_pos = field.find_last_of(\"\\t \");\n if (field_type_end_pos == std::string::npos)\n return \"\";\n std::string field_type = field.substr(0, field_type_end_pos);\n std::string field_name = field.substr(field_type_end_pos+1);\n\n if (field_type.find(\"__data_loc\") != std::string::npos)\n {\n \/\/ Note that the type here (ie `int`) does not matter. Later during parse\n \/\/ time the parser will rewrite this field type to a u64 so that it can\n \/\/ hold the pointer to the actual location of the data.\n field_type = R\"_(__attribute__((annotate(\"tp_data_loc\"))) int)_\";\n }\n\n \/\/ Only adjust field types for non-arrays\n if (field_name.find(\"[\") == std::string::npos)\n field_type = adjust_integer_types(field_type, size);\n\n \/\/ With --btf on, we try not to use any header files, including\n \/\/ . That means we must request all the types we need\n \/\/ from BTF. Note we don't need to gate this on --btf because the\n \/\/ expensive type reslution is already gated on --btf (adding to a set\n \/\/ is cheap).\n bpftrace.btf_set_.emplace(field_type);\n\n return extra + \" \" + field_type + \" \" + field_name + \";\\n\";\n}\n\nstd::string TracepointFormatParser::adjust_integer_types(const std::string &field_type, int size)\n{\n std::string new_type = field_type;\n \/\/ Adjust integer fields to correctly sized types\n if (size == 8)\n {\n if (field_type == \"int\")\n new_type = \"s64\";\n if (field_type == \"unsigned int\" || field_type == \"unsigned\" ||\n field_type == \"u32\" || field_type == \"pid_t\" ||\n field_type == \"uid_t\" || field_type == \"gid_t\")\n new_type = \"u64\";\n }\n\n return new_type;\n}\n\nstd::string TracepointFormatParser::get_tracepoint_struct(\n std::istream &format_file,\n const std::string &category,\n const std::string &event_name,\n BPFtrace &bpftrace)\n{\n std::string format_struct = get_struct_name(category, event_name) + \"\\n{\\n\";\n int last_offset = 0;\n\n for (std::string line; getline(format_file, line); )\n {\n format_struct += parse_field(line, &last_offset, bpftrace);\n }\n\n format_struct += \"};\\n\";\n return format_struct;\n}\n\n} \/\/ namespace bpftrace\n<|endoftext|>"} {"text":"\/\/===--- TestOptions.cpp --------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"TestOptions.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Option\/Arg.h\"\n#include \"llvm\/Option\/ArgList.h\"\n#include \"llvm\/Option\/Option.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace sourcekitd_test;\nusing llvm::StringRef;\n\nnamespace {\n\n\/\/ Create enum with OPT_xxx values for each option in Options.td.\nenum Opt {\n OPT_INVALID = 0,\n#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \\\n HELP, META, VALUES) \\\n OPT_##ID,\n#include \"Options.inc\"\n LastOption\n#undef OPTION\n};\n\n\/\/ Create prefix string literals used in Options.td.\n#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;\n#include \"Options.inc\"\n#undef PREFIX\n\n\/\/ Create table mapping all options defined in Options.td.\nstatic const llvm::opt::OptTable::Info InfoTable[] = {\n#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \\\n HELPTEXT, METAVAR, VALUES) \\\n {PREFIX, NAME, HELPTEXT, \\\n METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \\\n PARAM, FLAGS, OPT_##GROUP, \\\n OPT_##ALIAS, ALIASARGS, VALUES},\n#include \"Options.inc\"\n#undef OPTION\n};\n\n\/\/ Create OptTable class for parsing actual command line arguments\nclass TestOptTable : public llvm::opt::OptTable {\npublic:\n TestOptTable() : OptTable(InfoTable, llvm::array_lengthof(InfoTable)){}\n};\n\n} \/\/ end anonymous namespace\n\nstatic std::pair parseLineCol(StringRef LineCol) {\n unsigned Line, Col;\n size_t ColonIdx = LineCol.find(':');\n if (ColonIdx == StringRef::npos) {\n llvm::errs() << \"wrong pos format, it should be ':'\\n\";\n exit(1);\n }\n if (LineCol.substr(0, ColonIdx).getAsInteger(10, Line)) {\n llvm::errs() << \"wrong pos format, it should be ':'\\n\";\n exit(1);\n }\n if (LineCol.substr(ColonIdx+1).getAsInteger(10, Col)) {\n llvm::errs() << \"wrong pos format, it should be ':'\\n\";\n exit(1);\n }\n\n if (Line == 0 || Col == 0) {\n llvm::errs() << \"wrong pos format, line\/col should start from 1\\n\";\n exit(1);\n }\n\n return { Line, Col };\n}\n\nbool TestOptions::parseArgs(llvm::ArrayRef Args) {\n if (Args.empty())\n return false;\n\n \/\/ Parse command line options using Options.td\n TestOptTable Table;\n unsigned MissingIndex;\n unsigned MissingCount;\n llvm::opt::InputArgList ParsedArgs =\n Table.ParseArgs(Args, MissingIndex, MissingCount);\n if (MissingCount) {\n llvm::errs() << \"error: missing argument value for '\"\n << ParsedArgs.getArgString(MissingIndex) << \"', expected \"\n << MissingCount << \" argument(s)\\n\";\n return true;\n }\n\n for (auto InputArg : ParsedArgs) {\n switch (InputArg->getOption().getID()) {\n case OPT_req:\n Request = llvm::StringSwitch(InputArg->getValue())\n .Case(\"version\", SourceKitRequest::ProtocolVersion)\n .Case(\"demangle\", SourceKitRequest::DemangleNames)\n .Case(\"mangle\", SourceKitRequest::MangleSimpleClasses)\n .Case(\"index\", SourceKitRequest::Index)\n .Case(\"complete\", SourceKitRequest::CodeComplete)\n .Case(\"complete.open\", SourceKitRequest::CodeCompleteOpen)\n .Case(\"complete.close\", SourceKitRequest::CodeCompleteClose)\n .Case(\"complete.update\", SourceKitRequest::CodeCompleteUpdate)\n .Case(\"complete.cache.ondisk\", SourceKitRequest::CodeCompleteCacheOnDisk)\n .Case(\"complete.setpopularapi\", SourceKitRequest::CodeCompleteSetPopularAPI)\n .Case(\"typecontextinfo\", SourceKitRequest::TypeContextInfo)\n .Case(\"cursor\", SourceKitRequest::CursorInfo)\n .Case(\"related-idents\", SourceKitRequest::RelatedIdents)\n .Case(\"syntax-map\", SourceKitRequest::SyntaxMap)\n .Case(\"syntax-tree\", SourceKitRequest::SyntaxTree)\n .Case(\"structure\", SourceKitRequest::Structure)\n .Case(\"format\", SourceKitRequest::Format)\n .Case(\"expand-placeholder\", SourceKitRequest::ExpandPlaceholder)\n .Case(\"doc-info\", SourceKitRequest::DocInfo)\n .Case(\"sema\", SourceKitRequest::SemanticInfo)\n .Case(\"interface-gen\", SourceKitRequest::InterfaceGen)\n .Case(\"interface-gen-open\", SourceKitRequest::InterfaceGenOpen)\n .Case(\"find-usr\", SourceKitRequest::FindUSR)\n .Case(\"find-interface\", SourceKitRequest::FindInterfaceDoc)\n .Case(\"open\", SourceKitRequest::Open)\n .Case(\"close\", SourceKitRequest::Close)\n .Case(\"edit\", SourceKitRequest::Edit)\n .Case(\"print-annotations\", SourceKitRequest::PrintAnnotations)\n .Case(\"print-diags\", SourceKitRequest::PrintDiags)\n .Case(\"extract-comment\", SourceKitRequest::ExtractComment)\n .Case(\"module-groups\", SourceKitRequest::ModuleGroups)\n .Case(\"range\", SourceKitRequest::RangeInfo)\n .Case(\"syntactic-rename\", SourceKitRequest::SyntacticRename)\n .Case(\"find-rename-ranges\", SourceKitRequest::FindRenameRanges)\n .Case(\"find-local-rename-ranges\", SourceKitRequest::FindLocalRenameRanges)\n .Case(\"translate\", SourceKitRequest::NameTranslation)\n .Case(\"local-rename\", SourceKitRequest::LocalRename)\n .Case(\"extract-expr\", SourceKitRequest::ExtractExpr)\n .Case(\"extract-repeated\", SourceKitRequest::ExtractRepeatedExpr)\n .Case(\"extract-func\", SourceKitRequest::ExtractFunction)\n .Case(\"fill-stub\", SourceKitRequest::FillProtocolStub)\n .Case(\"expand-default\", SourceKitRequest::ExpandDefault)\n .Case(\"localize-string\", SourceKitRequest::LocalizeString)\n .Case(\"markup-xml\", SourceKitRequest::MarkupToXML)\n .Case(\"stats\", SourceKitRequest::Statistics)\n .Case(\"track-compiles\", SourceKitRequest::EnableCompileNotifications)\n .Default(SourceKitRequest::None);\n\n if (Request == SourceKitRequest::None) {\n llvm::errs() << \"error: invalid request '\" << InputArg->getValue()\n << \"'\\nexpected one of \"\n << \"version\/demangle\/mangle\/index\/complete\/complete.open\/complete.cursor\/\"\n \"complete.update\/complete.cache.ondisk\/complete.cache.setpopularapi\/\"\n \"cursor\/related-idents\/syntax-map\/structure\/format\/expand-placeholder\/\"\n \"doc-info\/sema\/interface-gen\/interface-gen-openfind-usr\/find-interface\/\"\n \"open\/close\/edit\/print-annotations\/print-diags\/extract-comment\/module-groups\/\"\n \"range\/syntactic-rename\/find-rename-ranges\/translate\/markup-xml\/stats\/\"\n \"track-compiles\\n\";\n return true;\n }\n break;\n\n case OPT_help: {\n printHelp(false);\n return true;\n }\n\n case OPT_offset:\n if (StringRef(InputArg->getValue()).getAsInteger(10, Offset)) {\n llvm::errs() << \"error: expected integer for 'offset'\\n\";\n return true;\n }\n break;\n\n case OPT_length:\n if (StringRef(InputArg->getValue()).getAsInteger(10, Length)) {\n llvm::errs() << \"error: expected integer for 'length'\\n\";\n return true;\n }\n break;\n\n case OPT_pos: {\n auto linecol = parseLineCol(InputArg->getValue());\n Line = linecol.first;\n Col = linecol.second;\n break;\n }\n\n case OPT_end_pos: {\n auto linecol = parseLineCol(InputArg->getValue());\n EndLine = linecol.first;\n EndCol = linecol.second;\n break;\n }\n\n case OPT_using_swift_args: {\n UsingSwiftArgs = true;\n break;\n }\n\n case OPT_swift_version:\n SwiftVersion = InputArg->getValue();\n break;\n\n case OPT_pass_version_as_string:\n PassVersionAsString = true;\n break;\n\n case OPT_line:\n if (StringRef(InputArg->getValue()).getAsInteger(10, Line)) {\n llvm::errs() << \"error: expected integer for 'line'\\n\";\n return true;\n }\n Col = 1;\n break;\n\n case OPT_replace:\n ReplaceText = InputArg->getValue();\n break;\n\n case OPT_module:\n ModuleName = InputArg->getValue();\n break;\n\n case OPT_group_name:\n ModuleGroupName = InputArg->getValue();\n break;\n\n case OPT_interested_usr:\n InterestedUSR = InputArg->getValue();\n break;\n\n case OPT_header:\n HeaderPath = InputArg->getValue();\n break;\n\n case OPT_text_input:\n TextInputFile = InputArg->getValue();\n break;\n\n case OPT_usr:\n USR = InputArg->getValue();\n break;\n\n case OPT_pass_as_sourcetext:\n PassAsSourceText = true;\n break;\n\n case OPT_cache_path:\n CachePath = InputArg->getValue();\n break;\n\n case OPT_req_opts:\n for (auto item : InputArg->getValues())\n RequestOptions.push_back(item);\n break;\n\n case OPT_check_interface_is_ascii:\n CheckInterfaceIsASCII = true;\n break;\n\n case OPT_dont_print_request:\n PrintRequest = false;\n break;\n\n case OPT_print_response_as_json:\n PrintResponseAsJSON = true;\n break;\n\n case OPT_print_raw_response:\n PrintRawResponse = true;\n break;\n\n case OPT_dont_print_response:\n PrintResponse = false;\n break;\n\n case OPT_INPUT:\n SourceFile = InputArg->getValue();\n SourceText = llvm::None;\n Inputs.push_back(InputArg->getValue());\n break;\n\n case OPT_rename_spec:\n RenameSpecPath = InputArg->getValue();\n break;\n\n case OPT_json_request_path:\n JsonRequestPath = InputArg->getValue();\n break;\n\n case OPT_simplified_demangling:\n SimplifiedDemangling = true;\n break;\n\n case OPT_synthesized_extension:\n SynthesizedExtensions = true;\n break;\n\n case OPT_async:\n isAsyncRequest = true;\n break;\n\n case OPT_cursor_action:\n CollectActionables = true;\n break;\n\n case OPT_swift_name:\n SwiftName = InputArg->getValue();\n break;\n\n case OPT_objc_name:\n ObjCName = InputArg->getValue();\n break;\n\n case OPT_objc_selector:\n ObjCSelector = InputArg->getValue();\n break;\n\n case OPT_name:\n Name = InputArg->getValue();\n break;\n\n case OPT_cancel_on_subsequent_request:\n unsigned Cancel;\n if (StringRef(InputArg->getValue()).getAsInteger(10, Cancel)) {\n llvm::errs() << \"error: expected integer for 'cancel-on-subsequent-request'\\n\";\n return true;\n }\n CancelOnSubsequentRequest = Cancel;\n break;\n\n case OPT_time_request:\n timeRequest = true;\n break;\n\n case OPT_repeat_request:\n if (StringRef(InputArg->getValue()).getAsInteger(10, repeatRequest)) {\n llvm::errs() << \"error: expected integer for 'cancel-on-subsequent-request'\\n\";\n return true;\n } else if (repeatRequest < 1) {\n llvm::errs() << \"error: repeat-request must be >= 1\\n\";\n return true;\n }\n break;\n\n case OPT_UNKNOWN:\n llvm::errs() << \"error: unknown argument: \"\n << InputArg->getAsString(ParsedArgs) << '\\n'\n << \"Use -h or -help for assistance\" << '\\n';\n return true;\n }\n }\n\n if (Request == SourceKitRequest::InterfaceGenOpen && isAsyncRequest) {\n llvm::errs()\n << \"error: cannot use -async with interface-gen-open request\\n\";\n return true;\n }\n\n return false;\n}\n\nvoid TestOptions::printHelp(bool ShowHidden) const {\n\n \/\/ Based off of swift\/lib\/Driver\/Driver.cpp, at Driver::printHelp\n \/\/FIXME: should we use IncludedFlagsBitmask and ExcludedFlagsBitmask?\n \/\/ Maybe not for modes such as Interactive, Batch, AutolinkExtract, etc,\n \/\/ as in Driver.cpp. But could be useful for extra info, like HelpHidden.\n\n TestOptTable Table;\n\n Table.PrintHelp(llvm::outs(), \"sourcekitd-test\", \"SourceKit Testing Tool\",\n ShowHidden);\n}\n[master-next] Adjust sourcekitd-test PrintHelp call for LLVM r344097\/\/===--- TestOptions.cpp --------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"TestOptions.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Option\/Arg.h\"\n#include \"llvm\/Option\/ArgList.h\"\n#include \"llvm\/Option\/Option.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace sourcekitd_test;\nusing llvm::StringRef;\n\nnamespace {\n\n\/\/ Create enum with OPT_xxx values for each option in Options.td.\nenum Opt {\n OPT_INVALID = 0,\n#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \\\n HELP, META, VALUES) \\\n OPT_##ID,\n#include \"Options.inc\"\n LastOption\n#undef OPTION\n};\n\n\/\/ Create prefix string literals used in Options.td.\n#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;\n#include \"Options.inc\"\n#undef PREFIX\n\n\/\/ Create table mapping all options defined in Options.td.\nstatic const llvm::opt::OptTable::Info InfoTable[] = {\n#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \\\n HELPTEXT, METAVAR, VALUES) \\\n {PREFIX, NAME, HELPTEXT, \\\n METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \\\n PARAM, FLAGS, OPT_##GROUP, \\\n OPT_##ALIAS, ALIASARGS, VALUES},\n#include \"Options.inc\"\n#undef OPTION\n};\n\n\/\/ Create OptTable class for parsing actual command line arguments\nclass TestOptTable : public llvm::opt::OptTable {\npublic:\n TestOptTable() : OptTable(InfoTable, llvm::array_lengthof(InfoTable)){}\n};\n\n} \/\/ end anonymous namespace\n\nstatic std::pair parseLineCol(StringRef LineCol) {\n unsigned Line, Col;\n size_t ColonIdx = LineCol.find(':');\n if (ColonIdx == StringRef::npos) {\n llvm::errs() << \"wrong pos format, it should be ':'\\n\";\n exit(1);\n }\n if (LineCol.substr(0, ColonIdx).getAsInteger(10, Line)) {\n llvm::errs() << \"wrong pos format, it should be ':'\\n\";\n exit(1);\n }\n if (LineCol.substr(ColonIdx+1).getAsInteger(10, Col)) {\n llvm::errs() << \"wrong pos format, it should be ':'\\n\";\n exit(1);\n }\n\n if (Line == 0 || Col == 0) {\n llvm::errs() << \"wrong pos format, line\/col should start from 1\\n\";\n exit(1);\n }\n\n return { Line, Col };\n}\n\nbool TestOptions::parseArgs(llvm::ArrayRef Args) {\n if (Args.empty())\n return false;\n\n \/\/ Parse command line options using Options.td\n TestOptTable Table;\n unsigned MissingIndex;\n unsigned MissingCount;\n llvm::opt::InputArgList ParsedArgs =\n Table.ParseArgs(Args, MissingIndex, MissingCount);\n if (MissingCount) {\n llvm::errs() << \"error: missing argument value for '\"\n << ParsedArgs.getArgString(MissingIndex) << \"', expected \"\n << MissingCount << \" argument(s)\\n\";\n return true;\n }\n\n for (auto InputArg : ParsedArgs) {\n switch (InputArg->getOption().getID()) {\n case OPT_req:\n Request = llvm::StringSwitch(InputArg->getValue())\n .Case(\"version\", SourceKitRequest::ProtocolVersion)\n .Case(\"demangle\", SourceKitRequest::DemangleNames)\n .Case(\"mangle\", SourceKitRequest::MangleSimpleClasses)\n .Case(\"index\", SourceKitRequest::Index)\n .Case(\"complete\", SourceKitRequest::CodeComplete)\n .Case(\"complete.open\", SourceKitRequest::CodeCompleteOpen)\n .Case(\"complete.close\", SourceKitRequest::CodeCompleteClose)\n .Case(\"complete.update\", SourceKitRequest::CodeCompleteUpdate)\n .Case(\"complete.cache.ondisk\", SourceKitRequest::CodeCompleteCacheOnDisk)\n .Case(\"complete.setpopularapi\", SourceKitRequest::CodeCompleteSetPopularAPI)\n .Case(\"typecontextinfo\", SourceKitRequest::TypeContextInfo)\n .Case(\"cursor\", SourceKitRequest::CursorInfo)\n .Case(\"related-idents\", SourceKitRequest::RelatedIdents)\n .Case(\"syntax-map\", SourceKitRequest::SyntaxMap)\n .Case(\"syntax-tree\", SourceKitRequest::SyntaxTree)\n .Case(\"structure\", SourceKitRequest::Structure)\n .Case(\"format\", SourceKitRequest::Format)\n .Case(\"expand-placeholder\", SourceKitRequest::ExpandPlaceholder)\n .Case(\"doc-info\", SourceKitRequest::DocInfo)\n .Case(\"sema\", SourceKitRequest::SemanticInfo)\n .Case(\"interface-gen\", SourceKitRequest::InterfaceGen)\n .Case(\"interface-gen-open\", SourceKitRequest::InterfaceGenOpen)\n .Case(\"find-usr\", SourceKitRequest::FindUSR)\n .Case(\"find-interface\", SourceKitRequest::FindInterfaceDoc)\n .Case(\"open\", SourceKitRequest::Open)\n .Case(\"close\", SourceKitRequest::Close)\n .Case(\"edit\", SourceKitRequest::Edit)\n .Case(\"print-annotations\", SourceKitRequest::PrintAnnotations)\n .Case(\"print-diags\", SourceKitRequest::PrintDiags)\n .Case(\"extract-comment\", SourceKitRequest::ExtractComment)\n .Case(\"module-groups\", SourceKitRequest::ModuleGroups)\n .Case(\"range\", SourceKitRequest::RangeInfo)\n .Case(\"syntactic-rename\", SourceKitRequest::SyntacticRename)\n .Case(\"find-rename-ranges\", SourceKitRequest::FindRenameRanges)\n .Case(\"find-local-rename-ranges\", SourceKitRequest::FindLocalRenameRanges)\n .Case(\"translate\", SourceKitRequest::NameTranslation)\n .Case(\"local-rename\", SourceKitRequest::LocalRename)\n .Case(\"extract-expr\", SourceKitRequest::ExtractExpr)\n .Case(\"extract-repeated\", SourceKitRequest::ExtractRepeatedExpr)\n .Case(\"extract-func\", SourceKitRequest::ExtractFunction)\n .Case(\"fill-stub\", SourceKitRequest::FillProtocolStub)\n .Case(\"expand-default\", SourceKitRequest::ExpandDefault)\n .Case(\"localize-string\", SourceKitRequest::LocalizeString)\n .Case(\"markup-xml\", SourceKitRequest::MarkupToXML)\n .Case(\"stats\", SourceKitRequest::Statistics)\n .Case(\"track-compiles\", SourceKitRequest::EnableCompileNotifications)\n .Default(SourceKitRequest::None);\n\n if (Request == SourceKitRequest::None) {\n llvm::errs() << \"error: invalid request '\" << InputArg->getValue()\n << \"'\\nexpected one of \"\n << \"version\/demangle\/mangle\/index\/complete\/complete.open\/complete.cursor\/\"\n \"complete.update\/complete.cache.ondisk\/complete.cache.setpopularapi\/\"\n \"cursor\/related-idents\/syntax-map\/structure\/format\/expand-placeholder\/\"\n \"doc-info\/sema\/interface-gen\/interface-gen-openfind-usr\/find-interface\/\"\n \"open\/close\/edit\/print-annotations\/print-diags\/extract-comment\/module-groups\/\"\n \"range\/syntactic-rename\/find-rename-ranges\/translate\/markup-xml\/stats\/\"\n \"track-compiles\\n\";\n return true;\n }\n break;\n\n case OPT_help: {\n printHelp(false);\n return true;\n }\n\n case OPT_offset:\n if (StringRef(InputArg->getValue()).getAsInteger(10, Offset)) {\n llvm::errs() << \"error: expected integer for 'offset'\\n\";\n return true;\n }\n break;\n\n case OPT_length:\n if (StringRef(InputArg->getValue()).getAsInteger(10, Length)) {\n llvm::errs() << \"error: expected integer for 'length'\\n\";\n return true;\n }\n break;\n\n case OPT_pos: {\n auto linecol = parseLineCol(InputArg->getValue());\n Line = linecol.first;\n Col = linecol.second;\n break;\n }\n\n case OPT_end_pos: {\n auto linecol = parseLineCol(InputArg->getValue());\n EndLine = linecol.first;\n EndCol = linecol.second;\n break;\n }\n\n case OPT_using_swift_args: {\n UsingSwiftArgs = true;\n break;\n }\n\n case OPT_swift_version:\n SwiftVersion = InputArg->getValue();\n break;\n\n case OPT_pass_version_as_string:\n PassVersionAsString = true;\n break;\n\n case OPT_line:\n if (StringRef(InputArg->getValue()).getAsInteger(10, Line)) {\n llvm::errs() << \"error: expected integer for 'line'\\n\";\n return true;\n }\n Col = 1;\n break;\n\n case OPT_replace:\n ReplaceText = InputArg->getValue();\n break;\n\n case OPT_module:\n ModuleName = InputArg->getValue();\n break;\n\n case OPT_group_name:\n ModuleGroupName = InputArg->getValue();\n break;\n\n case OPT_interested_usr:\n InterestedUSR = InputArg->getValue();\n break;\n\n case OPT_header:\n HeaderPath = InputArg->getValue();\n break;\n\n case OPT_text_input:\n TextInputFile = InputArg->getValue();\n break;\n\n case OPT_usr:\n USR = InputArg->getValue();\n break;\n\n case OPT_pass_as_sourcetext:\n PassAsSourceText = true;\n break;\n\n case OPT_cache_path:\n CachePath = InputArg->getValue();\n break;\n\n case OPT_req_opts:\n for (auto item : InputArg->getValues())\n RequestOptions.push_back(item);\n break;\n\n case OPT_check_interface_is_ascii:\n CheckInterfaceIsASCII = true;\n break;\n\n case OPT_dont_print_request:\n PrintRequest = false;\n break;\n\n case OPT_print_response_as_json:\n PrintResponseAsJSON = true;\n break;\n\n case OPT_print_raw_response:\n PrintRawResponse = true;\n break;\n\n case OPT_dont_print_response:\n PrintResponse = false;\n break;\n\n case OPT_INPUT:\n SourceFile = InputArg->getValue();\n SourceText = llvm::None;\n Inputs.push_back(InputArg->getValue());\n break;\n\n case OPT_rename_spec:\n RenameSpecPath = InputArg->getValue();\n break;\n\n case OPT_json_request_path:\n JsonRequestPath = InputArg->getValue();\n break;\n\n case OPT_simplified_demangling:\n SimplifiedDemangling = true;\n break;\n\n case OPT_synthesized_extension:\n SynthesizedExtensions = true;\n break;\n\n case OPT_async:\n isAsyncRequest = true;\n break;\n\n case OPT_cursor_action:\n CollectActionables = true;\n break;\n\n case OPT_swift_name:\n SwiftName = InputArg->getValue();\n break;\n\n case OPT_objc_name:\n ObjCName = InputArg->getValue();\n break;\n\n case OPT_objc_selector:\n ObjCSelector = InputArg->getValue();\n break;\n\n case OPT_name:\n Name = InputArg->getValue();\n break;\n\n case OPT_cancel_on_subsequent_request:\n unsigned Cancel;\n if (StringRef(InputArg->getValue()).getAsInteger(10, Cancel)) {\n llvm::errs() << \"error: expected integer for 'cancel-on-subsequent-request'\\n\";\n return true;\n }\n CancelOnSubsequentRequest = Cancel;\n break;\n\n case OPT_time_request:\n timeRequest = true;\n break;\n\n case OPT_repeat_request:\n if (StringRef(InputArg->getValue()).getAsInteger(10, repeatRequest)) {\n llvm::errs() << \"error: expected integer for 'cancel-on-subsequent-request'\\n\";\n return true;\n } else if (repeatRequest < 1) {\n llvm::errs() << \"error: repeat-request must be >= 1\\n\";\n return true;\n }\n break;\n\n case OPT_UNKNOWN:\n llvm::errs() << \"error: unknown argument: \"\n << InputArg->getAsString(ParsedArgs) << '\\n'\n << \"Use -h or -help for assistance\" << '\\n';\n return true;\n }\n }\n\n if (Request == SourceKitRequest::InterfaceGenOpen && isAsyncRequest) {\n llvm::errs()\n << \"error: cannot use -async with interface-gen-open request\\n\";\n return true;\n }\n\n return false;\n}\n\nvoid TestOptions::printHelp(bool ShowHidden) const {\n\n \/\/ Based off of swift\/lib\/Driver\/Driver.cpp, at Driver::printHelp\n \/\/FIXME: should we use IncludedFlagsBitmask and ExcludedFlagsBitmask?\n \/\/ Maybe not for modes such as Interactive, Batch, AutolinkExtract, etc,\n \/\/ as in Driver.cpp. But could be useful for extra info, like HelpHidden.\n\n TestOptTable Table;\n\n Table.PrintHelp(llvm::outs(), \"sourcekitd-test [options] \",\n \"SourceKit Testing Tool\", ShowHidden);\n}\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n\n#include \"lib\/sql_util.h\"\n#include \"lib\/file_replace.h\"\n\nusing hawq::test::SQLUtility;\nusing hawq::test::FileReplace;\n\nclass TestExternalTable : public ::testing::Test {\n public:\n TestExternalTable() {}\n ~TestExternalTable() {}\n};\n\nTEST_F(TestExternalTable, TestExternalTableAll) {\n SQLUtility util;\n auto test_root = util.getTestRootPath();\n auto replace_lambda = [&] () {\n FileReplace frep;\n std::unordered_map D;\n D[\"@hostname@\"] = std::string(\"localhost\");\n D[\"@abs_srcdir@\"] = test_root + \"\/ExternalSource\";\n D[\"@gpwhich_gpfdist@\"] = std::string(std::string(getenv(\"GPHOME\")) + \"\/bin\/gpfdist\");\n frep.replace(test_root + \"\/ExternalSource\/sql\/exttab1.sql.source\",\n test_root + \"\/ExternalSource\/sql\/exttab1.sql\",\n D);\n frep.replace(test_root + \"\/ExternalSource\/ans\/exttab1.ans.source\",\n test_root + \"\/ExternalSource\/ans\/exttab1.ans\",\n D);\n };\n \n replace_lambda();\n util.execSQLFile(\"ExternalSource\/sql\/exttab1.sql\",\n \"ExternalSource\/ans\/exttab1.ans\");\n}\nHAWQ-1126. Disable feature test case of ExternalTable temporarily#include \"gtest\/gtest.h\"\n\n#include \"lib\/sql_util.h\"\n#include \"lib\/file_replace.h\"\n\nusing hawq::test::SQLUtility;\nusing hawq::test::FileReplace;\n\nclass TestExternalTable : public ::testing::Test {\n public:\n TestExternalTable() {}\n ~TestExternalTable() {}\n};\n\nTEST_F(TestExternalTable, DISABLED_TestExternalTableAll) {\n SQLUtility util;\n auto test_root = util.getTestRootPath();\n auto replace_lambda = [&] () {\n FileReplace frep;\n std::unordered_map D;\n D[\"@hostname@\"] = std::string(\"localhost\");\n D[\"@abs_srcdir@\"] = test_root + \"\/ExternalSource\";\n D[\"@gpwhich_gpfdist@\"] = std::string(std::string(getenv(\"GPHOME\")) + \"\/bin\/gpfdist\");\n frep.replace(test_root + \"\/ExternalSource\/sql\/exttab1.sql.source\",\n test_root + \"\/ExternalSource\/sql\/exttab1.sql\",\n D);\n frep.replace(test_root + \"\/ExternalSource\/ans\/exttab1.ans.source\",\n test_root + \"\/ExternalSource\/ans\/exttab1.ans\",\n D);\n };\n \n replace_lambda();\n util.execSQLFile(\"ExternalSource\/sql\/exttab1.sql\",\n \"ExternalSource\/ans\/exttab1.ans\");\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008-2013 The Communi Project\n *\n * This test is free, and not covered by the LGPL license. There is no\n * restriction applied to their modification, redistribution, using and so on.\n * You can study them, modify them, use them in your own program - either\n * completely or partially.\n *\/\n\n#include \"irc.h\"\n#include \"irctextformat.h\"\n#include \n\nclass tst_IrcTextFormat : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void testDefaults();\n void testColorName();\n void testPlainText_data();\n void testPlainText();\n};\n\nvoid tst_IrcTextFormat::testDefaults()\n{\n IrcTextFormat format;\n QVERIFY(!format.urlPattern().isEmpty());\n for (int i = Irc::White; i <= Irc::LightGray; ++i)\n QVERIFY(!format.colorName(i).isEmpty());\n QCOMPARE(format.colorName(-1, \"fallback\"), QString(\"fallback\"));\n}\n\nvoid tst_IrcTextFormat::testColorName()\n{\n IrcTextFormat format;\n for (int i = -1; i <= 123; ++i) {\n format.setColorName(i, QString::number(i));\n QCOMPARE(format.colorName(i), QString::number(i));\n }\n}\n\nvoid tst_IrcTextFormat::testPlainText_data()\n{\n QTest::addColumn(\"input\");\n QTest::addColumn(\"output\");\n\n QTest::newRow(\"bold\") << \"\\02bold\\x0f\" << \"bold\";\n QTest::newRow(\"strike-through\") << \"\\x13strike-through\\x0f\" << \"strike-through\";\n QTest::newRow(\"underline\") << \"\\x15underline\\x0f\" << \"underline\";\n QTest::newRow(\"inverse\") << \"\\x16inverse\\x0f\" << \"inverse\";\n QTest::newRow(\"italic\") << \"\\x1ditalic\\x0f\" << \"italic\";\n QTest::newRow(\"underline\") << \"\\x1funderline\\x0f\" << \"underline\";\n\n IrcTextFormat format;\n for (int i = Irc::White; i <= Irc::LightGray; ++i) {\n QString color = format.colorName(i);\n QTest::newRow(color.toUtf8()) << QString(\"\\x03%1%2\\x0f\").arg(i).arg(color) << color;\n }\n}\n\nvoid tst_IrcTextFormat::testPlainText()\n{\n QFETCH(QString, input);\n QFETCH(QString, output);\n\n IrcTextFormat format;\n QCOMPARE(format.toPlainText(input), output);\n}\n\nQTEST_MAIN(tst_IrcTextFormat)\n\n#include \"tst_irctextformat.moc\"\nExtend IrcTextFormat auto test\/*\n * Copyright (C) 2008-2013 The Communi Project\n *\n * This test is free, and not covered by the LGPL license. There is no\n * restriction applied to their modification, redistribution, using and so on.\n * You can study them, modify them, use them in your own program - either\n * completely or partially.\n *\/\n\n#include \"irc.h\"\n#include \"irctextformat.h\"\n#include \n\nclass tst_IrcTextFormat : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void testDefaults();\n void testColorName();\n void testPlainText_data();\n void testPlainText();\n void testHtml_data();\n void testHtml();\n void testUrls_data();\n void testUrls();\n};\n\nvoid tst_IrcTextFormat::testDefaults()\n{\n IrcTextFormat format;\n QVERIFY(!format.urlPattern().isEmpty());\n for (int i = Irc::White; i <= Irc::LightGray; ++i)\n QVERIFY(!format.colorName(i).isEmpty());\n QCOMPARE(format.colorName(-1, \"fallback\"), QString(\"fallback\"));\n}\n\nvoid tst_IrcTextFormat::testColorName()\n{\n IrcTextFormat format;\n for (int i = -1; i <= 123; ++i) {\n format.setColorName(i, QString::number(i));\n QCOMPARE(format.colorName(i), QString::number(i));\n }\n}\n\nvoid tst_IrcTextFormat::testPlainText_data()\n{\n QTest::addColumn(\"input\");\n QTest::addColumn(\"output\");\n\n QTest::newRow(\"bold\") << \"\\02bold\\x0f\" << \"bold\";\n QTest::newRow(\"strike-through\") << \"\\x13strike-through\\x0f\" << \"strike-through\";\n QTest::newRow(\"underline\") << \"\\x15underline\\x0f\" << \"underline\";\n QTest::newRow(\"inverse\") << \"\\x16inverse\\x0f\" << \"inverse\";\n QTest::newRow(\"italic\") << \"\\x1ditalic\\x0f\" << \"italic\";\n QTest::newRow(\"underline\") << \"\\x1funderline\\x0f\" << \"underline\";\n\n IrcTextFormat format;\n for (int i = Irc::White; i <= Irc::LightGray; ++i) {\n QString color = format.colorName(i);\n QTest::newRow(color.toUtf8()) << QString(\"\\x03%1%2\\x0f\").arg(i).arg(color) << color;\n }\n}\n\nvoid tst_IrcTextFormat::testPlainText()\n{\n QFETCH(QString, input);\n QFETCH(QString, output);\n\n IrcTextFormat format;\n QCOMPARE(format.toPlainText(input), output);\n}\n\nvoid tst_IrcTextFormat::testHtml_data()\n{\n QTest::addColumn(\"input\");\n QTest::addColumn(\"output\");\n\n QTest::newRow(\"bold\") << \"\\02bold\\x0f\" << \"bold<\/span>\";\n QTest::newRow(\"strike-through\") << \"\\x13strike-through\\x0f\" << \"strike-through<\/span>\";\n QTest::newRow(\"underline\") << \"\\x15underline\\x0f\" << \"underline<\/span>\";\n \/\/TODO: QTest::newRow(\"inverse\") << \"\\x16inverse\\x0f\" << \"inverse\";\n QTest::newRow(\"italic\") << \"\\x1ditalic\\x0f\" << \"italic<\/span>\";\n QTest::newRow(\"underline\") << \"\\x1funderline\\x0f\" << \"underline<\/span>\";\n\n IrcTextFormat format;\n for (int i = Irc::White; i <= Irc::LightGray; ++i) {\n QString color = format.colorName(i);\n QTest::newRow(color.toUtf8()) << QString(\"\\x03%1%2\\x0f\").arg(i).arg(color) << QString(\"%1<\/span>\").arg(color);\n }\n}\n\nvoid tst_IrcTextFormat::testHtml()\n{\n QFETCH(QString, input);\n QFETCH(QString, output);\n\n IrcTextFormat format;\n QCOMPARE(format.toHtml(input), output);\n}\n\nvoid tst_IrcTextFormat::testUrls_data()\n{\n QTest::addColumn(\"input\");\n QTest::addColumn(\"output\");\n\n QTest::newRow(\"www.fi\") << \"www.fi\" << \"www.fi<\/a>\";\n QTest::newRow(\"ftp.funet.fi\") << \"ftp.funet.fi\" << \"ftp.funet.fi<\/a>\";\n QTest::newRow(\"jpnurmi@gmail.com\") << \"jpnurmi@gmail.com\" << \"jpnurmi@gmail.com<\/a>\";\n QTest::newRow(\"github commits\") << \"https:\/\/github.com\/communi\/libcommuni\/compare\/ebf3c8ea47dc...19d66ddcb122\" << \"https:\/\/github.com\/communi\/libcommuni\/compare\/ebf3c8ea47dc...19d66ddcb122<\/a>\";\n}\n\nvoid tst_IrcTextFormat::testUrls()\n{\n QFETCH(QString, input);\n QFETCH(QString, output);\n\n IrcTextFormat format;\n QCOMPARE(format.toHtml(input), output);\n}\n\n\nQTEST_MAIN(tst_IrcTextFormat)\n\n#include \"tst_irctextformat.moc\"\n<|endoftext|>"} {"text":"\/*\n * dis.cpp\n *\n * Created on: Sep 20, 2015\n * Author: anon\n *\/\n\n#include \"arm\/ARMDisassembler.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Disassembler;\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n cerr << \"Usage: .\/%s [thumb|arm] \" << endl;\n return -1;\n }\n\n string arg_mode { argv[1] };\n string arg_opcode { argv[2] };\n\n ARMMode mode = (arg_mode == \"thumb\") ? ARMMode_Thumb : ARMMode_ARM;\n uint32_t opcode = std::stoul(arg_opcode, nullptr, 16);\n\n ARMDisassembler dis;\n shared_ptr ins = dis.disassemble(opcode, mode);\n cout << \"Disassembled instruction: \" << (void *) opcode << \" -> \" << ins->toString() << endl;\n\n return 0;\n}\nMake sure we invert the thumb2 opcodes.\/*\n * dis.cpp\n *\n * Created on: Sep 20, 2015\n * Author: anon\n *\/\n\n#include \"arm\/ARMDisassembler.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Disassembler;\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n cerr << \"Usage: .\/%s [thumb|arm] \" << endl;\n return -1;\n }\n\n string arg_mode { argv[1] };\n string arg_opcode { argv[2] };\n\n uint32_t opcode = std::stoul(arg_opcode, nullptr, 16);\n\n ARMMode mode;\n if (arg_mode == \"thumb\") {\n mode = ARMMode_Thumb;\n cout << \"Using mode THUMB\" << endl;\n\n if (opcode > 0xffff) {\n opcode = (opcode >> 16) | ((opcode << 16) & 0xffffffff);\n }\n } else {\n mode = ARMMode_ARM;\n cout << \"Using mode THUMB\" << endl;\n }\n\n ARMDisassembler dis { ARMv7All };\n shared_ptr ins = dis.disassemble(opcode, mode);\n cout << \"Disassembled instruction: \" << (void *) opcode << \" -> \" << ins->toString() << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/cc\/saved_model\/loader.h\"\n\n#include \n\n#include \"tensorflow\/cc\/saved_model\/constants.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/monitoring\/counter.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/protobuf_internal.h\"\n#include \"tensorflow\/core\/protobuf\/saved_model.pb.h\"\n#include \"tensorflow\/core\/public\/session.h\"\n#include \"tensorflow\/core\/public\/session_options.h\"\n#include \"tensorflow\/core\/util\/tensor_bundle\/naming.h\"\n\nnamespace tensorflow {\nnamespace {\n\nauto* load_attempt_count = monitoring::Counter<2>::New(\n \"\/tensorflow\/cc\/saved_model\/load_attempt_count\", \"model_path\", \"status\",\n \"The number of times a SavedModel was successfully loaded.\");\nauto* load_latency = monitoring::Counter<1>::New(\n \"\/tensorflow\/cc\/saved_model\/load_latency\", \"model_path\",\n \"Latency in microseconds for SavedModels that were succesfully loaded.\");\nconstexpr char kLoadAttemptFail[] = \"fail\";\nconstexpr char kLoadAttemptSuccess[] = \"success\";\n\nStatus ReadSavedModel(const string& export_dir, SavedModel* saved_model_proto) {\n const string saved_model_pb_path =\n io::JoinPath(export_dir, kSavedModelFilenamePb);\n if (Env::Default()->FileExists(saved_model_pb_path).ok()) {\n return ReadBinaryProto(Env::Default(), saved_model_pb_path,\n saved_model_proto);\n }\n const string saved_model_pbtxt_path =\n io::JoinPath(export_dir, kSavedModelFilenamePbTxt);\n if (Env::Default()->FileExists(saved_model_pbtxt_path).ok()) {\n return ReadTextProto(Env::Default(), saved_model_pbtxt_path,\n saved_model_proto);\n }\n return Status(error::Code::NOT_FOUND,\n \"Could not find SavedModel .pb or .pbtxt at supplied export \"\n \"directory path: \" +\n export_dir);\n}\n\nStatus FindMetaGraphDefToLoad(const SavedModel& saved_model_proto,\n const std::unordered_set& tags,\n MetaGraphDef* meta_graph_def_to_load) {\n for (const MetaGraphDef& meta_graph_def : saved_model_proto.meta_graphs()) {\n \/\/ Get tags from the meta_graph_def.\n std::unordered_set graph_tags;\n for (const string& tag : meta_graph_def.meta_info_def().tags()) {\n graph_tags.insert(tag);\n }\n \/\/ Match with the set of tags provided.\n if (graph_tags == tags) {\n *meta_graph_def_to_load = meta_graph_def;\n return Status::OK();\n }\n }\n return Status(error::Code::NOT_FOUND,\n \"Could not find meta graph def matching supplied tags.\");\n}\n\nStatus LoadMetaGraphIntoSession(const MetaGraphDef& meta_graph_def,\n const SessionOptions& session_options,\n std::unique_ptr* session) {\n session->reset(NewSession(session_options));\n return (*session)->Create(meta_graph_def.graph_def());\n}\n\nTensor CreateStringTensor(const string& value) {\n Tensor tensor(DT_STRING, TensorShape({}));\n tensor.scalar()() = value;\n return tensor;\n}\n\nvoid AddAssetsTensorsToInputs(const StringPiece export_dir,\n const std::vector& asset_file_defs,\n std::vector>* inputs) {\n if (asset_file_defs.empty()) {\n return;\n }\n for (auto& asset_file_def : asset_file_defs) {\n Tensor assets_file_path_tensor = CreateStringTensor(io::JoinPath(\n export_dir, kSavedModelAssetsDirectory, asset_file_def.filename()));\n inputs->push_back(\n {asset_file_def.tensor_info().name(), assets_file_path_tensor});\n }\n}\n\nStatus RunRestore(const RunOptions& run_options, const string& export_dir,\n const StringPiece restore_op_name,\n const StringPiece variable_filename_const_op_name,\n const std::vector& asset_file_defs,\n Session* session) {\n LOG(INFO) << \"Restoring SavedModel bundle.\";\n \/\/ Find path to variables to be restored in export directory.\n const string variables_directory =\n io::JoinPath(export_dir, kSavedModelVariablesDirectory);\n \/\/ Check for saver checkpoints in v2 format. Models exported in the checkpoint\n \/\/ v2 format will have a variables.index file. The corresponding\n \/\/ variables are stored in the variables.data-?????-of-????? files.\n const string variables_index_path = io::JoinPath(\n variables_directory, MetaFilename(kSavedModelVariablesFilename));\n if (!Env::Default()->FileExists(variables_index_path).ok()) {\n return errors::NotFound(\n \"Checkpoint index file not found in SavedModel directory.\");\n }\n const string variables_path =\n io::JoinPath(variables_directory, kSavedModelVariablesFilename);\n\n \/\/ Add variables to the graph.\n Tensor variables_path_tensor(DT_STRING, TensorShape({}));\n variables_path_tensor.scalar()() = variables_path;\n\n std::vector> inputs = {\n {variable_filename_const_op_name.ToString(), variables_path_tensor}};\n\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n\n RunMetadata run_metadata;\n return session->Run(run_options, inputs, {}, {restore_op_name.ToString()},\n nullptr \/* outputs *\/, &run_metadata);\n}\n\nStatus RunLegacyInitOp(const RunOptions& run_options, const string& export_dir,\n const MetaGraphDef& meta_graph_def,\n const std::vector& asset_file_defs,\n Session* session) {\n LOG(INFO) << \"Running LegacyInitOp on SavedModel bundle.\";\n const auto& collection_def_map = meta_graph_def.collection_def();\n const auto init_op_it = collection_def_map.find(kSavedModelLegacyInitOpKey);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(strings::StrCat(\n \"Expected exactly one serving init op in : \", export_dir));\n }\n std::vector> inputs;\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n RunMetadata run_metadata;\n const StringPiece legacy_init_op_name =\n init_op_it->second.node_list().value(0);\n return session->Run(run_options, inputs, {},\n {legacy_init_op_name.ToString()}, nullptr \/* outputs *\/,\n &run_metadata);\n }\n return Status::OK();\n}\n\nStatus GetAssetFileDefs(const MetaGraphDef& meta_graph_def,\n std::vector* asset_file_defs) {\n const auto& collection_def_map = meta_graph_def.collection_def();\n const auto assets_it = collection_def_map.find(kSavedModelAssetsKey);\n if (assets_it == collection_def_map.end()) {\n return Status::OK();\n }\n const auto& any_assets = assets_it->second.any_list().value();\n for (const auto& any_asset : any_assets) {\n AssetFileDef asset_file_def;\n TF_RETURN_IF_ERROR(\n ParseAny(any_asset, &asset_file_def, \"tensorflow.AssetFileDef\"));\n asset_file_defs->push_back(asset_file_def);\n }\n return Status::OK();\n}\n\nStatus LoadSavedModelInternal(const SessionOptions& session_options,\n const RunOptions& run_options,\n const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n if (!MaybeSavedModelDirectory(export_dir)) {\n return Status(error::Code::NOT_FOUND,\n \"SavedModel not found in export directory: \" + export_dir);\n }\n LOG(INFO) << \"Loading SavedModel from: \" << export_dir;\n\n SavedModel saved_model_proto;\n TF_RETURN_IF_ERROR(ReadSavedModel(export_dir, &saved_model_proto));\n\n TF_RETURN_IF_ERROR(\n FindMetaGraphDefToLoad(saved_model_proto, tags, &bundle->meta_graph_def));\n\n TF_RETURN_IF_ERROR(LoadMetaGraphIntoSession(\n bundle->meta_graph_def, session_options, &bundle->session));\n\n std::vector asset_file_defs;\n TF_RETURN_IF_ERROR(\n GetAssetFileDefs(bundle->meta_graph_def, &asset_file_defs));\n TF_RETURN_IF_ERROR(\n RunRestore(run_options, export_dir,\n bundle->meta_graph_def.saver_def().restore_op_name(),\n bundle->meta_graph_def.saver_def().filename_tensor_name(),\n asset_file_defs, bundle->session.get()));\n \/\/ TODO(sukritiramesh): Add support for a single main op to run upon load,\n \/\/ which will supersede the legacy_init_op and separate RunRestore.\n TF_RETURN_IF_ERROR(RunLegacyInitOp(run_options, export_dir,\n bundle->meta_graph_def, asset_file_defs,\n bundle->session.get()));\n return Status::OK();\n}\n\n} \/\/ namespace\n\nStatus LoadSavedModel(const SessionOptions& session_options,\n const RunOptions& run_options, const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n \/\/ TODO(robson): Add tests for the counters.\n const uint64 start_microseconds = Env::Default()->NowMicros();\n const Status status = LoadSavedModelInternal(session_options, run_options,\n export_dir, tags, bundle);\n const uint64 load_latency_microsecs = [&]() -> uint64 {\n const uint64 end_microseconds = Env::Default()->NowMicros();\n \/\/ Avoid clock skew.\n if (end_microseconds < start_microseconds) return 0;\n return end_microseconds - start_microseconds;\n }();\n auto log_and_count = [&](const string& status_str) {\n LOG(INFO) << \"Loading SavedModel: \" << status_str << \". Took \"\n << load_latency_microsecs << \" microseconds.\";\n load_attempt_count->GetCell(export_dir, status_str)->IncrementBy(1);\n };\n if (status.ok()) {\n log_and_count(kLoadAttemptSuccess);\n } else {\n log_and_count(kLoadAttemptFail);\n }\n load_latency->GetCell(export_dir)->IncrementBy(load_latency_microsecs);\n return status;\n}\n\nbool MaybeSavedModelDirectory(const string& export_dir) {\n const string saved_model_pb_path =\n io::JoinPath(export_dir, kSavedModelFilenamePb);\n const string saved_model_pbtxt_path =\n io::JoinPath(export_dir, kSavedModelFilenamePbTxt);\n return Env::Default()->FileExists(saved_model_pb_path).ok() ||\n Env::Default()->FileExists(saved_model_pbtxt_path).ok();\n}\n\n} \/\/ namespace tensorflow\nFix metric definitions in SavedModel. Change: 140854331\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/cc\/saved_model\/loader.h\"\n\n#include \n\n#include \"tensorflow\/cc\/saved_model\/constants.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/monitoring\/counter.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/protobuf_internal.h\"\n#include \"tensorflow\/core\/protobuf\/saved_model.pb.h\"\n#include \"tensorflow\/core\/public\/session.h\"\n#include \"tensorflow\/core\/public\/session_options.h\"\n#include \"tensorflow\/core\/util\/tensor_bundle\/naming.h\"\n\nnamespace tensorflow {\nnamespace {\n\nauto* load_attempt_count = monitoring::Counter<2>::New(\n \"\/tensorflow\/cc\/saved_model\/load_attempt_count\",\n \"The number of times a SavedModel was successfully loaded.\", \"model_path\",\n \"status\");\nauto* load_latency = monitoring::Counter<1>::New(\n \"\/tensorflow\/cc\/saved_model\/load_latency\",\n \"Latency in microseconds for SavedModels that were succesfully loaded.\",\n \"model_path\");\nconstexpr char kLoadAttemptFail[] = \"fail\";\nconstexpr char kLoadAttemptSuccess[] = \"success\";\n\nStatus ReadSavedModel(const string& export_dir, SavedModel* saved_model_proto) {\n const string saved_model_pb_path =\n io::JoinPath(export_dir, kSavedModelFilenamePb);\n if (Env::Default()->FileExists(saved_model_pb_path).ok()) {\n return ReadBinaryProto(Env::Default(), saved_model_pb_path,\n saved_model_proto);\n }\n const string saved_model_pbtxt_path =\n io::JoinPath(export_dir, kSavedModelFilenamePbTxt);\n if (Env::Default()->FileExists(saved_model_pbtxt_path).ok()) {\n return ReadTextProto(Env::Default(), saved_model_pbtxt_path,\n saved_model_proto);\n }\n return Status(error::Code::NOT_FOUND,\n \"Could not find SavedModel .pb or .pbtxt at supplied export \"\n \"directory path: \" +\n export_dir);\n}\n\nStatus FindMetaGraphDefToLoad(const SavedModel& saved_model_proto,\n const std::unordered_set& tags,\n MetaGraphDef* meta_graph_def_to_load) {\n for (const MetaGraphDef& meta_graph_def : saved_model_proto.meta_graphs()) {\n \/\/ Get tags from the meta_graph_def.\n std::unordered_set graph_tags;\n for (const string& tag : meta_graph_def.meta_info_def().tags()) {\n graph_tags.insert(tag);\n }\n \/\/ Match with the set of tags provided.\n if (graph_tags == tags) {\n *meta_graph_def_to_load = meta_graph_def;\n return Status::OK();\n }\n }\n return Status(error::Code::NOT_FOUND,\n \"Could not find meta graph def matching supplied tags.\");\n}\n\nStatus LoadMetaGraphIntoSession(const MetaGraphDef& meta_graph_def,\n const SessionOptions& session_options,\n std::unique_ptr* session) {\n session->reset(NewSession(session_options));\n return (*session)->Create(meta_graph_def.graph_def());\n}\n\nTensor CreateStringTensor(const string& value) {\n Tensor tensor(DT_STRING, TensorShape({}));\n tensor.scalar()() = value;\n return tensor;\n}\n\nvoid AddAssetsTensorsToInputs(const StringPiece export_dir,\n const std::vector& asset_file_defs,\n std::vector>* inputs) {\n if (asset_file_defs.empty()) {\n return;\n }\n for (auto& asset_file_def : asset_file_defs) {\n Tensor assets_file_path_tensor = CreateStringTensor(io::JoinPath(\n export_dir, kSavedModelAssetsDirectory, asset_file_def.filename()));\n inputs->push_back(\n {asset_file_def.tensor_info().name(), assets_file_path_tensor});\n }\n}\n\nStatus RunRestore(const RunOptions& run_options, const string& export_dir,\n const StringPiece restore_op_name,\n const StringPiece variable_filename_const_op_name,\n const std::vector& asset_file_defs,\n Session* session) {\n LOG(INFO) << \"Restoring SavedModel bundle.\";\n \/\/ Find path to variables to be restored in export directory.\n const string variables_directory =\n io::JoinPath(export_dir, kSavedModelVariablesDirectory);\n \/\/ Check for saver checkpoints in v2 format. Models exported in the checkpoint\n \/\/ v2 format will have a variables.index file. The corresponding\n \/\/ variables are stored in the variables.data-?????-of-????? files.\n const string variables_index_path = io::JoinPath(\n variables_directory, MetaFilename(kSavedModelVariablesFilename));\n if (!Env::Default()->FileExists(variables_index_path).ok()) {\n return errors::NotFound(\n \"Checkpoint index file not found in SavedModel directory.\");\n }\n const string variables_path =\n io::JoinPath(variables_directory, kSavedModelVariablesFilename);\n\n \/\/ Add variables to the graph.\n Tensor variables_path_tensor(DT_STRING, TensorShape({}));\n variables_path_tensor.scalar()() = variables_path;\n\n std::vector> inputs = {\n {variable_filename_const_op_name.ToString(), variables_path_tensor}};\n\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n\n RunMetadata run_metadata;\n return session->Run(run_options, inputs, {}, {restore_op_name.ToString()},\n nullptr \/* outputs *\/, &run_metadata);\n}\n\nStatus RunLegacyInitOp(const RunOptions& run_options, const string& export_dir,\n const MetaGraphDef& meta_graph_def,\n const std::vector& asset_file_defs,\n Session* session) {\n LOG(INFO) << \"Running LegacyInitOp on SavedModel bundle.\";\n const auto& collection_def_map = meta_graph_def.collection_def();\n const auto init_op_it = collection_def_map.find(kSavedModelLegacyInitOpKey);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(strings::StrCat(\n \"Expected exactly one serving init op in : \", export_dir));\n }\n std::vector> inputs;\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n RunMetadata run_metadata;\n const StringPiece legacy_init_op_name =\n init_op_it->second.node_list().value(0);\n return session->Run(run_options, inputs, {},\n {legacy_init_op_name.ToString()}, nullptr \/* outputs *\/,\n &run_metadata);\n }\n return Status::OK();\n}\n\nStatus GetAssetFileDefs(const MetaGraphDef& meta_graph_def,\n std::vector* asset_file_defs) {\n const auto& collection_def_map = meta_graph_def.collection_def();\n const auto assets_it = collection_def_map.find(kSavedModelAssetsKey);\n if (assets_it == collection_def_map.end()) {\n return Status::OK();\n }\n const auto& any_assets = assets_it->second.any_list().value();\n for (const auto& any_asset : any_assets) {\n AssetFileDef asset_file_def;\n TF_RETURN_IF_ERROR(\n ParseAny(any_asset, &asset_file_def, \"tensorflow.AssetFileDef\"));\n asset_file_defs->push_back(asset_file_def);\n }\n return Status::OK();\n}\n\nStatus LoadSavedModelInternal(const SessionOptions& session_options,\n const RunOptions& run_options,\n const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n if (!MaybeSavedModelDirectory(export_dir)) {\n return Status(error::Code::NOT_FOUND,\n \"SavedModel not found in export directory: \" + export_dir);\n }\n LOG(INFO) << \"Loading SavedModel from: \" << export_dir;\n\n SavedModel saved_model_proto;\n TF_RETURN_IF_ERROR(ReadSavedModel(export_dir, &saved_model_proto));\n\n TF_RETURN_IF_ERROR(\n FindMetaGraphDefToLoad(saved_model_proto, tags, &bundle->meta_graph_def));\n\n TF_RETURN_IF_ERROR(LoadMetaGraphIntoSession(\n bundle->meta_graph_def, session_options, &bundle->session));\n\n std::vector asset_file_defs;\n TF_RETURN_IF_ERROR(\n GetAssetFileDefs(bundle->meta_graph_def, &asset_file_defs));\n TF_RETURN_IF_ERROR(\n RunRestore(run_options, export_dir,\n bundle->meta_graph_def.saver_def().restore_op_name(),\n bundle->meta_graph_def.saver_def().filename_tensor_name(),\n asset_file_defs, bundle->session.get()));\n \/\/ TODO(sukritiramesh): Add support for a single main op to run upon load,\n \/\/ which will supersede the legacy_init_op and separate RunRestore.\n TF_RETURN_IF_ERROR(RunLegacyInitOp(run_options, export_dir,\n bundle->meta_graph_def, asset_file_defs,\n bundle->session.get()));\n return Status::OK();\n}\n\n} \/\/ namespace\n\nStatus LoadSavedModel(const SessionOptions& session_options,\n const RunOptions& run_options, const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n \/\/ TODO(robson): Add tests for the counters.\n const uint64 start_microseconds = Env::Default()->NowMicros();\n const Status status = LoadSavedModelInternal(session_options, run_options,\n export_dir, tags, bundle);\n const uint64 load_latency_microsecs = [&]() -> uint64 {\n const uint64 end_microseconds = Env::Default()->NowMicros();\n \/\/ Avoid clock skew.\n if (end_microseconds < start_microseconds) return 0;\n return end_microseconds - start_microseconds;\n }();\n auto log_and_count = [&](const string& status_str) {\n LOG(INFO) << \"Loading SavedModel: \" << status_str << \". Took \"\n << load_latency_microsecs << \" microseconds.\";\n load_attempt_count->GetCell(export_dir, status_str)->IncrementBy(1);\n };\n if (status.ok()) {\n log_and_count(kLoadAttemptSuccess);\n } else {\n log_and_count(kLoadAttemptFail);\n }\n load_latency->GetCell(export_dir)->IncrementBy(load_latency_microsecs);\n return status;\n}\n\nbool MaybeSavedModelDirectory(const string& export_dir) {\n const string saved_model_pb_path =\n io::JoinPath(export_dir, kSavedModelFilenamePb);\n const string saved_model_pbtxt_path =\n io::JoinPath(export_dir, kSavedModelFilenamePbTxt);\n return Env::Default()->FileExists(saved_model_pb_path).ok() ||\n Env::Default()->FileExists(saved_model_pbtxt_path).ok();\n}\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \n\n\nnamespace DoremiEngine\n{\n namespace Physics\n {\n PhysicsModuleImplementation::PhysicsModuleImplementation(const Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext) {}\n PhysicsModuleImplementation::~PhysicsModuleImplementation() {}\n\n void PhysicsModuleImplementation::Startup()\n {\n \/\/ Start physX\n m_utils.m_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, m_utils.m_allocator, m_utils.m_errorCallback);\n PxProfileZoneManager* profileZoneManager = &PxProfileZoneManager::createProfileZoneManager(m_utils.m_foundation);\n m_utils.m_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *m_utils.m_foundation, PxTolerancesScale(), true, profileZoneManager);\n\n \/\/ Create world scene TODOJB create scene handler for this kind of job\n CreateWorldScene();\n\n \/\/ Create sub modules\n m_utils.m_rigidBodyManager = new RigidBodyManagerImpl(m_utils);\n m_utils.m_physicsMaterialManager = new PhysicsMaterialManagerImpl(m_utils);\n m_utils.m_characterControlManager = new CharacterControlManagerImpl(m_utils);\n m_utils.m_fluidManager = new FluidManagerImpl(m_utils);\n m_utils.m_rayCastManager = new RayCastManagerImpl(m_utils);\n\n \/\/ Make some other important thingies\n m_utils.m_characterControlManager->SetCallbackClass(this);\n\n if(m_utils.m_physics->getPvdConnectionManager() == NULL)\n {\n int failed = 1;\n }\n PxVisualDebuggerConnection* theConnection =\n PxVisualDebuggerExt::createConnection(m_utils.m_physics->getPvdConnectionManager(), \"127.0.0.1\", 5425, 100,\n PxVisualDebuggerExt::getAllConnectionFlags());\n if(theConnection) theConnection->release();\n }\n\n void PhysicsModuleImplementation::Shutdown() {}\n\n void PhysicsModuleImplementation::Update(float p_dt)\n {\n \/\/ Start by clearing the list of collision pairs (WARNING potentially bad idea)\n m_collisionPairs.clear();\n m_triggerPairs.clear();\n m_utils.m_fluidManager->Update(p_dt);\n m_utils.m_worldScene->simulate(p_dt);\n m_utils.m_worldScene->fetchResults(true);\n }\n\n RigidBodyManager& PhysicsModuleImplementation::GetRigidBodyManager() { return *m_utils.m_rigidBodyManager; }\n PhysicsMaterialManager& PhysicsModuleImplementation::GetPhysicsMaterialManager() { return *m_utils.m_physicsMaterialManager; }\n CharacterControlManager& PhysicsModuleImplementation::GetCharacterControlManager() { return *m_utils.m_characterControlManager; }\n FluidManager& PhysicsModuleImplementation::GetFluidManager() { return *m_utils.m_fluidManager; }\n RayCastManager& PhysicsModuleImplementation::GetRayCastManager() { return *m_utils.m_rayCastManager; };\n\n vector PhysicsModuleImplementation::GetCollisionPairs() { return m_collisionPairs; }\n vector PhysicsModuleImplementation::GetTriggerPairs() { return m_triggerPairs; }\n\n \/\/ Custom collision filter shader\n PxFilterFlags TestFilter(PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1,\n PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)\n {\n \/\/ Rigid bodies collisions\n if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))\n {\n pairFlags = PxPairFlag::eTRIGGER_DEFAULT;\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_PERSISTS;\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_LOST;\n return PxFilterFlag::eDEFAULT;\n }\n\n \/\/ controller vs. controller collisions\n bool kinematic0 = PxFilterObjectIsKinematic(attributes0);\n bool kinematic1 = PxFilterObjectIsKinematic(attributes1);\n\n if(kinematic0 && kinematic1)\n {\n pairFlags = PxPairFlag::eTRIGGER_DEFAULT;\n return PxFilterFlag::eDEFAULT;\n }\n\n \/\/ generate contacts for all that were not filtered above\n pairFlags = PxPairFlag::eCONTACT_DEFAULT;\n\n \/\/ trigger the contact callback for pairs (A,B) where\n \/\/ the filtermask of A contains the ID of B and vice versa.\n if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1))\n {\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;\n }\n\n return PxFilterFlag::eDEFAULT;\n }\n\n void PhysicsModuleImplementation::CreateWorldScene()\n {\n \/\/\/ Create the scene\n \/\/ No idea what the \"tolerances\" is\n PxSceneDesc sceneDesc(m_utils.m_physics->getTolerancesScale());\n \/\/ Gravity sounds straight forward\n sceneDesc.gravity = PxVec3(0.0f, -9.8f, 0.0f);\n \/\/ Not too sure what this is. Probably related to how threads work\n m_utils.m_dispatcher = PxDefaultCpuDispatcherCreate(2);\n sceneDesc.cpuDispatcher = m_utils.m_dispatcher;\n \/\/ Some way of filtering collisions. Use default shaders since we cba to write our own\n sceneDesc.filterShader = TestFilter;\n \/\/ Notify PhysX that we want callbacks to be called here\n sceneDesc.simulationEventCallback = this;\n\n \/\/ Create the scene\n m_utils.m_worldScene = m_utils.m_physics->createScene(sceneDesc);\n\n \/\/ Assign stuff to the global material (again, probably stupid to have this here)\n PxMaterial* groundMaterial = m_utils.m_physics->createMaterial(0.5, 0.5, 0.5);\n\n \/\/ Create the ground on which everything stands on. Possibly shouldn't here (member varialbe? Separate class?)\n PxPlane groundPlane = PxPlane(0, 1, 0, 10); \/\/ change last digit for distance from origo\n\n PxRigidStatic* worldGround = PxCreatePlane(*m_utils.m_physics, groundPlane, *groundMaterial);\n \/\/ Add the ground plane to the scene. Apparently it's this easy\n m_utils.m_worldScene->addActor(*worldGround);\n \/\/ Not sure what this does... Desperate try maybe?\n m_utils.m_worldScene->setFlag(PxSceneFlag::eENABLE_KINEMATIC_PAIRS, true);\n\n \/\/ m_utils.m_worldScene->setFlag(PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS, true);\n\n \/*\n And we now have a simple scene with gravity and the ground as a plane*\/\n }\n\n void PhysicsModuleImplementation::onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs)\n {\n m_utils.m_rigidBodyManager->GetIDsByBodies();\n for(size_t i = 0; i < nbPairs; i++)\n {\n const PxContactPair& cp = pairs[i];\n CollisionPair collisionPair;\n \/\/ collisionPair.firstID = m_utils.m_rigidBodyManager->GetIDsByBodies()[pairHeader.actors[0]];\n \/\/ collisionPair.secondID = m_utils.m_rigidBodyManager->GetIDsByBodies()[pairHeader.actors[1]];\n collisionPair.firstID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairHeader.actors[0])->second;\n collisionPair.secondID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairHeader.actors[1])->second;\n m_collisionPairs.push_back(collisionPair);\n }\n }\n\n\n void PhysicsModuleImplementation::onTrigger(PxTriggerPair* pairs, PxU32 count)\n {\n for(size_t i = 0; i < count; i++)\n {\n const PxTriggerPair& cp = pairs[i];\n CollisionPair collisionPair;\n collisionPair.firstID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairs->triggerActor)->second;\n collisionPair.secondID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairs->otherActor)->second;\n m_triggerPairs.push_back(collisionPair);\n }\n }\n\n void PhysicsModuleImplementation::onShapeHit(const PxControllerShapeHit& hit)\n {\n \/\/ TODOJB implement\n }\n PxUserControllerHitReport* derp;\n\n void PhysicsModuleImplementation::onControllerHit(const PxControllersHit& hit)\n {\n CollisionPair collisionPair;\n unordered_map idsByControllers = m_utils.m_characterControlManager->GetIdsByControllers();\n PxController* firstActor = hit.controller;\n PxController* secondActor = hit.other;\n int first = idsByControllers[firstActor];\n int second = idsByControllers[secondActor];\n\n collisionPair.firstID = m_utils.m_characterControlManager->GetIdsByControllers().find(hit.controller)->second;\n collisionPair.secondID = m_utils.m_characterControlManager->GetIdsByControllers().find(hit.other)->second;\n m_collisionPairs.push_back(collisionPair);\n }\n }\n}\n\nDoremiEngine::Physics::PhysicsModule* CreatePhysicsModule(const DoremiEngine::Core::SharedContext& p_sharedContext)\n{\n DoremiEngine::Physics::PhysicsModule* physics = new DoremiEngine::Physics::PhysicsModuleImplementation(p_sharedContext);\n return physics;\n}Fix in physics#include \n\n\nnamespace DoremiEngine\n{\n namespace Physics\n {\n PhysicsModuleImplementation::PhysicsModuleImplementation(const Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext) {}\n PhysicsModuleImplementation::~PhysicsModuleImplementation() {}\n\n void PhysicsModuleImplementation::Startup()\n {\n \/\/ Start physX\n m_utils.m_foundation = PxCreateFoundation(PX_PHYSICS_VERSION, m_utils.m_allocator, m_utils.m_errorCallback);\n PxProfileZoneManager* profileZoneManager = &PxProfileZoneManager::createProfileZoneManager(m_utils.m_foundation);\n m_utils.m_physics = PxCreatePhysics(PX_PHYSICS_VERSION, *m_utils.m_foundation, PxTolerancesScale(), true, profileZoneManager);\n\n \/\/ Create world scene TODOJB create scene handler for this kind of job\n CreateWorldScene();\n\n \/\/ Create sub modules\n m_utils.m_rigidBodyManager = new RigidBodyManagerImpl(m_utils);\n m_utils.m_physicsMaterialManager = new PhysicsMaterialManagerImpl(m_utils);\n m_utils.m_characterControlManager = new CharacterControlManagerImpl(m_utils);\n m_utils.m_fluidManager = new FluidManagerImpl(m_utils);\n m_utils.m_rayCastManager = new RayCastManagerImpl(m_utils);\n\n \/\/ Make some other important thingies\n m_utils.m_characterControlManager->SetCallbackClass(this);\n\n if(m_utils.m_physics->getPvdConnectionManager() == NULL)\n {\n int failed = 1;\n }\n PxVisualDebuggerConnection* theConnection =\n PxVisualDebuggerExt::createConnection(m_utils.m_physics->getPvdConnectionManager(), \"127.0.0.1\", 5425, 100,\n PxVisualDebuggerExt::getAllConnectionFlags());\n if(theConnection) theConnection->release();\n }\n\n void PhysicsModuleImplementation::Shutdown() {}\n\n void PhysicsModuleImplementation::Update(float p_dt)\n {\n \/\/ Start by clearing the list of collision pairs (WARNING potentially bad idea)\n m_collisionPairs.clear();\n m_triggerPairs.clear();\n m_utils.m_fluidManager->Update(p_dt);\n m_utils.m_worldScene->simulate(p_dt);\n m_utils.m_worldScene->fetchResults(true);\n }\n\n RigidBodyManager& PhysicsModuleImplementation::GetRigidBodyManager() { return *m_utils.m_rigidBodyManager; }\n PhysicsMaterialManager& PhysicsModuleImplementation::GetPhysicsMaterialManager() { return *m_utils.m_physicsMaterialManager; }\n CharacterControlManager& PhysicsModuleImplementation::GetCharacterControlManager() { return *m_utils.m_characterControlManager; }\n FluidManager& PhysicsModuleImplementation::GetFluidManager() { return *m_utils.m_fluidManager; }\n RayCastManager& PhysicsModuleImplementation::GetRayCastManager() { return *m_utils.m_rayCastManager; };\n\n vector PhysicsModuleImplementation::GetCollisionPairs() { return m_collisionPairs; }\n vector PhysicsModuleImplementation::GetTriggerPairs() { return m_triggerPairs; }\n\n \/\/ Custom collision filter shader\n PxFilterFlags TestFilter(PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1,\n PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)\n {\n \/\/ Rigid bodies collisions\n if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1))\n {\n pairFlags = PxPairFlag::eTRIGGER_DEFAULT;\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_PERSISTS;\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_LOST;\n return PxFilterFlag::eDEFAULT;\n }\n\n \/\/ controller vs. controller collisions\n bool kinematic0 = PxFilterObjectIsKinematic(attributes0);\n bool kinematic1 = PxFilterObjectIsKinematic(attributes1);\n\n if(kinematic0 && kinematic1)\n {\n pairFlags = PxPairFlag::eTRIGGER_DEFAULT;\n return PxFilterFlag::eDEFAULT;\n }\n\n \/\/ generate contacts for all that were not filtered above\n pairFlags = PxPairFlag::eCONTACT_DEFAULT;\n\n \/\/ trigger the contact callback for pairs (A,B) where\n \/\/ the filtermask of A contains the ID of B and vice versa.\n if((filterData0.word0 & filterData1.word1) && (filterData1.word0 & filterData0.word1))\n {\n pairFlags |= PxPairFlag::eNOTIFY_TOUCH_FOUND;\n }\n\n return PxFilterFlag::eDEFAULT;\n }\n\n void PhysicsModuleImplementation::CreateWorldScene()\n {\n \/\/\/ Create the scene\n \/\/ No idea what the \"tolerances\" is\n PxSceneDesc sceneDesc(m_utils.m_physics->getTolerancesScale());\n \/\/ Gravity sounds straight forward\n sceneDesc.gravity = PxVec3(0.0f, -9.8f, 0.0f);\n \/\/ Not too sure what this is. Probably related to how threads work\n m_utils.m_dispatcher = PxDefaultCpuDispatcherCreate(2);\n sceneDesc.cpuDispatcher = m_utils.m_dispatcher;\n \/\/ Some way of filtering collisions. Use default shaders since we cba to write our own\n sceneDesc.filterShader = TestFilter;\n \/\/ Notify PhysX that we want callbacks to be called here\n sceneDesc.simulationEventCallback = this;\n\n \/\/ Create the scene\n m_utils.m_worldScene = m_utils.m_physics->createScene(sceneDesc);\n\n \/\/ Assign stuff to the global material (again, probably stupid to have this here)\n PxMaterial* groundMaterial = m_utils.m_physics->createMaterial(0.5, 0.5, 0.5);\n\n \/\/ Create the ground on which everything stands on. Possibly shouldn't here (member varialbe? Separate class?)\n PxPlane groundPlane = PxPlane(0, 1, 0, 10); \/\/ change last digit for distance from origo\n\n PxRigidStatic* worldGround = PxCreatePlane(*m_utils.m_physics, groundPlane, *groundMaterial);\n \/\/ Add the ground plane to the scene. Apparently it's this easy\n m_utils.m_worldScene->addActor(*worldGround);\n \/\/ Not sure what this does... Desperate try maybe?\n m_utils.m_worldScene->setFlag(PxSceneFlag::eENABLE_KINEMATIC_PAIRS, true);\n\n \/\/ m_utils.m_worldScene->setFlag(PxSceneFlag::eENABLE_KINEMATIC_STATIC_PAIRS, true);\n\n \/*\n And we now have a simple scene with gravity and the ground as a plane*\/\n }\n\n void PhysicsModuleImplementation::onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs)\n {\n m_utils.m_rigidBodyManager->GetIDsByBodies();\n for(size_t i = 0; i < nbPairs; i++)\n {\n const PxContactPair& cp = pairs[i];\n CollisionPair collisionPair;\n\n if(m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairHeader.actors[0]) != m_utils.m_rigidBodyManager->GetIDsByBodies().end())\n {\n collisionPair.firstID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairHeader.actors[0])->second;\n }\n else\n {\n \/\/ Probably hit a controller. TODOJB solve some time\n }\n\n if (m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairHeader.actors[1]) != m_utils.m_rigidBodyManager->GetIDsByBodies().end())\n {\n collisionPair.secondID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairHeader.actors[1])->second;\n }\n else\n {\n \/\/ Probably hit a controller. TODOJB solve some time\n }\n\n\n\n m_collisionPairs.push_back(collisionPair);\n }\n }\n\n\n void PhysicsModuleImplementation::onTrigger(PxTriggerPair* pairs, PxU32 count)\n {\n for(size_t i = 0; i < count; i++)\n {\n const PxTriggerPair& cp = pairs[i];\n CollisionPair collisionPair;\n collisionPair.firstID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairs->triggerActor)->second;\n collisionPair.secondID = m_utils.m_rigidBodyManager->GetIDsByBodies().find(pairs->otherActor)->second;\n m_triggerPairs.push_back(collisionPair);\n }\n }\n\n void PhysicsModuleImplementation::onShapeHit(const PxControllerShapeHit& hit)\n {\n \/\/ TODOJB implement\n }\n PxUserControllerHitReport* derp;\n\n void PhysicsModuleImplementation::onControllerHit(const PxControllersHit& hit)\n {\n CollisionPair collisionPair;\n unordered_map idsByControllers = m_utils.m_characterControlManager->GetIdsByControllers();\n PxController* firstActor = hit.controller;\n PxController* secondActor = hit.other;\n int first = idsByControllers[firstActor];\n int second = idsByControllers[secondActor];\n\n collisionPair.firstID = m_utils.m_characterControlManager->GetIdsByControllers().find(hit.controller)->second;\n collisionPair.secondID = m_utils.m_characterControlManager->GetIdsByControllers().find(hit.other)->second;\n m_collisionPairs.push_back(collisionPair);\n }\n }\n}\n\nDoremiEngine::Physics::PhysicsModule* CreatePhysicsModule(const DoremiEngine::Core::SharedContext& p_sharedContext)\n{\n DoremiEngine::Physics::PhysicsModule* physics = new DoremiEngine::Physics::PhysicsModuleImplementation(p_sharedContext);\n return physics;\n}<|endoftext|>"} {"text":"\/*\n Copyright (C) 2010 Marco Ballesio \n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see .\n *\/\n\n#include \"player.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* This is a simple example of a command-line player. It accepts the URI of\n * a media file as the first command line argument and then constructs a pipeline\n * that uses playbin2 to decode the stream. *\/\n\nPlayer::Player(QWidget *parent) \n : QGst::Ui::VideoWidget(parent) {\n connect(&m_positionTimer, SIGNAL(timeout()), this, SLOT(updatePosition()));\n setMouseTracking(true);\n }\n\nvoid Player::setUri(const QString & uri) {\n QString realUri = uri;\n\n if(uri.indexOf(\":\/\/\") < 0){\n if(realUri[0] != '\/'){\n realUri = QDir::current().path() + \"\/\" + realUri;\n }\n realUri = \"file:\/\/\" + realUri;\n }\n\n if(!m_pipeline){\n QGst::ElementPtr playbin = QGst::ElementFactory::make(\"playbin2\");\n if(playbin) {\n m_pipeline = playbin.dynamicCast();\n QGst::BusPtr bus = m_pipeline->bus();\n QGlib::Signal::connect(bus, \"message\", this, &Player::busMessage);\n bus->addSignalWatch();\n }\n }\n\n if(m_pipeline){\n m_pipeline->setProperty(\"uri\", realUri);\n }\n}\n\nPlayer::~Player() {\n if(m_pipeline)\n m_pipeline->setState(QGst::StateNull);\n}\n\nvoid Player::updatePosition() {\n Q_EMIT positionChanged(position());\n}\n\nvoid Player::play() {\n if(m_pipeline){\n m_pipeline->setState(QGst::StatePlaying);\n }\n}\n\nvoid Player::pause( ){\n if(m_pipeline){\n m_pipeline->setState(QGst::StatePaused);\n }\n}\n\nvoid Player::stop() {\n if(m_pipeline){\n m_pipeline->setState(QGst::StateReady);\n }\n}\n\nvoid Player::setPosition(QTime pos) {\n QGst::SeekEventPtr evt = QGst::SeekEvent::create(\n 1.0, QGst::FormatTime, QGst::SeekFlagFlush,\n QGst::SeekTypeSet, QGst::Clock::clockTimeFromTime(pos),\n QGst::SeekTypeNone, -1);\n\n m_pipeline.dynamicCast()->sendEvent(evt);\n}\n\nQTime Player::position() {\n if(m_pipeline){\n QGst::PositionQueryPtr query = QGst::PositionQuery::create(QGst::FormatTime);\n m_pipeline.dynamicCast()->query(query);\n return QGst::Clock::timeFromClockTime(query->position());\n }\n return QTime(0, 0, 0, 0);\n}\n\nQTime Player::length() {\n if(m_pipeline){\n QGst::DurationQueryPtr query = QGst::DurationQuery::create(QGst::FormatTime);\n m_pipeline->query(query);\n return QGst::Clock::timeFromClockTime(query->duration());\n }\n return QTime(0, 0, 0, 0);\n}\n\nQGst::State Player::state() {\n QGst::State state;\n if(!m_pipeline || \n m_pipeline.dynamicCast()->getState(&state, NULL, 1e9) != \n QGst::StateChangeSuccess)\n {\n state = QGst::StateNull;\n }\n return state;\n}\n\nvoid Player::handleStateChange(QGst::StateChangedMessagePtr scm) {\n switch(scm->newState()){\n case QGst::StatePlaying:\n Q_EMIT positionChanged(position());\n m_positionTimer.start(500);\n break;\n case QGst::StatePaused:\n if(scm->oldState() == QGst::StateReady){\n QGst::ElementPtr sink = \n m_pipeline->property(\"video-sink\").get();\n if(sink){\n setVideoSink(sink);\n QGst::ChildProxyPtr proxy = sink.dynamicCast();\n proxy->childByIndex(0)->setProperty(\"force-aspect-ratio\", true);\n }\n } else\n m_positionTimer.stop();\n break;\n case QGst::StateReady:\n if(scm->oldState() == QGst::StatePaused)\n \/* Remove the sink now to avoid inter-thread issues with Qt\n for the next time the pipeline goes to StatePlaying *\/\n setVideoSink(QGst::ElementPtr());\n break;\n default:\n break;\n }\n}\n\nvoid Player::busMessage(const QGst::MessagePtr & message) {\n switch(message->type()) {\n case QGst::MessageEos: \/\/End of stream. We reached the end of the file.\n qDebug() << \"got eos\";\n m_pipeline->setState(QGst::StateReady);\n break;\n case QGst::MessageError: \/\/Some error occurred.\n \/*TODO: send a message to UI *\/\n break;\n case QGst::MessageAsyncDone:\n {\n \/\/File prerolled, queries the pipeline to get the file duration\n QGst::DurationQueryPtr query = QGst::DurationQuery::create(QGst::FormatTime);\n \/\/This will create a temporary (cast to query).\n m_pipeline->query(query);\n }\n break;\n case QGst::MessageStateChanged:\n if(QGlib::Type::fromInstance(message->source()).\n isA(QGlib::GetType())) \n {\n QGst::StateChangedMessagePtr scm = \n message.dynamicCast();\n handleStateChange(scm);\n Q_EMIT stateChanged(scm->newState());\n }\n\n break;\n default:\n break;\n }\n}\n\nRemoved unneeded dynamic casts\/*\n Copyright (C) 2010 Marco Ballesio \n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see .\n *\/\n\n#include \"player.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* This is a simple example of a command-line player. It accepts the URI of\n * a media file as the first command line argument and then constructs a pipeline\n * that uses playbin2 to decode the stream. *\/\n\nPlayer::Player(QWidget *parent) \n : QGst::Ui::VideoWidget(parent) {\n connect(&m_positionTimer, SIGNAL(timeout()), this, SLOT(updatePosition()));\n setMouseTracking(true);\n }\n\nvoid Player::setUri(const QString & uri) {\n QString realUri = uri;\n\n if(uri.indexOf(\":\/\/\") < 0){\n if(realUri[0] != '\/'){\n realUri = QDir::current().path() + \"\/\" + realUri;\n }\n realUri = \"file:\/\/\" + realUri;\n }\n\n if(!m_pipeline){\n QGst::ElementPtr playbin = QGst::ElementFactory::make(\"playbin2\");\n if(playbin) {\n m_pipeline = playbin.dynamicCast();\n QGst::BusPtr bus = m_pipeline->bus();\n QGlib::Signal::connect(bus, \"message\", this, &Player::busMessage);\n bus->addSignalWatch();\n }\n }\n\n if(m_pipeline){\n m_pipeline->setProperty(\"uri\", realUri);\n }\n}\n\nPlayer::~Player() {\n if(m_pipeline)\n m_pipeline->setState(QGst::StateNull);\n}\n\nvoid Player::updatePosition() {\n Q_EMIT positionChanged(position());\n}\n\nvoid Player::play() {\n if(m_pipeline){\n m_pipeline->setState(QGst::StatePlaying);\n }\n}\n\nvoid Player::pause( ){\n if(m_pipeline){\n m_pipeline->setState(QGst::StatePaused);\n }\n}\n\nvoid Player::stop() {\n if(m_pipeline){\n m_pipeline->setState(QGst::StateReady);\n }\n}\n\nvoid Player::setPosition(QTime pos) {\n QGst::SeekEventPtr evt = QGst::SeekEvent::create(\n 1.0, QGst::FormatTime, QGst::SeekFlagFlush,\n QGst::SeekTypeSet, QGst::Clock::clockTimeFromTime(pos),\n QGst::SeekTypeNone, -1);\n\n m_pipeline->sendEvent(evt);\n}\n\nQTime Player::position() {\n if(m_pipeline){\n QGst::PositionQueryPtr query = QGst::PositionQuery::create(QGst::FormatTime);\n m_pipeline->query(query);\n return QGst::Clock::timeFromClockTime(query->position());\n }\n return QTime(0, 0, 0, 0);\n}\n\nQTime Player::length() {\n if(m_pipeline){\n QGst::DurationQueryPtr query = QGst::DurationQuery::create(QGst::FormatTime);\n m_pipeline->query(query);\n return QGst::Clock::timeFromClockTime(query->duration());\n }\n return QTime(0, 0, 0, 0);\n}\n\nQGst::State Player::state() {\n QGst::State state;\n if(!m_pipeline || \n m_pipeline->getState(&state, NULL, 1e9) != QGst::StateChangeSuccess)\n {\n state = QGst::StateNull;\n }\n return state;\n}\n\nvoid Player::handleStateChange(QGst::StateChangedMessagePtr scm) {\n switch(scm->newState()){\n case QGst::StatePlaying:\n Q_EMIT positionChanged(position());\n m_positionTimer.start(500);\n break;\n case QGst::StatePaused:\n if(scm->oldState() == QGst::StateReady){\n QGst::ElementPtr sink = \n m_pipeline->property(\"video-sink\").get();\n if(sink){\n setVideoSink(sink);\n QGst::ChildProxyPtr proxy = sink.dynamicCast();\n if (proxy)\n proxy->childByIndex(0)->setProperty(\"force-aspect-ratio\", true);\n }\n } else\n m_positionTimer.stop();\n break;\n case QGst::StateReady:\n if(scm->oldState() == QGst::StatePaused)\n \/* Remove the sink now to avoid inter-thread issues with Qt\n for the next time the pipeline goes to StatePlaying *\/\n setVideoSink(QGst::ElementPtr());\n break;\n default:\n break;\n }\n}\n\nvoid Player::busMessage(const QGst::MessagePtr & message) {\n switch(message->type()) {\n case QGst::MessageEos: \/\/End of stream. We reached the end of the file.\n qDebug() << \"got eos\";\n m_pipeline->setState(QGst::StateReady);\n break;\n case QGst::MessageError: \/\/Some error occurred.\n \/*TODO: send a message to UI *\/\n break;\n case QGst::MessageAsyncDone:\n {\n \/\/File prerolled, queries the pipeline to get the file duration\n QGst::DurationQueryPtr query = QGst::DurationQuery::create(QGst::FormatTime);\n \/\/This will create a temporary (cast to query).\n m_pipeline->query(query);\n }\n break;\n case QGst::MessageStateChanged:\n if(QGlib::Type::fromInstance(message->source()).\n isA(QGlib::GetType())) \n {\n QGst::StateChangedMessagePtr scm = \n message.dynamicCast();\n handleStateChange(scm);\n Q_EMIT stateChanged(scm->newState());\n }\n\n break;\n default:\n break;\n }\n}\n\n<|endoftext|>"} {"text":"add sirikata setup<|endoftext|>"} {"text":"\/\/ Filename: collisionPlane.cxx\n\/\/ Created by: drose (25Apr00)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/etc.cmu.edu\/panda3d\/docs\/license\/ .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d-general@lists.sourceforge.net .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"collisionPlane.h\"\n#include \"collisionHandler.h\"\n#include \"collisionEntry.h\"\n#include \"collisionSphere.h\"\n#include \"collisionLine.h\"\n#include \"collisionRay.h\"\n#include \"collisionSegment.h\"\n#include \"config_collide.h\"\n#include \"pointerToArray.h\"\n#include \"geomNode.h\"\n#include \"geom.h\"\n#include \"datagram.h\"\n#include \"datagramIterator.h\"\n#include \"bamReader.h\"\n#include \"bamWriter.h\"\n#include \"boundingPlane.h\"\n#include \"geom.h\"\n#include \"geomTrifans.h\"\n#include \"geomLinestrips.h\"\n#include \"geomVertexWriter.h\"\n\nPStatCollector CollisionPlane::_volume_pcollector(\"Collision Volumes:CollisionPlane\");\nPStatCollector CollisionPlane::_test_pcollector(\"Collision Tests:CollisionPlane\");\nTypeHandle CollisionPlane::_type_handle;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::make_copy\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCollisionSolid *CollisionPlane::\nmake_copy() {\n return new CollisionPlane(*this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::xform\n\/\/ Access: Public, Virtual\n\/\/ Description: Transforms the solid by the indicated matrix.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nxform(const LMatrix4f &mat) {\n _plane = _plane * mat;\n CollisionSolid::xform(mat);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::get_collision_origin\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns the point in space deemed to be the \"origin\"\n\/\/ of the solid for collision purposes. The closest\n\/\/ intersection point to this origin point is considered\n\/\/ to be the most significant.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nLPoint3f CollisionPlane::\nget_collision_origin() const {\n \/\/ No real sensible origin exists for a plane. We return 0, 0, 0,\n \/\/ without even bothering to ensure that that point exists on the\n \/\/ plane.\n return LPoint3f::origin();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::get_volume_pcollector\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns a PStatCollector that is used to count the\n\/\/ number of bounding volume tests made against a solid\n\/\/ of this type in a given frame.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPStatCollector CollisionPlane::\nget_volume_pcollector() {\n return _volume_pcollector;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::get_test_pcollector\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns a PStatCollector that is used to count the\n\/\/ number of intersection tests made against a solid\n\/\/ of this type in a given frame.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPStatCollector CollisionPlane::\nget_test_pcollector() {\n return _test_pcollector;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::output\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\noutput(ostream &out) const {\n out << \"cplane, (\" << _plane << \")\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::compute_internal_bounds\n\/\/ Access: Protected, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(BoundingVolume) CollisionPlane::\ncompute_internal_bounds() const {\n return new BoundingPlane(_plane);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_sphere\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_sphere(const CollisionEntry &entry) const {\n const CollisionSphere *sphere;\n DCAST_INTO_R(sphere, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_center = sphere->get_center() * wrt_mat;\n LVector3f from_radius_v =\n LVector3f(sphere->get_radius(), 0.0f, 0.0f) * wrt_mat;\n float from_radius = length(from_radius_v);\n\n float dist = dist_to_plane(from_center);\n if (dist > from_radius) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path() << \" into \"\n << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LVector3f from_normal = get_normal() * entry.get_inv_wrt_mat();\n\n LVector3f normal = (has_effective_normal() && sphere->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(from_center - get_normal() * dist);\n new_entry->set_interior_point(from_center - get_normal() * from_radius);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_line\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_line(const CollisionEntry &entry) const {\n const CollisionLine *line;\n DCAST_INTO_R(line, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_origin = line->get_origin() * wrt_mat;\n LVector3f from_direction = line->get_direction() * wrt_mat;\n\n float t;\n if (!_plane.intersects_line(t, from_origin, from_direction)) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LPoint3f into_intersection_point = from_origin + t * from_direction;\n\n LVector3f normal = (has_effective_normal() && line->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(into_intersection_point);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_ray\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_ray(const CollisionEntry &entry) const {\n const CollisionRay *ray;\n DCAST_INTO_R(ray, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_origin = ray->get_origin() * wrt_mat;\n LVector3f from_direction = ray->get_direction() * wrt_mat;\n\n float t;\n if (!_plane.intersects_line(t, from_origin, from_direction)) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (t < 0.0f) {\n \/\/ The intersection point is before the start of the ray.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LPoint3f into_intersection_point = from_origin + t * from_direction;\n\n LVector3f normal = (has_effective_normal() && ray->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(into_intersection_point);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_segment\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_segment(const CollisionEntry &entry) const {\n const CollisionSegment *segment;\n DCAST_INTO_R(segment, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_a = segment->get_point_a() * wrt_mat;\n LPoint3f from_b = segment->get_point_b() * wrt_mat;\n LVector3f from_direction = from_b - from_a;\n\n float t;\n if (!_plane.intersects_line(t, from_a, from_direction)) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (t < 0.0f || t > 1.0f) {\n \/\/ The intersection point is before the start of the segment or\n \/\/ after the end of the segment.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LPoint3f into_intersection_point = from_a + t * from_direction;\n\n LVector3f normal = (has_effective_normal() && segment->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(into_intersection_point);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::fill_viz_geom\n\/\/ Access: Protected, Virtual\n\/\/ Description: Fills the _viz_geom GeomNode up with Geoms suitable\n\/\/ for rendering this solid.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nfill_viz_geom() {\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"Recomputing viz for \" << *this << \"\\n\";\n }\n\n \/\/ Since we can't represent an infinite plane, we'll have to be\n \/\/ satisfied with drawing a big polygon. Choose four points on the\n \/\/ plane to be the corners of the polygon.\n\n \/\/ We must choose four points fairly reasonably spread apart on\n \/\/ the plane. We'll start with a center point and one corner\n \/\/ point, and then use cross products to find the remaining three\n \/\/ corners of a square.\n\n \/\/ The center point will be on the axis with the largest\n \/\/ coefficent. The first corner will be diagonal in the other two\n \/\/ dimensions.\n\n LPoint3f cp;\n LVector3f p1, p2, p3, p4;\n\n LVector3f normal = get_normal();\n float D = _plane[3];\n\n if (fabs(normal[0]) > fabs(normal[1]) &&\n fabs(normal[0]) > fabs(normal[2])) {\n \/\/ X has the largest coefficient.\n cp.set(-D \/ normal[0], 0.0f, 0.0f);\n p1 = LPoint3f(-(normal[1] + normal[2] + D)\/normal[0], 1.0f, 1.0f) - cp;\n\n } else if (fabs(normal[1]) > fabs(normal[2])) {\n \/\/ Y has the largest coefficient.\n cp.set(0.0f, -D \/ normal[1], 0.0f);\n p1 = LPoint3f(1.0f, -(normal[0] + normal[2] + D)\/normal[1], 1.0f) - cp;\n\n } else {\n \/\/ Z has the largest coefficient.\n cp.set(0.0f, 0.0f, -D \/ normal[2]);\n p1 = LPoint3f(1.0f, 1.0f, -(normal[0] + normal[1] + D)\/normal[2]) - cp;\n }\n\n p1.normalize();\n p2 = cross(normal, p1);\n p3 = cross(normal, p2);\n p4 = cross(normal, p3);\n\n static const double plane_scale = 10.0;\n\n PT(GeomVertexData) vdata = new GeomVertexData\n (\"collision\", GeomVertexFormat::get_v3(),\n Geom::UH_static);\n GeomVertexWriter vertex(vdata, InternalName::get_vertex());\n \n vertex.add_data3f(cp + p1 * plane_scale);\n vertex.add_data3f(cp + p2 * plane_scale);\n vertex.add_data3f(cp + p3 * plane_scale);\n vertex.add_data3f(cp + p4 * plane_scale);\n \n PT(GeomTrifans) body = new GeomTrifans(Geom::UH_static);\n body->add_consecutive_vertices(0, 4);\n body->close_primitive();\n \n PT(GeomLinestrips) border = new GeomLinestrips(Geom::UH_static);\n border->add_consecutive_vertices(0, 4);\n border->add_vertex(0);\n border->close_primitive();\n \n PT(Geom) geom1 = new Geom(vdata);\n geom1->add_primitive(body);\n \n PT(Geom) geom2 = new Geom(vdata);\n geom2->add_primitive(border);\n \n _viz_geom->add_geom(geom1, get_solid_viz_state());\n _viz_geom->add_geom(geom2, get_wireframe_viz_state());\n \n _bounds_viz_geom->add_geom(geom1, get_solid_bounds_viz_state());\n _bounds_viz_geom->add_geom(geom2, get_wireframe_bounds_viz_state());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::write_datagram\n\/\/ Access: Public\n\/\/ Description: Function to write the important information in\n\/\/ the particular object to a Datagram\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nwrite_datagram(BamWriter *manager, Datagram &me)\n{\n CollisionSolid::write_datagram(manager, me);\n _plane.write_datagram(me);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::fillin\n\/\/ Access: Protected\n\/\/ Description: Function that reads out of the datagram (or asks\n\/\/ manager to read) all of the data that is needed to\n\/\/ re-create this object and stores it in the appropiate\n\/\/ place\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nfillin(DatagramIterator& scan, BamReader* manager)\n{\n CollisionSolid::fillin(scan, manager);\n _plane.read_datagram(scan);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::make_CollisionPlane\n\/\/ Access: Protected\n\/\/ Description: Factory method to generate a CollisionPlane object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTypedWritable* CollisionPlane::\nmake_CollisionPlane(const FactoryParams ¶ms)\n{\n CollisionPlane *me = new CollisionPlane;\n DatagramIterator scan;\n BamReader *manager;\n\n parse_params(params, scan, manager);\n me->fillin(scan, manager);\n return me;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::register_with_factory\n\/\/ Access: Public, Static\n\/\/ Description: Factory method to generate a CollisionPlane object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nregister_with_read_factory()\n{\n BamReader::get_factory()->register_factory(get_class_type(), make_CollisionPlane);\n}\nformatting\/\/ Filename: collisionPlane.cxx\n\/\/ Created by: drose (25Apr00)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/etc.cmu.edu\/panda3d\/docs\/license\/ .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d-general@lists.sourceforge.net .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"collisionPlane.h\"\n#include \"collisionHandler.h\"\n#include \"collisionEntry.h\"\n#include \"collisionSphere.h\"\n#include \"collisionLine.h\"\n#include \"collisionRay.h\"\n#include \"collisionSegment.h\"\n#include \"config_collide.h\"\n#include \"pointerToArray.h\"\n#include \"geomNode.h\"\n#include \"geom.h\"\n#include \"datagram.h\"\n#include \"datagramIterator.h\"\n#include \"bamReader.h\"\n#include \"bamWriter.h\"\n#include \"boundingPlane.h\"\n#include \"geom.h\"\n#include \"geomTrifans.h\"\n#include \"geomLinestrips.h\"\n#include \"geomVertexWriter.h\"\n\nPStatCollector CollisionPlane::_volume_pcollector(\"Collision Volumes:CollisionPlane\");\nPStatCollector CollisionPlane::_test_pcollector(\"Collision Tests:CollisionPlane\");\nTypeHandle CollisionPlane::_type_handle;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::make_copy\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCollisionSolid *CollisionPlane::\nmake_copy() {\n return new CollisionPlane(*this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::xform\n\/\/ Access: Public, Virtual\n\/\/ Description: Transforms the solid by the indicated matrix.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nxform(const LMatrix4f &mat) {\n _plane = _plane * mat;\n CollisionSolid::xform(mat);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::get_collision_origin\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns the point in space deemed to be the \"origin\"\n\/\/ of the solid for collision purposes. The closest\n\/\/ intersection point to this origin point is considered\n\/\/ to be the most significant.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nLPoint3f CollisionPlane::\nget_collision_origin() const {\n \/\/ No real sensible origin exists for a plane. We return 0, 0, 0,\n \/\/ without even bothering to ensure that that point exists on the\n \/\/ plane.\n return LPoint3f::origin();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::get_volume_pcollector\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns a PStatCollector that is used to count the\n\/\/ number of bounding volume tests made against a solid\n\/\/ of this type in a given frame.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPStatCollector CollisionPlane::\nget_volume_pcollector() {\n return _volume_pcollector;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::get_test_pcollector\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns a PStatCollector that is used to count the\n\/\/ number of intersection tests made against a solid\n\/\/ of this type in a given frame.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPStatCollector CollisionPlane::\nget_test_pcollector() {\n return _test_pcollector;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::output\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\noutput(ostream &out) const {\n out << \"cplane, (\" << _plane << \")\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::compute_internal_bounds\n\/\/ Access: Protected, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(BoundingVolume) CollisionPlane::\ncompute_internal_bounds() const {\n return new BoundingPlane(_plane);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_sphere\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_sphere(const CollisionEntry &entry) const {\n const CollisionSphere *sphere;\n DCAST_INTO_R(sphere, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_center = sphere->get_center() * wrt_mat;\n LVector3f from_radius_v =\n LVector3f(sphere->get_radius(), 0.0f, 0.0f) * wrt_mat;\n float from_radius = length(from_radius_v);\n\n float dist = dist_to_plane(from_center);\n if (dist > from_radius) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LVector3f from_normal = get_normal() * entry.get_inv_wrt_mat();\n\n LVector3f normal = (\n has_effective_normal() && sphere->get_respect_effective_normal())\n ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(from_center - get_normal() * dist);\n new_entry->set_interior_point(from_center - get_normal() * from_radius);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_line\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_line(const CollisionEntry &entry) const {\n const CollisionLine *line;\n DCAST_INTO_R(line, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_origin = line->get_origin() * wrt_mat;\n LVector3f from_direction = line->get_direction() * wrt_mat;\n\n float t;\n if (!_plane.intersects_line(t, from_origin, from_direction)) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LPoint3f into_intersection_point = from_origin + t * from_direction;\n\n LVector3f normal = (has_effective_normal() && line->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(into_intersection_point);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_ray\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_ray(const CollisionEntry &entry) const {\n const CollisionRay *ray;\n DCAST_INTO_R(ray, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_origin = ray->get_origin() * wrt_mat;\n LVector3f from_direction = ray->get_direction() * wrt_mat;\n\n float t;\n if (!_plane.intersects_line(t, from_origin, from_direction)) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (t < 0.0f) {\n \/\/ The intersection point is before the start of the ray.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LPoint3f into_intersection_point = from_origin + t * from_direction;\n\n LVector3f normal = (has_effective_normal() && ray->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(into_intersection_point);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::test_intersection_from_segment\n\/\/ Access: Public, Virtual\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(CollisionEntry) CollisionPlane::\ntest_intersection_from_segment(const CollisionEntry &entry) const {\n const CollisionSegment *segment;\n DCAST_INTO_R(segment, entry.get_from(), 0);\n\n const LMatrix4f &wrt_mat = entry.get_wrt_mat();\n\n LPoint3f from_a = segment->get_point_a() * wrt_mat;\n LPoint3f from_b = segment->get_point_b() * wrt_mat;\n LVector3f from_direction = from_b - from_a;\n\n float t;\n if (!_plane.intersects_line(t, from_a, from_direction)) {\n \/\/ No intersection.\n return NULL;\n }\n\n if (t < 0.0f || t > 1.0f) {\n \/\/ The intersection point is before the start of the segment or\n \/\/ after the end of the segment.\n return NULL;\n }\n\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"intersection detected from \" << entry.get_from_node_path()\n << \" into \" << entry.get_into_node_path() << \"\\n\";\n }\n PT(CollisionEntry) new_entry = new CollisionEntry(entry);\n\n LPoint3f into_intersection_point = from_a + t * from_direction;\n\n LVector3f normal = (has_effective_normal() && segment->get_respect_effective_normal()) ? get_effective_normal() : get_normal();\n\n new_entry->set_surface_normal(normal);\n new_entry->set_surface_point(into_intersection_point);\n\n return new_entry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::fill_viz_geom\n\/\/ Access: Protected, Virtual\n\/\/ Description: Fills the _viz_geom GeomNode up with Geoms suitable\n\/\/ for rendering this solid.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nfill_viz_geom() {\n if (collide_cat.is_debug()) {\n collide_cat.debug()\n << \"Recomputing viz for \" << *this << \"\\n\";\n }\n\n \/\/ Since we can't represent an infinite plane, we'll have to be\n \/\/ satisfied with drawing a big polygon. Choose four points on the\n \/\/ plane to be the corners of the polygon.\n\n \/\/ We must choose four points fairly reasonably spread apart on\n \/\/ the plane. We'll start with a center point and one corner\n \/\/ point, and then use cross products to find the remaining three\n \/\/ corners of a square.\n\n \/\/ The center point will be on the axis with the largest\n \/\/ coefficent. The first corner will be diagonal in the other two\n \/\/ dimensions.\n\n LPoint3f cp;\n LVector3f p1, p2, p3, p4;\n\n LVector3f normal = get_normal();\n float D = _plane[3];\n\n if (fabs(normal[0]) > fabs(normal[1]) &&\n fabs(normal[0]) > fabs(normal[2])) {\n \/\/ X has the largest coefficient.\n cp.set(-D \/ normal[0], 0.0f, 0.0f);\n p1 = LPoint3f(-(normal[1] + normal[2] + D)\/normal[0], 1.0f, 1.0f) - cp;\n\n } else if (fabs(normal[1]) > fabs(normal[2])) {\n \/\/ Y has the largest coefficient.\n cp.set(0.0f, -D \/ normal[1], 0.0f);\n p1 = LPoint3f(1.0f, -(normal[0] + normal[2] + D)\/normal[1], 1.0f) - cp;\n\n } else {\n \/\/ Z has the largest coefficient.\n cp.set(0.0f, 0.0f, -D \/ normal[2]);\n p1 = LPoint3f(1.0f, 1.0f, -(normal[0] + normal[1] + D)\/normal[2]) - cp;\n }\n\n p1.normalize();\n p2 = cross(normal, p1);\n p3 = cross(normal, p2);\n p4 = cross(normal, p3);\n\n static const double plane_scale = 10.0;\n\n PT(GeomVertexData) vdata = new GeomVertexData\n (\"collision\", GeomVertexFormat::get_v3(),\n Geom::UH_static);\n GeomVertexWriter vertex(vdata, InternalName::get_vertex());\n \n vertex.add_data3f(cp + p1 * plane_scale);\n vertex.add_data3f(cp + p2 * plane_scale);\n vertex.add_data3f(cp + p3 * plane_scale);\n vertex.add_data3f(cp + p4 * plane_scale);\n \n PT(GeomTrifans) body = new GeomTrifans(Geom::UH_static);\n body->add_consecutive_vertices(0, 4);\n body->close_primitive();\n \n PT(GeomLinestrips) border = new GeomLinestrips(Geom::UH_static);\n border->add_consecutive_vertices(0, 4);\n border->add_vertex(0);\n border->close_primitive();\n \n PT(Geom) geom1 = new Geom(vdata);\n geom1->add_primitive(body);\n \n PT(Geom) geom2 = new Geom(vdata);\n geom2->add_primitive(border);\n \n _viz_geom->add_geom(geom1, get_solid_viz_state());\n _viz_geom->add_geom(geom2, get_wireframe_viz_state());\n \n _bounds_viz_geom->add_geom(geom1, get_solid_bounds_viz_state());\n _bounds_viz_geom->add_geom(geom2, get_wireframe_bounds_viz_state());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::write_datagram\n\/\/ Access: Public\n\/\/ Description: Function to write the important information in\n\/\/ the particular object to a Datagram\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nwrite_datagram(BamWriter *manager, Datagram &me)\n{\n CollisionSolid::write_datagram(manager, me);\n _plane.write_datagram(me);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::fillin\n\/\/ Access: Protected\n\/\/ Description: Function that reads out of the datagram (or asks\n\/\/ manager to read) all of the data that is needed to\n\/\/ re-create this object and stores it in the appropiate\n\/\/ place\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nfillin(DatagramIterator& scan, BamReader* manager)\n{\n CollisionSolid::fillin(scan, manager);\n _plane.read_datagram(scan);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::make_CollisionPlane\n\/\/ Access: Protected\n\/\/ Description: Factory method to generate a CollisionPlane object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTypedWritable* CollisionPlane::\nmake_CollisionPlane(const FactoryParams ¶ms)\n{\n CollisionPlane *me = new CollisionPlane;\n DatagramIterator scan;\n BamReader *manager;\n\n parse_params(params, scan, manager);\n me->fillin(scan, manager);\n return me;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: CollisionPlane::register_with_factory\n\/\/ Access: Public, Static\n\/\/ Description: Factory method to generate a CollisionPlane object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CollisionPlane::\nregister_with_read_factory()\n{\n BamReader::get_factory()->register_factory(get_class_type(), make_CollisionPlane);\n}\n<|endoftext|>"} {"text":"\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2017 Taras Kushnir \n *\n * Xpiks is distributed under the GNU General Public License, version 3.0\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"translationmanager.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/Common\/defines.h\"\n#include \"translationquery.h\"\n#include \"translationservice.h\"\n#include \"..\/Commands\/commandmanager.h\"\n#include \"..\/Models\/settingsmodel.h\"\n#include \"..\/Helpers\/constants.h\"\n\n#define SHORT_TRANSLATION_SYMBOLS 500\n#define BOOKNAME QLatin1String(\"bookname\")\n\nnamespace Translation {\n bool parseIfoFile(const QString &fullIfoPath, DictionaryInfo &info) {\n LOG_INFO << fullIfoPath;\n QFile file(fullIfoPath);\n bool success = false;\n\n if (file.open(QIODevice::ReadOnly)) {\n QTextStream in(&file);\n\n QString line;\n\n do {\n if (!in.atEnd()) {\n line = in.readLine();\n if ((line != \"StarDict's treedict ifo file\") &&\n (line != \"StarDict's dict ifo file\")) {\n LOG_WARNING << \"Wrong header\" << line;\n break;\n }\n }\n\n while (!in.atEnd()) {\n line = in.readLine();\n if (line.startsWith(BOOKNAME)) {\n info.m_Description = line.mid(BOOKNAME.size() + 1).simplified();\n info.m_FullIfoPath = fullIfoPath;\n success = true;\n break;\n }\n }\n } while (false);\n }\n\n return success;\n }\n\n TranslationManager::TranslationManager(QObject *parent) :\n QObject(parent),\n Common::BaseEntity(),\n m_AllowedSuffixes({\"idx\", \"idx.dz\", \"idx.oft\", \"dict.dz\", \"dict\", \"ifo\"}),\n m_SelectedDictionaryIndex(-1),\n m_IsBusy(false),\n m_HasMore(false)\n {\n m_TranslateTimer.setSingleShot(true);\n QObject::connect(&m_TranslateTimer, SIGNAL(timeout()), this, SLOT(updateTranslationTimer()));\n\n QObject::connect(&m_InitializationWatcher, SIGNAL(finished()), this, SLOT(initializationFinished()));\n }\n\n void TranslationManager::initializeDictionaries() {\n LOG_DEBUG << \"#\";\n QFuture initializeFuture = QtConcurrent::run(this, &TranslationManager::doInitializeDictionaries);\n m_InitializationWatcher.setFuture(initializeFuture);\n }\n\n void TranslationManager::setQuery(const QString &value) {\n bool anySignificantDifference = value.simplified() != m_Query;\n\n if (m_Query != value) {\n m_Query = value;\n emit queryChanged();\n }\n\n if (anySignificantDifference) {\n m_TranslateTimer.start(1000);\n }\n }\n\n void TranslationManager::setSelectedDictionaryIndex(int value) {\n LOG_INFO << value;\n\n if (m_SelectedDictionaryIndex != value) {\n m_SelectedDictionaryIndex = value;\n emit selectedDictionaryIndexChanged();\n\n if ((0 <= value) && (value < m_DictionariesList.length())) {\n auto *translationService = m_CommandManager->getTranslationService();\n auto &dictInfo = m_DictionariesList[value];\n LOG_INFO << \"Selecting\" << dictInfo.m_Description;\n translationService->selectDictionary(dictInfo.m_FullIfoPath);\n } else {\n LOG_WARNING << \"Cannot select dictionary path: indices to not match\";\n }\n\n if (!m_Query.isEmpty()) {\n m_TranslateTimer.start(1000);\n setIsBusy(true);\n }\n\n auto *settingsModel = m_CommandManager->getSettingsModel();\n settingsModel->setSelectedDictIndex(value);\n settingsModel->saveSelectedDictionaryIndex();\n }\n }\n\n QStringList TranslationManager::getDictionariesDescriptions() const {\n QStringList descriptions;\n descriptions.reserve(m_DictionariesList.length());\n\n foreach (const DictionaryInfo &dict, m_DictionariesList) {\n descriptions.append(dict.m_Description);\n }\n\n return descriptions;\n }\n\n void TranslationManager::doInitializeDictionaries() {\n QString appDataPath = XPIKS_USERDATA_PATH;\n\n if (!appDataPath.isEmpty()) {\n m_DictionariesDirPath = QDir::cleanPath(appDataPath + QDir::separator() + Constants::TRANSLATOR_DIR);\n\n QDir dictionariesDir(m_DictionariesDirPath);\n if (!dictionariesDir.exists()) {\n LOG_INFO << \"Creating dictionaries dir\" << m_DictionariesDirPath;\n QDir().mkpath(m_DictionariesDirPath);\n }\n } else {\n m_DictionariesDirPath = QDir::currentPath();\n }\n\n QDirIterator it(m_DictionariesDirPath, QStringList() << \"*.ifo\", QDir::Files, QDirIterator::NoIteratorFlags);\n\n while (it.hasNext()) {\n QString ifoFullPath = it.next();\n\n DictionaryInfo di;\n if (parseIfoFile(ifoFullPath, di) &&\n hasAllNeededComponents(ifoFullPath)) {\n m_DictionariesList.append(di);\n LOG_INFO << \"Parsed\" << di.m_Description;\n } else {\n LOG_WARNING << \"Failed to parse IFO:\" << ifoFullPath;\n }\n }\n }\n\n bool TranslationManager::acquireDictionary(const QString &anyDictFilePath) {\n QFileInfo fi(anyDictFilePath);\n Q_ASSERT(fi.exists());\n QString longPrefix = QDir::cleanPath(fi.absolutePath() + QDir::separator() + fi.baseName());\n QString shortPrefix = fi.baseName();\n\n bool anyError = false, anyFileCopied = false,\n indexFound = false, dictFound = false, ifoFound = false;\n\n foreach (const QString &suffix, m_AllowedSuffixes) {\n QString probablePath = longPrefix + \".\" + suffix;\n\n if (QFileInfo(probablePath).exists()) {\n LOG_INFO << \"File found:\" << probablePath;\n QString localDict = QDir::cleanPath(m_DictionariesDirPath + QDir::separator() + shortPrefix + \".\" + suffix);\n\n if (QFile::copy(probablePath, localDict)) {\n LOG_INFO << \"Copied to\" << localDict;\n anyFileCopied = true;\n\n \/\/ TODO: refactor this someday to check just needed\n \/\/ extensions instead of looping all of them\n indexFound = indexFound || suffix.contains(\"idx\");\n dictFound = dictFound || suffix.contains(\"dict\");\n ifoFound = ifoFound || suffix.contains(\"ifo\");\n } else {\n LOG_WARNING << \"Failed to copy as:\" << localDict;\n anyError = true;\n break;\n }\n } else {\n LOG_INFO << \"File NOT found:\" << probablePath;\n }\n }\n\n LOG_INFO << \"IFO found\" << ifoFound << \"Index found\" << indexFound << \"Dictionary found\" << dictFound;\n\n bool success = (anyFileCopied) && (!anyError) && (ifoFound && dictFound && indexFound);\n return success;\n }\n\n bool TranslationManager::hasAllNeededComponents(const QString &anyDictFilePath) const {\n QFileInfo fi(anyDictFilePath);\n Q_ASSERT(fi.exists());\n\n QString longPrefix = QDir::cleanPath(fi.absolutePath() + QDir::separator() + fi.baseName());\n bool indexFound = false, dictFound = false, ifoFound = false;\n\n foreach (const QString &suffix, m_AllowedSuffixes) {\n QString probablePath = longPrefix + \".\" + suffix;\n\n if (QFileInfo(probablePath).exists()) {\n \/\/ TODO: refactor this someday to check just needed\n \/\/ extensions instead of looping all of them\n indexFound = indexFound || suffix.contains(\"idx\");\n dictFound = dictFound || suffix.contains(\"dict\");\n ifoFound = ifoFound || suffix.contains(\"ifo\");\n }\n }\n\n bool success = ifoFound && dictFound && indexFound;\n return success;\n }\n\n void TranslationManager::clear() {\n m_Query.clear();\n m_FullTranslation.clear();\n m_ShortenedTranslation.clear();\n m_HasMore = false;\n emit queryChanged();\n emit fullTranslationChanged();\n emit shortTranslationChanged();\n emit hasMoreChanged();\n }\n\n bool TranslationManager::addDictionary(const QUrl &url) {\n Q_ASSERT(url.isLocalFile());\n QString anyDictFilePath = url.toLocalFile();\n LOG_INFO << anyDictFilePath;\n QFileInfo fi(anyDictFilePath);\n bool success = false;\n\n QSet allowedSuffixes = m_AllowedSuffixes.toSet();\n\n do {\n if (!fi.exists()) {\n LOG_WARNING << \"File does not exist:\" << anyDictFilePath;\n break;\n }\n\n if (!fi.isFile()) {\n LOG_WARNING << \"Path is not a file:\" << anyDictFilePath;\n break;\n }\n\n if (!allowedSuffixes.contains(fi.completeSuffix().toLower())) {\n LOG_WARNING << \"File\" << fi.completeSuffix() << \"is unsupported\";\n break;\n }\n\n QString probableIfoPath = QDir::cleanPath(fi.absolutePath() + QDir::separator() +\n fi.baseName() + \".ifo\");\n DictionaryInfo di;\n if (parseIfoFile(probableIfoPath, di)) {\n LOG_INFO << \"Parsed\" << di.m_Description;\n if (acquireDictionary(probableIfoPath)) {\n m_DictionariesList.append(di);\n success = true;\n } else {\n LOG_WARNING << \"Failed to acquire dictionary\" << probableIfoPath;\n }\n } else {\n LOG_WARNING << \"Failed to parse IFO:\" << probableIfoPath;\n }\n } while (false);\n\n if (success && (m_SelectedDictionaryIndex == -1)) {\n setSelectedDictionaryIndex(0);\n }\n\n emit dictionariesChanged();\n\n return success;\n }\n\n void TranslationManager::translationArrived() {\n LOG_DEBUG << \"#\";\n TranslationQuery *query = qobject_cast(sender());\n Q_ASSERT(query != nullptr);\n\n if (query->hasTranslation()) {\n QString translation = query->getTranslation();\n\n m_FullTranslation = translation;\n m_ShortenedTranslation = translation.left(SHORT_TRANSLATION_SYMBOLS);\n } else {\n QString nothingFound = QObject::tr(\"No results\");\n\n m_FullTranslation = nothingFound;\n m_ShortenedTranslation = nothingFound;\n }\n\n m_HasMore = m_FullTranslation.length() != m_ShortenedTranslation.length();\n emit hasMoreChanged();\n\n if (m_HasMore) {\n m_ShortenedTranslation.append(\"...\");\n }\n\n emit fullTranslationChanged();\n emit shortTranslationChanged();\n\n setIsBusy(false);\n }\n\n void TranslationManager::updateTranslationTimer() {\n TranslationService *translationService = m_CommandManager->getTranslationService();\n translationService->translate(m_Query);\n setIsBusy(true);\n }\n\n void TranslationManager::initializationFinished() {\n LOG_DEBUG << \"#\";\n\n auto *settingsModel = m_CommandManager->getSettingsModel();\n int selectedDictIndex = settingsModel->getSelectedDictIndex();\n if ((0 <= selectedDictIndex) && (selectedDictIndex < m_DictionariesList.length())) {\n setSelectedDictionaryIndex(selectedDictIndex);\n } else {\n setSelectedDictionaryIndex(0);\n }\n\n emit dictionariesChanged();\n emit selectedDictionaryIndexChanged();\n }\n}\nFix for integration tests\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2017 Taras Kushnir \n *\n * Xpiks is distributed under the GNU General Public License, version 3.0\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"translationmanager.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/Common\/defines.h\"\n#include \"translationquery.h\"\n#include \"translationservice.h\"\n#include \"..\/Commands\/commandmanager.h\"\n#include \"..\/Models\/settingsmodel.h\"\n#include \"..\/Helpers\/constants.h\"\n\n#define SHORT_TRANSLATION_SYMBOLS 500\n#define BOOKNAME QLatin1String(\"bookname\")\n\nnamespace Translation {\n bool parseIfoFile(const QString &fullIfoPath, DictionaryInfo &info) {\n LOG_INFO << fullIfoPath;\n QFile file(fullIfoPath);\n bool success = false;\n\n if (file.open(QIODevice::ReadOnly)) {\n QTextStream in(&file);\n\n QString line;\n\n do {\n if (!in.atEnd()) {\n line = in.readLine();\n if ((line != \"StarDict's treedict ifo file\") &&\n (line != \"StarDict's dict ifo file\")) {\n LOG_WARNING << \"Wrong header\" << line;\n break;\n }\n }\n\n while (!in.atEnd()) {\n line = in.readLine();\n if (line.startsWith(BOOKNAME)) {\n info.m_Description = line.mid(BOOKNAME.size() + 1).simplified();\n info.m_FullIfoPath = fullIfoPath;\n success = true;\n break;\n }\n }\n } while (false);\n }\n\n return success;\n }\n\n TranslationManager::TranslationManager(QObject *parent) :\n QObject(parent),\n Common::BaseEntity(),\n m_AllowedSuffixes({\"idx\", \"idx.dz\", \"idx.oft\", \"dict.dz\", \"dict\", \"ifo\"}),\n m_SelectedDictionaryIndex(-1),\n m_IsBusy(false),\n m_HasMore(false)\n {\n m_TranslateTimer.setSingleShot(true);\n QObject::connect(&m_TranslateTimer, SIGNAL(timeout()), this, SLOT(updateTranslationTimer()));\n\n QObject::connect(&m_InitializationWatcher, SIGNAL(finished()), this, SLOT(initializationFinished()));\n }\n\n void TranslationManager::initializeDictionaries() {\n LOG_DEBUG << \"#\";\n QFuture initializeFuture = QtConcurrent::run(this, &TranslationManager::doInitializeDictionaries);\n m_InitializationWatcher.setFuture(initializeFuture);\n }\n\n void TranslationManager::setQuery(const QString &value) {\n bool anySignificantDifference = value.simplified() != m_Query;\n\n if (m_Query != value) {\n m_Query = value;\n emit queryChanged();\n }\n\n if (anySignificantDifference) {\n m_TranslateTimer.start(1000);\n }\n }\n\n void TranslationManager::setSelectedDictionaryIndex(int value) {\n LOG_INFO << value;\n LOG_INTEGRATION_TESTS << \"Current index\" << m_SelectedDictionaryIndex;\n LOG_INTEGRATION_TESTS << \"Overall\" << m_DictionariesList.length() << \"dictionaries\";\n\n if (m_SelectedDictionaryIndex != value) {\n LOG_INFO << \"Changing current dictionary\";\n m_SelectedDictionaryIndex = value;\n emit selectedDictionaryIndexChanged();\n\n if ((0 <= value) && (value < m_DictionariesList.length())) {\n auto *translationService = m_CommandManager->getTranslationService();\n auto &dictInfo = m_DictionariesList[value];\n LOG_INFO << \"Selecting\" << dictInfo.m_Description;\n translationService->selectDictionary(dictInfo.m_FullIfoPath);\n } else {\n LOG_WARNING << \"Cannot select dictionary path: indices to not match\";\n }\n\n if (!m_Query.isEmpty()) {\n m_TranslateTimer.start(1000);\n setIsBusy(true);\n }\n\n auto *settingsModel = m_CommandManager->getSettingsModel();\n settingsModel->setSelectedDictIndex(value);\n settingsModel->saveSelectedDictionaryIndex();\n }\n }\n\n QStringList TranslationManager::getDictionariesDescriptions() const {\n QStringList descriptions;\n descriptions.reserve(m_DictionariesList.length());\n\n foreach (const DictionaryInfo &dict, m_DictionariesList) {\n descriptions.append(dict.m_Description);\n }\n\n return descriptions;\n }\n\n void TranslationManager::doInitializeDictionaries() {\n QString appDataPath = XPIKS_USERDATA_PATH;\n\n if (!appDataPath.isEmpty()) {\n m_DictionariesDirPath = QDir::cleanPath(appDataPath + QDir::separator() + Constants::TRANSLATOR_DIR);\n\n QDir dictionariesDir(m_DictionariesDirPath);\n if (!dictionariesDir.exists()) {\n LOG_INFO << \"Creating dictionaries dir\" << m_DictionariesDirPath;\n QDir().mkpath(m_DictionariesDirPath);\n }\n } else {\n m_DictionariesDirPath = QDir::currentPath();\n }\n\n QDirIterator it(m_DictionariesDirPath, QStringList() << \"*.ifo\", QDir::Files, QDirIterator::NoIteratorFlags);\n\n while (it.hasNext()) {\n QString ifoFullPath = it.next();\n\n DictionaryInfo di;\n if (parseIfoFile(ifoFullPath, di) &&\n hasAllNeededComponents(ifoFullPath)) {\n m_DictionariesList.append(di);\n LOG_INFO << \"Parsed\" << di.m_Description;\n } else {\n LOG_WARNING << \"Failed to parse IFO:\" << ifoFullPath;\n }\n }\n }\n\n bool TranslationManager::acquireDictionary(const QString &anyDictFilePath) {\n QFileInfo fi(anyDictFilePath);\n Q_ASSERT(fi.exists());\n QString longPrefix = QDir::cleanPath(fi.absolutePath() + QDir::separator() + fi.baseName());\n QString shortPrefix = fi.baseName();\n\n bool anyError = false, anyFileCopied = false,\n indexFound = false, dictFound = false, ifoFound = false;\n\n foreach (const QString &suffix, m_AllowedSuffixes) {\n QString probablePath = longPrefix + \".\" + suffix;\n\n if (QFileInfo(probablePath).exists()) {\n LOG_INFO << \"File found:\" << probablePath;\n QString localDict = QDir::cleanPath(m_DictionariesDirPath + QDir::separator() + shortPrefix + \".\" + suffix);\n\n if (QFile::copy(probablePath, localDict)) {\n LOG_INFO << \"Copied to\" << localDict;\n anyFileCopied = true;\n\n \/\/ TODO: refactor this someday to check just needed\n \/\/ extensions instead of looping all of them\n indexFound = indexFound || suffix.contains(\"idx\");\n dictFound = dictFound || suffix.contains(\"dict\");\n ifoFound = ifoFound || suffix.contains(\"ifo\");\n } else {\n LOG_WARNING << \"Failed to copy as:\" << localDict;\n anyError = true;\n break;\n }\n } else {\n LOG_INFO << \"File NOT found:\" << probablePath;\n }\n }\n\n LOG_INFO << \"IFO found\" << ifoFound << \"Index found\" << indexFound << \"Dictionary found\" << dictFound;\n\n bool success = (anyFileCopied) && (!anyError) && (ifoFound && dictFound && indexFound);\n return success;\n }\n\n bool TranslationManager::hasAllNeededComponents(const QString &anyDictFilePath) const {\n QFileInfo fi(anyDictFilePath);\n Q_ASSERT(fi.exists());\n\n QString longPrefix = QDir::cleanPath(fi.absolutePath() + QDir::separator() + fi.baseName());\n bool indexFound = false, dictFound = false, ifoFound = false;\n\n foreach (const QString &suffix, m_AllowedSuffixes) {\n QString probablePath = longPrefix + \".\" + suffix;\n\n if (QFileInfo(probablePath).exists()) {\n \/\/ TODO: refactor this someday to check just needed\n \/\/ extensions instead of looping all of them\n indexFound = indexFound || suffix.contains(\"idx\");\n dictFound = dictFound || suffix.contains(\"dict\");\n ifoFound = ifoFound || suffix.contains(\"ifo\");\n }\n }\n\n bool success = ifoFound && dictFound && indexFound;\n return success;\n }\n\n void TranslationManager::clear() {\n m_Query.clear();\n m_FullTranslation.clear();\n m_ShortenedTranslation.clear();\n m_HasMore = false;\n emit queryChanged();\n emit fullTranslationChanged();\n emit shortTranslationChanged();\n emit hasMoreChanged();\n }\n\n bool TranslationManager::addDictionary(const QUrl &url) {\n Q_ASSERT(url.isLocalFile());\n QString anyDictFilePath = url.toLocalFile();\n LOG_INFO << anyDictFilePath;\n QFileInfo fi(anyDictFilePath);\n bool success = false;\n\n QSet allowedSuffixes = m_AllowedSuffixes.toSet();\n\n do {\n if (!fi.exists()) {\n LOG_WARNING << \"File does not exist:\" << anyDictFilePath;\n break;\n }\n\n if (!fi.isFile()) {\n LOG_WARNING << \"Path is not a file:\" << anyDictFilePath;\n break;\n }\n\n if (!allowedSuffixes.contains(fi.completeSuffix().toLower())) {\n LOG_WARNING << \"File\" << fi.completeSuffix() << \"is unsupported\";\n break;\n }\n\n QString probableIfoPath = QDir::cleanPath(fi.absolutePath() + QDir::separator() +\n fi.baseName() + \".ifo\");\n DictionaryInfo di;\n if (parseIfoFile(probableIfoPath, di)) {\n LOG_INFO << \"Parsed\" << di.m_Description;\n if (acquireDictionary(probableIfoPath)) {\n m_DictionariesList.append(di);\n success = true;\n } else {\n LOG_WARNING << \"Failed to acquire dictionary\" << probableIfoPath;\n }\n } else {\n LOG_WARNING << \"Failed to parse IFO:\" << probableIfoPath;\n }\n } while (false);\n\n if (success && (m_SelectedDictionaryIndex == -1)) {\n setSelectedDictionaryIndex(0);\n }\n\n emit dictionariesChanged();\n\n return success;\n }\n\n void TranslationManager::translationArrived() {\n LOG_DEBUG << \"#\";\n TranslationQuery *query = qobject_cast(sender());\n Q_ASSERT(query != nullptr);\n\n if (query->hasTranslation()) {\n QString translation = query->getTranslation();\n\n m_FullTranslation = translation;\n m_ShortenedTranslation = translation.left(SHORT_TRANSLATION_SYMBOLS);\n } else {\n QString nothingFound = QObject::tr(\"No results\");\n\n m_FullTranslation = nothingFound;\n m_ShortenedTranslation = nothingFound;\n }\n\n m_HasMore = m_FullTranslation.length() != m_ShortenedTranslation.length();\n emit hasMoreChanged();\n\n if (m_HasMore) {\n m_ShortenedTranslation.append(\"...\");\n }\n\n emit fullTranslationChanged();\n emit shortTranslationChanged();\n\n setIsBusy(false);\n }\n\n void TranslationManager::updateTranslationTimer() {\n TranslationService *translationService = m_CommandManager->getTranslationService();\n translationService->translate(m_Query);\n setIsBusy(true);\n }\n\n void TranslationManager::initializationFinished() {\n LOG_DEBUG << \"#\";\n\n auto *settingsModel = m_CommandManager->getSettingsModel();\n int selectedDictIndex = settingsModel->getSelectedDictIndex();\n if ((0 <= selectedDictIndex) && (selectedDictIndex < m_DictionariesList.length())) {\n setSelectedDictionaryIndex(selectedDictIndex);\n } else {\n if (!m_DictionariesList.empty()) {\n setSelectedDictionaryIndex(0);\n }\n }\n\n emit dictionariesChanged();\n emit selectedDictionaryIndexChanged();\n }\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_FWD_MAT_FUN_UNIT_VECTOR_CONSTRAIN_HPP\n#define STAN_MATH_FWD_MAT_FUN_UNIT_VECTOR_CONSTRAIN_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n template \n inline Eigen::Matrix, R, C>\n unit_vector_constrain(const Eigen::Matrix, R, C>& y) {\n using std::sqrt;\n using Eigen::Matrix;\n\n Matrix y_t(y.size());\n for (int k = 0; k < y.size(); ++k)\n y_t.coeffRef(k) = y.coeff(k).val_;\n\n Matrix unit_vector_y_t\n = unit_vector_constrain(y_t);\n Matrix, R, C> unit_vector_y(y.size());\n for (int k = 0; k < y.size(); ++k)\n unit_vector_y.coeffRef(k).val_ = unit_vector_y_t.coeff(k);\n\n const T squared_norm = dot_self(y_t);\n const T norm = sqrt(squared_norm);\n const T inv_norm = inv(norm);\n Matrix J\n = tcrossprod(y_t) \/ (-norm * squared_norm);\n\n \/\/ for each input position\n for (int m = 0; m < y.size(); ++m) {\n J.coeffRef(m, m) += inv_norm;\n \/\/ for each output position\n for (int k = 0; k < y.size(); ++k) {\n \/\/ chain from input to output\n unit_vector_y.coeffRef(k).d_ = J.coeff(k, m);\n }\n }\n return unit_vector_y;\n }\n\n template \n inline Eigen::Matrix, R, C>\n unit_vector_constrain(const Eigen::Matrix, R, C>& y, fvar& lp) {\n const fvar squared_norm = dot_self(y);\n lp -= 0.5 * squared_norm;\n return unit_vector_constrain(y);\n }\n\n }\n}\n#endif\nincludes and divide for unit vector constrain#ifndef STAN_MATH_FWD_MAT_FUN_UNIT_VECTOR_CONSTRAIN_HPP\n#define STAN_MATH_FWD_MAT_FUN_UNIT_VECTOR_CONSTRAIN_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n template \n inline Eigen::Matrix, R, C>\n unit_vector_constrain(const Eigen::Matrix, R, C>& y) {\n using std::sqrt;\n using Eigen::Matrix;\n\n Matrix y_t(y.size());\n for (int k = 0; k < y.size(); ++k)\n y_t.coeffRef(k) = y.coeff(k).val_;\n\n Matrix unit_vector_y_t\n = unit_vector_constrain(y_t);\n Matrix, R, C> unit_vector_y(y.size());\n for (int k = 0; k < y.size(); ++k)\n unit_vector_y.coeffRef(k).val_ = unit_vector_y_t.coeff(k);\n\n const T squared_norm = dot_self(y_t);\n const T norm = sqrt(squared_norm);\n const T inv_norm = inv(norm);\n Matrix J\n = divide(tcrossprod(y_t), -norm * squared_norm);\n\n \/\/ for each input position\n for (int m = 0; m < y.size(); ++m) {\n J.coeffRef(m, m) += inv_norm;\n \/\/ for each output position\n for (int k = 0; k < y.size(); ++k) {\n \/\/ chain from input to output\n unit_vector_y.coeffRef(k).d_ = J.coeff(k, m);\n }\n }\n return unit_vector_y;\n }\n\n template \n inline Eigen::Matrix, R, C>\n unit_vector_constrain(const Eigen::Matrix, R, C>& y, fvar& lp) {\n const fvar squared_norm = dot_self(y);\n lp -= 0.5 * squared_norm;\n return unit_vector_constrain(y);\n }\n\n }\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ MFEM\n\/\/\n\/\/ Compile with: make ex1p\n\/\/\n\/\/ Sample runs:\n\/\/ mpirun -np 1 ex1p -m ..\/..\/data\/inline-quad.mesh -rs 0 -vis -o 2\n\n#include \"..\/..\/mfem.hpp\"\n#include \n#include \n\nusing namespace std;\nusing namespace mfem;\n\ndouble dist_value(const Vector &x, const int type)\n{\n double ring_radius = 0.2;\n if (type == 1 || type == 2) { \/\/ circle of radius 0.2 - centered at 0.5, 0.5\n double dx = x(0) - 0.5,\n dy = x(1) - 0.5,\n rv = dx*dx + dy*dy;\n rv = rv > 0 ? pow(rv, 0.5) : 0;\n return rv - ring_radius; \/\/ +ve is the domain\n }\n else if (type == 3) { \/\/ walls at y = 0.0 and y = 1.0\n if (x(1) > 0.5) {\n return 1. - x(1);\n }\n else {\n return x(1);\n }\n }\n else {\n MFEM_ABORT(\" Function type not implement yet.\");\n }\n return 0.;\n}\n\n\/\/\/ Returns distance from 0 level set. If dist +ve, point is inside the domain,\n\/\/\/ otherwise outside.\nclass Dist_Value_Coefficient : public Coefficient\n{\nprivate:\n int type;\n\npublic:\n Dist_Value_Coefficient(int type_)\n : Coefficient(), type(type_) { }\n\n virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)\n {\n Vector x(3);\n T.Transform(ip, x);\n return dist_value(x, type);\n }\n};\n\n\/\/\/ Level set coefficient - 1 inside the domain, -1 outside, 0 at the boundary.\nclass Dist_Level_Set_Coefficient : public Coefficient\n{\nprivate:\n int type;\n\npublic:\n Dist_Level_Set_Coefficient(int type_)\n : Coefficient(), type(type_) { }\n\n virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)\n {\n Vector x(3);\n T.Transform(ip, x);\n double dist = dist_value(x, type);\n if (dist >= 0.) { return 1.; }\n else { return -1.; }\n }\n};\n\n\/\/\/ Distance vector to the zero level-set.\nclass Dist_Vector_Coefficient : public VectorCoefficient\n{\nprivate:\n int type;\n\npublic:\n Dist_Vector_Coefficient(int dim_, int type_)\n : VectorCoefficient(dim_), type(type_) { }\n\n virtual void Eval(Vector &p, ElementTransformation &T,\n const IntegrationPoint &ip)\n {\n Vector x(3);\n T.Transform(ip, x);\n p.SetSize(x.Size());\n if (type == 1 || type == 2) {\n double dist0 = dist_value(x, type);\n double theta = std::atan2(x(1)-0.5, x(0)-0.5);\n p(0) = -dist0*std::cos(theta);\n p(1) = -dist0*std::sin(theta);\n }\n else if (type == 3) {\n double dist0 = dist_value(x, type);\n p(0) = 0.;\n if (x(1) > 1. || x(1) < 0.5) {\n p(1) = -dist0;\n }\n else {\n p(1) = dist0;\n }\n }\n }\n};\n\n#define xy_p 2.\n\/\/\/ Boundary conditions\ndouble dirichlet_velocity(const Vector &x, int type)\n{\n if (type == 1) { \/\/ u = 0. on the boundaries.\n return 0.;\n }\n else if (type == 2) { \/\/ u = x^p+y^p\n return pow(x(0), xy_p) + pow(x(1), xy_p);\n }\n else if (type == 3) { \/\/ u = (1\/pi^2)sin(pi*x*y),\n return 1.\/(M_PI*M_PI)*std::sin(M_PI*x(0)*x(1));\n }\n else {\n MFEM_ABORT(\" Function type not implement yet.\");\n }\n return 0.;\n}\n\n\/\/\/ `f` for the Poisson problem (-nabla^2 u = f).\ndouble rhs_fun(const Vector &x, int type)\n{\n if (type == 1) {\n return 1.;\n }\n else if (type == 2) {\n double coeff = std::max(xy_p*(xy_p-1), 1.);\n double expon = std::max(0., xy_p-2);\n if (xy_p == 1) {\n return 0.;\n }\n else {\n return -coeff*std::pow(x(0), expon) - coeff*std::pow(x(1), expon);\n }\n }\n else if (type == 3) {\n return std::sin(M_PI*x(0)*x(1))*(x(0)*x(0)+x(1)*x(1));\n }\n else {\n MFEM_ABORT(\" Function type not implement yet.\");\n }\n return 0.;\n}\nlevel set type 1 for 3D case\/\/ MFEM\n\/\/\n\/\/ Compile with: make ex1p\n\/\/\n\/\/ Sample runs:\n\/\/ mpirun -np 1 ex1p -m ..\/..\/data\/inline-quad.mesh -rs 0 -vis -o 2\n\n#include \"..\/..\/mfem.hpp\"\n#include \n#include \n\nusing namespace std;\nusing namespace mfem;\n\ndouble dist_value(const Vector &x, const int type)\n{\n double ring_radius = 0.2;\n if (type == 1 || type == 2) { \/\/ circle of radius 0.2 - centered at 0.5, 0.5\n double dx = x(0) - 0.5,\n dy = x(1) - 0.5,\n rv = dx*dx + dy*dy;\n if (x.Size() == 3) {\n double dz = x(2) - 0.5;\n rv += dz*dz;\n }\n rv = rv > 0 ? pow(rv, 0.5) : 0;\n return rv - ring_radius; \/\/ +ve is the domain\n }\n else if (type == 3) { \/\/ walls at y = 0.0 and y = 1.0\n if (x(1) > 0.5) {\n return 1. - x(1);\n }\n else {\n return x(1);\n }\n }\n else {\n MFEM_ABORT(\" Function type not implement yet.\");\n }\n return 0.;\n}\n\n\/\/\/ Returns distance from 0 level set. If dist +ve, point is inside the domain,\n\/\/\/ otherwise outside.\nclass Dist_Value_Coefficient : public Coefficient\n{\nprivate:\n int type;\n\npublic:\n Dist_Value_Coefficient(int type_)\n : Coefficient(), type(type_) { }\n\n virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)\n {\n Vector x(3);\n T.Transform(ip, x);\n return dist_value(x, type);\n }\n};\n\n\/\/\/ Level set coefficient - 1 inside the domain, -1 outside, 0 at the boundary.\nclass Dist_Level_Set_Coefficient : public Coefficient\n{\nprivate:\n int type;\n\npublic:\n Dist_Level_Set_Coefficient(int type_)\n : Coefficient(), type(type_) { }\n\n virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)\n {\n Vector x(3);\n T.Transform(ip, x);\n double dist = dist_value(x, type);\n if (dist >= 0.) { return 1.; }\n else { return -1.; }\n }\n};\n\n\/\/\/ Distance vector to the zero level-set.\nclass Dist_Vector_Coefficient : public VectorCoefficient\n{\nprivate:\n int type;\n\npublic:\n Dist_Vector_Coefficient(int dim_, int type_)\n : VectorCoefficient(dim_), type(type_) { }\n\n virtual void Eval(Vector &p, ElementTransformation &T,\n const IntegrationPoint &ip)\n {\n Vector x;\n T.Transform(ip, x);\n const int dim = x.Size();\n p.SetSize(dim);\n if (type == 1 || type == 2) {\n double dist0 = dist_value(x, type);\n for (int i = 0; i < dim; i++) { p(i) = 0.5 - x(i); }\n double length = p.Norml2();\n p *= dist0\/length;\n }\n else if (type == 3) {\n double dist0 = dist_value(x, type);\n p(0) = 0.;\n if (x(1) > 1. || x(1) < 0.5) {\n p(1) = -dist0;\n }\n else {\n p(1) = dist0;\n }\n }\n }\n};\n\n#define xy_p 2.\n\/\/\/ Boundary conditions\ndouble dirichlet_velocity(const Vector &x, int type)\n{\n if (type == 1) { \/\/ u = 0. on the boundaries.\n return 0.;\n }\n else if (type == 2) { \/\/ u = x^p+y^p\n return pow(x(0), xy_p) + pow(x(1), xy_p);\n }\n else if (type == 3) { \/\/ u = (1\/pi^2)sin(pi*x*y),\n return 1.\/(M_PI*M_PI)*std::sin(M_PI*x(0)*x(1));\n }\n else {\n MFEM_ABORT(\" Function type not implement yet.\");\n }\n return 0.;\n}\n\n\/\/\/ `f` for the Poisson problem (-nabla^2 u = f).\ndouble rhs_fun(const Vector &x, int type)\n{\n if (type == 1) {\n return 1.;\n }\n else if (type == 2) {\n double coeff = std::max(xy_p*(xy_p-1), 1.);\n double expon = std::max(0., xy_p-2);\n if (xy_p == 1) {\n return 0.;\n }\n else {\n return -coeff*std::pow(x(0), expon) - coeff*std::pow(x(1), expon);\n }\n }\n else if (type == 3) {\n return std::sin(M_PI*x(0)*x(1))*(x(0)*x(0)+x(1)*x(1));\n }\n else {\n MFEM_ABORT(\" Function type not implement yet.\");\n }\n return 0.;\n}\n<|endoftext|>"} {"text":"We should use the same settings in the HLT Wrapper for TPC Offline Preprocessor as offline uses. Offline settings are set in CPass0 makeOCDB.C macro. Unfortunatelly I currently see no better solution but copying.<|endoftext|>"} {"text":"#include \"itkImage.h\"\n\nint main()\n{\n\n typedef itk::Image< unsigned short, 3 > ImageType;\n\n ImageType::Pointer image = ImageType::New();\n\n ImageType::IndexType start;\n ImageType::SizeType size;\n\n size[0] = 200; \/\/ size along X\n size[1] = 200; \/\/ size along Y\n size[2] = 200; \/\/ size along Z\n\n start[0] = 0; \/\/ first index on X\n start[1] = 0; \/\/ first index on Y\n start[2] = 0; \/\/ first index on Z\n\n ImageType::RegionType region;\n \n image->SetRegions( region );\n image->Allocate();\n\n image->FillBuffer( 0 );\n\n double spacing[ 3 ];\n\n spacing[0] = 0.33; \/\/ spacing in millimeters\n spacing[1] = 0.33; \/\/ spacing in millimeters\n spacing[2] = 1.20; \/\/ spacing in millimeters\n\n image->SetSpacing( spacing );\n\n double origin[ 3 ];\n\n origin[0] = 0.0; \/\/ coordinates of the \n origin[1] = 0.0; \/\/ first pixel in N-D\n origin[2] = 0.0;\n\n image->SetOrigin( origin );\n\n return 0;\n\n}\n\nENH: Use of the PhysicalPointToIndex method added.#include \"itkImage.h\"\n#include \"itkPoint.h\"\n\nint main()\n{\n\n typedef itk::Image< unsigned short, 3 > ImageType;\n\n ImageType::Pointer image = ImageType::New();\n\n ImageType::IndexType start;\n ImageType::SizeType size;\n\n size[0] = 200; \/\/ size along X\n size[1] = 200; \/\/ size along Y\n size[2] = 200; \/\/ size along Z\n\n start[0] = 0; \/\/ first index on X\n start[1] = 0; \/\/ first index on Y\n start[2] = 0; \/\/ first index on Z\n\n ImageType::RegionType region;\n \n image->SetRegions( region );\n image->Allocate();\n\n image->FillBuffer( 0 );\n\n double spacing[ 3 ];\n\n spacing[0] = 0.33; \/\/ spacing in millimeters\n spacing[1] = 0.33; \/\/ spacing in millimeters\n spacing[2] = 1.20; \/\/ spacing in millimeters\n\n image->SetSpacing( spacing );\n\n double origin[ 3 ];\n\n origin[0] = 0.0; \/\/ coordinates of the \n origin[1] = 0.0; \/\/ first pixel in N-D\n origin[2] = 0.0;\n\n image->SetOrigin( origin );\n\n typedef itk::Point PointType;\n \n PointType point;\n\n point[0] = 1.45;\n point[1] = 7.21;\n point[2] = 9.28;\n\n ImageType::IndexType index;\n\n image->TransformPhysicalPointToIndex( point, index ); \n\n return 0;\n\n}\n\n<|endoftext|>"} {"text":"Fix a race condition in async_loader_stdlib.cpp.<|endoftext|>"} {"text":"#include \"catch.hpp\"\n\n#include \"libirc\/wilson.h\"\n\n#include \"libirc\/atom.h\"\n#include \"libirc\/connectivity.h\"\n#include \"libirc\/conversion.h\"\n#include \"libirc\/io.h\"\n#include \"libirc\/molecule.h\"\n\n#include \"config.h\"\n\n#include \n#include \n\n#ifdef HAVE_ARMA\n#include \nusing vec3 = arma::vec3;\nusing vec = arma::vec;\nusing mat = arma::mat;\n#elif HAVE_EIGEN3\n#include \nusing vec3 = Eigen::Vector3d;\nusing vec = Eigen::VectorXd;\nusing mat = Eigen::MatrixXd;\n#else\n#error\n#endif\n\nusing namespace irc;\n\nTEST_CASE(\"Wilson B matrix\", \"[wilson]\") {\n\n bool verbose{true};\n\n using namespace std;\n\n using namespace connectivity;\n using namespace molecule;\n using namespace wilson;\n using namespace tools;\n\n SECTION(\"H2 stretching\") {\n\n \/\/ Define molecule\n Molecule mol{{\"H\", {0., 0., 0.}}, {\"H\", {1., 0., 0.}}};\n\n \/\/ Compute interatomic distances\n mat dd{distances(mol)};\n\n \/\/ Compute adjacency matrix (graph)\n UGraph adj{adjacency_matrix(dd, mol)};\n\n \/\/ Compute distance matrix and predecessor matrix\n mat dist, pred;\n tie(dist, pred) = distance_matrix(adj);\n\n \/\/ Compute bonds\n vector B{bonds(dist, mol)};\n\n REQUIRE(B.size() == 1);\n\n \/\/ Compute Wilson B matrix for H2 analytically\n mat Bwilson =\n wilson_matrix(to_cartesian(mol), B);\n\n \/\/ Check Wilson B matrix size\n REQUIRE(linalg::size(Bwilson) == 6);\n\n if (verbose) {\n cout << \"Wilson B matrix (analytical):\" << endl;\n cout << Bwilson << endl;\n }\n\n \/\/ Compute Wilson B matrix for H2 numerically\n mat BwilsonN = wilson_matrix_numerical(\n to_cartesian(mol), B);\n\n \/\/ Check Wilson B matrix size\n REQUIRE(linalg::size(BwilsonN) == 6);\n\n if (verbose) {\n cout << \"Wilson B matrix (numerical):\" << endl;\n cout << BwilsonN << endl;\n }\n\n \/\/ Check analytical and numerical Wilson matrices are the same\n SECTION(\"Analytical vs Numerical\") {\n for (size_t i{0}; i < 6; i++) {\n Approx target{BwilsonN(i)};\n target.margin(1e-6);\n\n REQUIRE(Bwilson(i) == target);\n }\n }\n\n \/\/ Set bond stretching\n double d{0.01};\n vec dx{-d, 0.00, 0.00, d, 0.00, 0.00};\n\n SECTION(\"Bond change (analytical)\") {\n \/\/ Compute transformation in IRC\n vec transformation{Bwilson * dx};\n\n if (verbose) {\n cout << \"\\nTransformation (analytical)\" << endl;\n cout << Bwilson * dx << endl;\n }\n\n Approx target{2 * d};\n target.margin(1e-5);\n\n REQUIRE(transformation(0) == target);\n }\n\n SECTION(\"Bond change (numerical)\") {\n \/\/ Compute transformation in IRC\n vec transformation{BwilsonN * dx};\n\n if (verbose) {\n cout << \"\\nTransformation (numerical)\" << endl;\n cout << Bwilson * dx << endl;\n }\n\n Approx target{2 * d};\n target.margin(1e-5);\n\n REQUIRE(transformation(0) == target);\n }\n } \/\/ H2 stretching\n\n SECTION(\"H2O bending\") {\n\n double angle(0.5);\n double angle_rad(angle \/ 180. * constants::pi);\n\n std::vector R{\n {\/\/ Rotation for H1\n {cos(angle_rad), -sin(angle_rad), 0},\n {sin(angle_rad), cos(angle_rad), 0},\n {0, 0, 1}},\n {\/\/ Rotation for O\n {1, 0, 0},\n {0, 1, 0},\n {0, 0, 1}},\n {\/\/ Rotation for H2\n {cos(-angle_rad), -sin(-angle_rad), 0},\n {sin(-angle_rad), cos(-angle_rad), 0},\n {0, 0, 1}},\n };\n\n Molecule mol{\n {\"H\", {1.43, -1.10, 0.00}}, \/\/ H1\n {\"O\", {0.00, 0.00, 0.00}}, \/\/ O\n {\"H\", {-1.43, -1.10, 0.00}} \/\/ H2\n };\n\n \/\/ Allocate displacements in cartesian coordinates\n vec dx{linalg::zeros(3 * mol.size())};\n\n \/\/ Compute displacements\n for (size_t i{0}; i < 3; i++) {\n vec3 v{R[i] * mol[i].position - mol[i].position};\n\n dx(3 * i + 0) = v(0);\n dx(3 * i + 1) = v(1);\n dx(3 * i + 2) = v(2);\n }\n\n \/\/ Compute interatomic distances\n mat dd{distances(mol)};\n\n \/\/ Compute adjacency matrix (graph)\n UGraph adj{adjacency_matrix(dd, mol)};\n\n \/\/ Compute distance matrix and predecessor matrix\n mat dist, pred;\n tie(dist, pred) = distance_matrix(adj);\n\n \/\/ Compute bonds\n vector B{bonds(dist, mol)};\n\n \/\/ Check number of bonds\n REQUIRE(B.size() == 2);\n\n \/\/ Compute bonds\n vector A{angles(dist, pred, mol)};\n\n REQUIRE(A.size() == 1);\n\n \/\/ Compute Wilson B matrix for H2O analytically\n mat Bwilson =\n wilson_matrix(to_cartesian(mol), B, A);\n\n \/\/ Check Wilson B matrix size\n REQUIRE(linalg::size(Bwilson) == 27);\n\n if (verbose) {\n \/\/ Print Wilson B matrix\n cout << \"\\nWilson B matrix (analytical):\" << endl;\n cout << Bwilson << endl;\n }\n\n \/\/ Compute Wilson B matrix for H2O numerically\n mat BwilsonN = wilson_matrix_numerical(\n to_cartesian(mol), B, A);\n\n \/\/ Check Wilson B matrix size\n REQUIRE(linalg::size(BwilsonN) == 27);\n\n if (verbose) {\n \/\/ Print Wilson B matrix\n cout << \"\\nWilson B matrix (numerical):\" << endl;\n cout << BwilsonN << endl;\n }\n\n \/\/ Check analytical and numerical Wilson matrices are the same\n SECTION(\"Analytical vs Numerical\") {\n for (size_t i{0}; i < 27; i++) {\n Approx target{BwilsonN(i)};\n target.margin(1e-6);\n\n REQUIRE(Bwilson(i) == target);\n }\n }\n\n SECTION(\"Analytical displacement\") {\n \/\/ Compute displacement in internal coordinates\n vec displacement{Bwilson * dx};\n cout << \"\\nDisplacement:\" << endl;\n cout << displacement << endl;\n\n \/\/ Check that bonds do not change\n SECTION(\"Bond change\") {\n Approx target{0};\n\n target.margin(1e-4);\n\n REQUIRE(displacement(0) == target);\n REQUIRE(displacement(1) == target);\n }\n\n \/\/ Check change in angle\n SECTION(\"Angle change\") {\n Approx target{2 * angle};\n\n target.margin(1e-3);\n\n REQUIRE(displacement(2) * 180 \/ constants::pi == target);\n }\n }\n }\n\n SECTION(\"H2O2 torsion\") {\n\n double angle(1.0);\n double angle_rad(angle \/ 180. * constants::pi);\n\n mat R{{cos(angle_rad), -sin(angle_rad), 0},\n {sin(angle_rad), cos(angle_rad), 0},\n {0, 0, 1}};\n\n molecule::Molecule molecule{\n {\"H\", {0.000, 0.947, -0.079}}, \/\/ H1\n {\"O\", {0.000, 0.000, 0.000}}, \/\/ O1\n {\"O\", {0.000, 0.000, 1.474}}, \/\/ O2\n {\"H\", {-0.854, -0.407, 1.553}} \/\/ H2\n };\n\n \/\/ Transform molecular coordinates from angstrom to bohr\n molecule::multiply_positions(molecule, conversion::angstrom_to_bohr);\n\n \/\/ Allocate displacements in cartesian coordinates\n vec dx{linalg::zeros(3 * molecule.size())};\n\n \/\/ Compute transformation for H1 rotation\n vec3 v{R * molecule[0].position - molecule[0].position};\n dx(0) = v(0);\n dx(1) = v(1);\n dx(2) = v(2);\n\n \/\/ Compute old dihedral (before rotation)\n double d_old{dihedral(molecule[0].position,\n molecule[1].position,\n molecule[2].position,\n molecule[3].position)};\n\n \/\/ Compute new dihedral angle (after rotation)\n double d_new{dihedral(R * molecule[0].position,\n molecule[1].position,\n molecule[2].position,\n molecule[3].position)};\n\n \/\/ Compute dihedral variation\n double d_diff{d_new - d_old};\n\n \/\/ Compute interatomic distances\n mat dd{distances(molecule)};\n\n \/\/ Compute adjacency matrix (graph)\n UGraph adj{adjacency_matrix(dd, molecule)};\n\n \/\/ Compute distance matrix and predecessor matrix\n mat dist, predecessors;\n tie(dist, predecessors) = distance_matrix(adj);\n\n \/\/ Compute bonds\n vector B{bonds(dist, molecule)};\n\n \/\/ Check number of bonds\n REQUIRE(B.size() == 3);\n\n \/\/ Compute angles\n vector A{angles(dist, predecessors, molecule)};\n\n \/\/ Check number of angles\n REQUIRE(A.size() == 2);\n\n \/\/ Compute dihedrals\n vector D{dihedrals(dist, predecessors, molecule)};\n\n \/\/ Check number of dihedrals\n REQUIRE(D.size() == 1);\n\n \/\/ Compute Wilson's B matrix\n mat Bwilson = wilson_matrix(\n to_cartesian(molecule), B, A, D);\n\n REQUIRE(linalg::size(Bwilson) == 72);\n\n if (verbose) {\n \/\/ Print Wilson B matrix\n cout << \"\\nWilson B matrix (analytical):\" << endl;\n cout << Bwilson << endl;\n }\n\n \/\/ Compute Wilson's B matrix\n mat BwilsonN = wilson_matrix_numerical(\n to_cartesian(molecule), B, A, D);\n\n REQUIRE(linalg::size(BwilsonN) == 72);\n\n if (verbose) {\n \/\/ Print Wilson B matrix\n cout << \"\\nWilson B matrix (numerical):\" << endl;\n cout << BwilsonN << endl;\n }\n\n \/\/ Check analytical and numerical Wilson matrices are the same\n SECTION(\"Analytical vs Numerical\") {\n for (size_t i{0}; i < 72; i++) {\n Approx target{BwilsonN(i)};\n target.margin(1e-6);\n\n REQUIRE(Bwilson(i) == target);\n }\n }\n\n SECTION(\"Analytical displacements\") {\n \/\/ Compute displacement in internal coordinates\n vec displacement{Bwilson * dx};\n\n \/\/ Print displacements\n if (verbose) {\n cout << \"\\nDisplacement (analytical):\" << endl;\n cout << displacement << endl;\n }\n\n \/\/ Check that bonds do not change\n SECTION(\"Bonds change\") {\n Approx target{0};\n\n target.margin(1e-3);\n\n REQUIRE(displacement(0) == target);\n REQUIRE(displacement(1) == target);\n REQUIRE(displacement(2) == target);\n }\n\n \/\/ Check change in angle\n SECTION(\"Angles change\") {\n Approx target{0};\n\n target.margin(1e-4);\n\n REQUIRE(displacement(3) == target);\n REQUIRE(displacement(4) == target);\n }\n\n \/\/ Check change in angle\n SECTION(\"Dihedral change\") {\n Approx target{d_diff};\n\n target.margin(1e-4);\n\n REQUIRE(displacement(5) == target);\n }\n }\n\n SECTION(\"Numerical displacements\") {\n \/\/ Compute displacement in internal coordinates\n vec displacement{BwilsonN * dx};\n\n \/\/ Print displacements\n if (verbose) {\n cout << \"\\nDisplacement (numerical):\" << endl;\n cout << displacement << endl;\n }\n\n \/\/ Check that bonds do not change\n SECTION(\"Bonds change\") {\n Approx target{0};\n\n target.margin(1e-3);\n\n REQUIRE(displacement(0) == target);\n REQUIRE(displacement(1) == target);\n REQUIRE(displacement(2) == target);\n }\n\n \/\/ Check change in angle\n SECTION(\"Angles change\") {\n Approx target{0};\n\n target.margin(1e-4);\n\n REQUIRE(displacement(3) == target);\n REQUIRE(displacement(4) == target);\n }\n\n \/\/ Check change in angle\n SECTION(\"Dihedral change\") {\n Approx target{d_diff};\n\n target.margin(1e-4);\n\n REQUIRE(displacement(5) == target);\n }\n }\n }\n}\n\nTEST_CASE(\"Wilson\") {\n using namespace std;\n\n using namespace connectivity;\n using namespace molecule;\n using namespace tools;\n using namespace wilson;\n\n bool verbose{true};\n\n Molecule mol{\n io::load_xyz(config::molecules_dir + \"water_dimer_2.xyz\")};\n\n \/\/ Transform molecule to bohr\n multiply_positions(mol, conversion::angstrom_to_bohr);\n\n \/\/ Compute interatomic distances\n mat dd{distances(mol)};\n\n \/\/ Compute adjacency matrix (graph)\n UGraph adj{adjacency_matrix(dd, mol)};\n\n \/\/ Compute distance matrix and predecessor matrix\n mat dist, predecessors;\n tie(dist, predecessors) = distance_matrix(adj);\n\n \/\/ Compute bonds\n vector B{bonds(dist, mol)};\n\n \/\/ Compute angles\n vector A{angles(dist, predecessors, mol)};\n\n \/\/ Compute dihedrals\n vector D{dihedrals(dist, predecessors, mol)};\n\n cout << \"q =\\n\"\n << connectivity::cartesian_to_irc(\n to_cartesian(mol), B, A, D)\n << endl;\n\n \/\/ Return Wilson's B matrix (analytical)\n mat WB{wilson_matrix(to_cartesian(mol), B, A, D)};\n\n if (verbose) {\n cout << \"B (analytical) =\\n\" << WB << endl;\n }\n\n \/\/ Return Wilson's B matrix (numerical)\n mat WBN{wilson_matrix_numerical(\n to_cartesian(mol), B, A, D)};\n\n if (verbose) {\n cout << \"B (numerical) =\\n\" << WBN << endl;\n }\n\n size_t n{linalg::size(WB)};\n for (size_t i{0}; i < n; i++) {\n Approx target(WBN(i));\n target.margin(1e-5);\n\n REQUIRE(WB(i) == target);\n }\n}Reduce LOC in wilson test#include \"catch.hpp\"\n\n#include \"libirc\/wilson.h\"\n\n#include \"libirc\/atom.h\"\n#include \"libirc\/connectivity.h\"\n#include \"libirc\/conversion.h\"\n#include \"libirc\/io.h\"\n#include \"libirc\/molecule.h\"\n\n#include \"config.h\"\n\n#include \n\n#ifdef HAVE_ARMA\n#include \nusing vec3 = arma::vec3;\nusing vec = arma::vec;\nusing mat = arma::mat;\n#elif HAVE_EIGEN3\n#include \nusing vec3 = Eigen::Vector3d;\nusing vec = Eigen::VectorXd;\nusing mat = Eigen::MatrixXd;\n#else\n#error\n#endif\n\nusing namespace irc;\n\nTEST_CASE(\"Wilson B matrix for single fragments\", \"[wilson]\") {\n using namespace connectivity;\n using namespace molecule;\n using namespace wilson;\n using namespace tools;\n\n SECTION(\"H2 stretching\") {\n \/\/ Define molecule\n Molecule mol{{\"H\", {0., 0., 0.}}, {\"H\", {1., 0., 0.}}};\n \/\/ Molecular connectivity\n mat dd{distances(mol)};\n UGraph adj{adjacency_matrix(dd, mol)};\n mat dist, pred;\n std::tie(dist, pred) = distance_matrix(adj);\n\n \/\/ Compute bonds\n std::vector B{bonds(dist, mol)};\n REQUIRE(B.size() == 1);\n\n \/\/ Compute Wilson B matrix for H2 analytically\n mat Bwilson =\n wilson_matrix(to_cartesian(mol), B);\n\n \/\/ Check Wilson B matrix size\n INFO(\"Wilson B matrix (analytical):\\n\" << Bwilson);\n REQUIRE(linalg::size(Bwilson) == 6);\n\n \/\/ Compute Wilson B matrix for H2 numerically\n mat BwilsonN = wilson_matrix_numerical(\n to_cartesian(mol), B);\n\n \/\/ Check Wilson B matrix size\n INFO(\"Wilson B matrix (numerical):\\n\" << BwilsonN);\n REQUIRE(linalg::size(BwilsonN) == 6);\n\n \/\/ Check analytical and numerical Wilson matrices are the same\n INFO(\"Analytical vs Numerical\");\n for (size_t i{0}; i < 6; i++) \n REQUIRE(Bwilson(i) == Approx(BwilsonN(i)).margin(1e-6));\n\n INFO(\"Transformation with bond stretch\");\n const double d{0.01};\n vec dx{-d, 0.00, 0.00, d, 0.00, 0.00};\n\n INFO(\"Analytical transformation\");\n vec analytical_transformation = Bwilson * dx;\n CAPTURE(analytical_transformation);\n REQUIRE(analytical_transformation(0) == Approx(2*d).margin(1e-5));\n\n INFO(\"Numerical transformation\");\n vec numerical_transformation = BwilsonN * dx;\n CAPTURE(numerical_transformation);\n REQUIRE(numerical_transformation(0) == Approx(2*d).margin(1e-5));\n } \/\/ H2 stretching\n\n SECTION(\"H2O bending\") {\n\n double angle(0.5);\n double angle_rad(angle \/ 180. * constants::pi);\n\n const std::vector R{\n {\/\/ Rotation for H1\n {cos(angle_rad), -sin(angle_rad), 0},\n {sin(angle_rad), cos(angle_rad), 0},\n {0, 0, 1}},\n {\/\/ Rotation for O\n {1, 0, 0},\n {0, 1, 0},\n {0, 0, 1}},\n {\/\/ Rotation for H2\n {cos(-angle_rad), -sin(-angle_rad), 0},\n {sin(-angle_rad), cos(-angle_rad), 0},\n {0, 0, 1}},\n };\n\n const Molecule mol{\n {\"H\", {1.43, -1.10, 0.00}}, \/\/ H1\n {\"O\", {0.00, 0.00, 0.00}}, \/\/ O\n {\"H\", {-1.43, -1.10, 0.00}} \/\/ H2\n };\n\n \/\/ Allocate displacements in cartesian coordinates\n vec dx{linalg::zeros(3 * mol.size())};\n\n \/\/ Compute displacements\n for (size_t i{0}; i < 3; i++) {\n vec3 v{R[i] * mol[i].position - mol[i].position};\n\n dx(3 * i + 0) = v(0);\n dx(3 * i + 1) = v(1);\n dx(3 * i + 2) = v(2);\n }\n\n \/\/ Molecular connectivity\n mat dd{distances(mol)};\n UGraph adj{adjacency_matrix(dd, mol)};\n mat dist, pred;\n std::tie(dist, pred) = distance_matrix(adj);\n\n \/\/ Compute bonds\n const auto B = bonds(dist, mol);\n REQUIRE(B.size() == 2);\n\n \/\/ Compute angles\n const auto A = angles(dist, pred, mol);\n REQUIRE(A.size() == 1);\n\n \/\/ Compute Wilson B matrix for H2O analytically\n mat Bwilson =\n wilson_matrix(to_cartesian(mol), B, A);\n REQUIRE(linalg::size(Bwilson) == 27);\n INFO(\"Wilson B matrix (analytical):\\n\" << Bwilson);\n\n \/\/ Compute Wilson B matrix for H2O numerically\n const mat BwilsonN = wilson_matrix_numerical(\n to_cartesian(mol), B, A);\n REQUIRE(linalg::size(BwilsonN) == 27);\n INFO(\"Wilson B matrix (numerical):\\n\" << BwilsonN);\n\n \/\/ Check analytical and numerical Wilson matrices are the same\n for (size_t i{0}; i < 27; i++)\n REQUIRE(Bwilson(i) == Approx(BwilsonN(i)).margin(1e-6));\n\n INFO(\"Compute displacements in internal coordinates\");\n const vec displacement = Bwilson * dx;\n CAPTURE(displacement);\n\n INFO(\"Check bond change\");\n REQUIRE(displacement(0) == Approx(0).margin(1e-4));\n REQUIRE(displacement(1) == Approx(0).margin(1e-4));\n\n INFO(\"Check angle change\");\n REQUIRE(displacement(2) == Approx(2*angle_rad).margin(1e-3));\n }\n\n SECTION(\"H2O2 torsion\") {\n\n const double angle(1.0);\n const double angle_rad(angle \/ 180. * constants::pi);\n\n const mat R{{cos(angle_rad), -sin(angle_rad), 0},\n {sin(angle_rad), cos(angle_rad), 0},\n {0, 0, 1}};\n\n molecule::Molecule molecule{\n {\"H\", {0.000, 0.947, -0.079}}, \/\/ H1\n {\"O\", {0.000, 0.000, 0.000}}, \/\/ O1\n {\"O\", {0.000, 0.000, 1.474}}, \/\/ O2\n {\"H\", {-0.854, -0.407, 1.553}} \/\/ H2\n };\n molecule::multiply_positions(molecule, conversion::angstrom_to_bohr);\n\n \/\/ Allocate displacements in cartesian coordinates\n vec dx{linalg::zeros(3 * molecule.size())};\n\n \/\/ Compute transformation for H1 rotation\n vec3 v{R * molecule[0].position - molecule[0].position};\n dx(0) = v(0);\n dx(1) = v(1);\n dx(2) = v(2);\n\n \/\/ Compute old dihedral (before rotation)\n double d_old{dihedral(molecule[0].position,\n molecule[1].position,\n molecule[2].position,\n molecule[3].position)};\n\n \/\/ Compute new dihedral angle (after rotation)\n double d_new{dihedral(R * molecule[0].position,\n molecule[1].position,\n molecule[2].position,\n molecule[3].position)};\n\n \/\/ Compute dihedral variation\n double d_diff{d_new - d_old};\n\n \/\/ Compute interatomic distances\n mat dd{distances(molecule)};\n UGraph adj{adjacency_matrix(dd, molecule)};\n mat dist, predecessors;\n std::tie(dist, predecessors) = distance_matrix(adj);\n\n \/\/ Compute bonds, angles and dihedrals\n const std::vector B{bonds(dist, molecule)};\n REQUIRE(B.size() == 3);\n const std::vector A{angles(dist, predecessors, molecule)};\n REQUIRE(A.size() == 2);\n const std::vector D{dihedrals(dist, predecessors, molecule)};\n REQUIRE(D.size() == 1);\n\n \/\/ Compute Wilson's B matrix\n const mat Bwilson = wilson_matrix(\n to_cartesian(molecule), B, A, D);\n REQUIRE(linalg::size(Bwilson) == 72);\n INFO(\"Wilson B matrix (analytical):\\n\" << Bwilson);\n\n \/\/ Compute Wilson's B matrix\n const mat BwilsonN = wilson_matrix_numerical(\n to_cartesian(molecule), B, A, D);\n REQUIRE(linalg::size(BwilsonN) == 72);\n INFO(\"Wilson B matrix (numerical):\\n\" << BwilsonN);\n\n \/\/ Check analytical and numerical Wilson matrices are the same\n INFO(\"Check Analytical vs Numerical Wilson B matrix\");\n for (size_t i{0}; i < 72; i++) {\n REQUIRE(Bwilson(i) == Approx(BwilsonN(i)).margin(1e-6));\n }\n\n SECTION(\"Analytical displacements\") {\n \/\/ Compute displacement in internal coordinates\n const vec displacement{Bwilson * dx};\n INFO(\"Displacement (analytical):\\n\" << displacement);\n\n INFO(\"Bonds do not change\");\n REQUIRE(displacement(0) == Approx(0).margin(1e-3));\n REQUIRE(displacement(1) == Approx(0).margin(1e-3));\n REQUIRE(displacement(2) == Approx(0).margin(1e-3));\n \n INFO(\"Angles do not change\");\n REQUIRE(displacement(3) == Approx(0).margin(1e-4));\n REQUIRE(displacement(4) == Approx(0).margin(1e-4));\n\n INFO(\"Dihedral should change\");\n REQUIRE(displacement(5) == Approx(d_diff).margin(1e-4));\n }\n\n SECTION(\"Numerical displacements\") {\n \/\/ Compute displacement in internal coordinates\n const vec displacement{BwilsonN * dx};\n INFO(\"Displacement (numerical):\\n\" << displacement);\n\n INFO(\"Bonds do not change\");\n REQUIRE(displacement(0) == Approx(0).margin(1e-3));\n REQUIRE(displacement(1) == Approx(0).margin(1e-3));\n REQUIRE(displacement(2) == Approx(0).margin(1e-3));\n \n INFO(\"Angles do not change\");\n REQUIRE(displacement(3) == Approx(0).margin(1e-4));\n REQUIRE(displacement(4) == Approx(0).margin(1e-4));\n\n INFO(\"Dihedral should change\");\n REQUIRE(displacement(5) == Approx(d_diff).margin(1e-4));\n }\n }\n}\n\nTEST_CASE(\"Wilson B matrix for water dimer\", \"[wilson]\") {\n using namespace connectivity;\n using namespace molecule;\n using namespace tools;\n using namespace wilson;\n using namespace io;\n\n Molecule mol = load_xyz(config::molecules_dir + \"water_dimer_2.xyz\");\n multiply_positions(mol, conversion::angstrom_to_bohr);\n\n \/\/ Compute interatomic distances\n mat dd{distances(mol)};\n UGraph adj{adjacency_matrix(dd, mol)};\n mat dist, predecessors;\n std::tie(dist, predecessors) = distance_matrix(adj);\n\n \/\/ Compute bonds\n std::vector B{bonds(dist, mol)};\n std::vector A{angles(dist, predecessors, mol)};\n std::vector D{dihedrals(dist, predecessors, mol)};\n\n const auto q = connectivity::cartesian_to_irc(\n to_cartesian(mol), B, A, D);\n CAPTURE(q);\n\n const mat wilson_b_analytical =\n wilson_matrix(to_cartesian(mol), B, A, D);\n CAPTURE(wilson_b_analytical);\n\n const mat wilson_b_numerical =\n wilson_matrix_numerical(to_cartesian(mol), B, A, D);\n CAPTURE(wilson_b_numerical);\n\n REQUIRE(linalg::size(wilson_b_analytical) == linalg::size(wilson_b_numerical));\n\n const size_t n = linalg::size(wilson_b_analytical);\n for (size_t i{0}; i < n; i++) {\n REQUIRE(wilson_b_analytical(i) == Approx(wilson_b_numerical(i)).margin(1e-5));\n }\n}\n<|endoftext|>"} {"text":" -- Remove the setup for the telemetry service.<|endoftext|>"} {"text":"\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2021 Filipe Coelho \n *\n * Permission to use, copy, modify, and\/or distribute this software for any purpose with\n * or without fee is hereby granted, provided that the above copyright notice and this\n * permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN\n * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\n * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef DISTRHO_UI_PRIVATE_DATA_HPP_INCLUDED\n#define DISTRHO_UI_PRIVATE_DATA_HPP_INCLUDED\n\n#include \"..\/DistrhoUI.hpp\"\n#include \"..\/..\/dgl\/Application.hpp\"\n\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n# include \"..\/..\/dgl\/src\/WindowPrivateData.hpp\"\n# include \"..\/..\/dgl\/src\/pugl.hpp\"\n#endif\n\n#if defined(DISTRHO_PLUGIN_TARGET_JACK) || defined(DISTRHO_PLUGIN_TARGET_DSSI)\n# define DISTRHO_UI_IS_STANDALONE 1\n#else\n# define DISTRHO_UI_IS_STANDALONE 0\n#endif\n\n#if defined(DISTRHO_PLUGIN_TARGET_VST2)\n# undef DISTRHO_UI_USER_RESIZABLE\n# define DISTRHO_UI_USER_RESIZABLE 0\n#endif\n\n\/\/ -----------------------------------------------------------------------\n\nSTART_NAMESPACE_DGL\n\n\/\/ -----------------------------------------------------------------------\n\/\/ Plugin Application, will set class name based on plugin details\n\nclass PluginApplication : public Application\n{\npublic:\n explicit PluginApplication()\n : Application(DISTRHO_UI_IS_STANDALONE)\n {\n const char* const className = (\n#ifdef DISTRHO_PLUGIN_BRAND\n DISTRHO_PLUGIN_BRAND\n#else\n DISTRHO_MACRO_AS_STRING(DISTRHO_NAMESPACE)\n#endif\n \"-\" DISTRHO_PLUGIN_NAME\n );\n setClassName(className);\n }\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginApplication)\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ Plugin Window, will pass some Window events to UI\n\n#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n\/\/ TODO external ui stuff\nclass PluginWindow\n{\n DISTRHO_NAMESPACE::UI* const ui;\n\npublic:\n explicit PluginWindow(DISTRHO_NAMESPACE::UI* const uiPtr,\n PluginApplication& app,\n const uintptr_t parentWindowHandle,\n const uint width,\n const uint height,\n const double scaleFactor)\n : Window(app, parentWindowHandle, width, height, scaleFactor, DISTRHO_UI_USER_RESIZABLE),\n ui(uiPtr) {}\n\n uint getWidth() const noexcept\n {\n return ui->getWidth();\n }\n\n uint getHeight() const noexcept\n {\n return ui->getHeight();\n }\n\n bool isVisible() const noexcept\n {\n return ui->isRunning();\n }\n\n uintptr_t getNativeWindowHandle() const noexcept\n {\n return 0;\n }\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginWindow)\n};\n#else\nclass PluginWindow : public Window\n{\n DISTRHO_NAMESPACE::UI* const ui;\n\npublic:\n explicit PluginWindow(DISTRHO_NAMESPACE::UI* const uiPtr,\n PluginApplication& app,\n const uintptr_t parentWindowHandle,\n const uint width,\n const uint height,\n const double scaleFactor)\n : Window(app, parentWindowHandle, width, height, scaleFactor, DISTRHO_UI_USER_RESIZABLE),\n ui(uiPtr)\n {\n puglBackendEnter(pData->view);\n }\n\n void leaveContext()\n {\n puglBackendLeave(pData->view);\n }\n\nprotected:\n void onFocus(const bool focus, const DGL_NAMESPACE::CrossingMode mode) override\n {\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n ui->uiFocus(focus, mode);\n }\n\n void onReshape(const uint width, const uint height) override\n {\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n ui->uiReshape(width, height);\n }\n\n void onScaleFactorChanged(const double scaleFactor) override\n {\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n ui->uiScaleFactorChanged(scaleFactor);\n }\n\n# ifndef DGL_FILE_BROWSER_DISABLED\n void onFileSelected(const char* filename) override;\n# endif\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginWindow)\n};\n#endif \/\/ !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n\nEND_NAMESPACE_DGL\n\n\/\/ -----------------------------------------------------------------------\n\nSTART_NAMESPACE_DISTRHO\n\nusing DGL_NAMESPACE::PluginApplication;\nusing DGL_NAMESPACE::PluginWindow;\n\n\/\/ -----------------------------------------------------------------------\n\/\/ UI callbacks\n\ntypedef void (*editParamFunc) (void* ptr, uint32_t rindex, bool started);\ntypedef void (*setParamFunc) (void* ptr, uint32_t rindex, float value);\ntypedef void (*setStateFunc) (void* ptr, const char* key, const char* value);\ntypedef void (*sendNoteFunc) (void* ptr, uint8_t channel, uint8_t note, uint8_t velo);\ntypedef void (*setSizeFunc) (void* ptr, uint width, uint height);\ntypedef bool (*fileRequestFunc) (void* ptr, const char* key);\n\n\/\/ -----------------------------------------------------------------------\n\/\/ UI private data\n\nstruct UI::PrivateData {\n \/\/ DGL\n PluginApplication app;\n ScopedPointer window;\n\n \/\/ DSP\n double sampleRate;\n uint32_t parameterOffset;\n void* dspPtr;\n\n \/\/ UI\n uint bgColor;\n uint fgColor;\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n double scaleFactor;\n uintptr_t winId;\n# ifndef DGL_FILE_BROWSER_DISABLED\n char* uiStateFileKeyRequest;\n# endif\n#endif\n\n \/\/ Callbacks\n void* callbacksPtr;\n editParamFunc editParamCallbackFunc;\n setParamFunc setParamCallbackFunc;\n setStateFunc setStateCallbackFunc;\n sendNoteFunc sendNoteCallbackFunc;\n setSizeFunc setSizeCallbackFunc;\n fileRequestFunc fileRequestCallbackFunc;\n\n PrivateData() noexcept\n : app(),\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n window(nullptr),\n#endif\n sampleRate(0),\n parameterOffset(0),\n dspPtr(nullptr),\n bgColor(0),\n fgColor(0xffffffff),\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n scaleFactor(1.0),\n winId(0),\n# ifndef DGL_FILE_BROWSER_DISABLED\n uiStateFileKeyRequest(nullptr),\n# endif\n#endif\n callbacksPtr(nullptr),\n editParamCallbackFunc(nullptr),\n setParamCallbackFunc(nullptr),\n setStateCallbackFunc(nullptr),\n sendNoteCallbackFunc(nullptr),\n setSizeCallbackFunc(nullptr),\n fileRequestCallbackFunc(nullptr)\n {\n#if defined(DISTRHO_PLUGIN_TARGET_DSSI) || defined(DISTRHO_PLUGIN_TARGET_LV2)\n parameterOffset += DISTRHO_PLUGIN_NUM_INPUTS + DISTRHO_PLUGIN_NUM_OUTPUTS;\n# if DISTRHO_PLUGIN_WANT_LATENCY\n parameterOffset += 1;\n# endif\n#endif\n\n#ifdef DISTRHO_PLUGIN_TARGET_LV2\n# if (DISTRHO_PLUGIN_WANT_MIDI_INPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || DISTRHO_PLUGIN_WANT_STATE)\n parameterOffset += 1;\n# endif\n# if (DISTRHO_PLUGIN_WANT_MIDI_OUTPUT || DISTRHO_PLUGIN_WANT_STATE)\n parameterOffset += 1;\n# endif\n#endif\n }\n\n ~PrivateData() noexcept\n {\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI && !defined(DGL_FILE_BROWSER_DISABLED)\n std::free(uiStateFileKeyRequest);\n#endif\n }\n\n void editParamCallback(const uint32_t rindex, const bool started)\n {\n if (editParamCallbackFunc != nullptr)\n editParamCallbackFunc(callbacksPtr, rindex, started);\n }\n\n void setParamCallback(const uint32_t rindex, const float value)\n {\n if (setParamCallbackFunc != nullptr)\n setParamCallbackFunc(callbacksPtr, rindex, value);\n }\n\n void setStateCallback(const char* const key, const char* const value)\n {\n if (setStateCallbackFunc != nullptr)\n setStateCallbackFunc(callbacksPtr, key, value);\n }\n\n void sendNoteCallback(const uint8_t channel, const uint8_t note, const uint8_t velocity)\n {\n if (sendNoteCallbackFunc != nullptr)\n sendNoteCallbackFunc(callbacksPtr, channel, note, velocity);\n }\n\n void setSizeCallback(const uint width, const uint height)\n {\n if (setSizeCallbackFunc != nullptr)\n setSizeCallbackFunc(callbacksPtr, width, height);\n }\n\n \/\/ implemented below, after PluginWindow\n bool fileRequestCallback(const char* const key);\n\n static UI::PrivateData* s_nextPrivateData;\n static PluginWindow& createNextWindow(UI* ui, uint width, uint height);\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ UI private data fileRequestCallback, which requires PluginWindow definitions\n\ninline bool UI::PrivateData::fileRequestCallback(const char* const key)\n{\n if (fileRequestCallbackFunc != nullptr)\n return fileRequestCallbackFunc(callbacksPtr, key);\n\n#if DISTRHO_PLUGIN_WANT_STATEFILES && !DISTRHO_PLUGIN_HAS_EXTERNAL_UI && !defined(DGL_FILE_BROWSER_DISABLED)\n std::free(uiStateFileKeyRequest);\n uiStateFileKeyRequest = strdup(key);\n DISTRHO_SAFE_ASSERT_RETURN(uiStateFileKeyRequest != nullptr, false);\n\n char title[0xff];\n snprintf(title, sizeof(title)-1u, DISTRHO_PLUGIN_NAME \": %s\", key);\n title[sizeof(title)-1u] = '\\0';\n\n DGL_NAMESPACE::Window::FileBrowserOptions opts;\n opts.title = title;\n return window->openFileBrowser(opts);\n#endif\n\n return false;\n}\n\nEND_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------\n\/\/ PluginWindow onFileSelected that require UI::PrivateData definitions\n\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI && !defined(DGL_FILE_BROWSER_DISABLED)\nSTART_NAMESPACE_DGL\n\ninline void PluginWindow::onFileSelected(const char* const filename)\n{\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n# if DISTRHO_PLUGIN_WANT_STATEFILES\n if (char* const key = ui->uiData->uiStateFileKeyRequest)\n {\n ui->uiData->uiStateFileKeyRequest = nullptr;\n \/\/ notify DSP\n ui->setState(key, filename != nullptr ? filename : \"\");\n \/\/ notify UI\n ui->stateChanged(key, filename != nullptr ? filename : \"\");\n std::free(key);\n return;\n }\n# endif\n\n ui->uiFileBrowserSelected(filename);\n}\n\nEND_NAMESPACE_DGL\n#endif\n\n\/\/ -----------------------------------------------------------------------\n\n#endif \/\/ DISTRHO_UI_PRIVATE_DATA_HPP_INCLUDED\nCorrections to d85add3a4c3434b51b822b416cfb963c6f878037\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2021 Filipe Coelho \n *\n * Permission to use, copy, modify, and\/or distribute this software for any purpose with\n * or without fee is hereby granted, provided that the above copyright notice and this\n * permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN\n * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER\n * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef DISTRHO_UI_PRIVATE_DATA_HPP_INCLUDED\n#define DISTRHO_UI_PRIVATE_DATA_HPP_INCLUDED\n\n#include \"..\/DistrhoUI.hpp\"\n#include \"..\/..\/dgl\/Application.hpp\"\n\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n# include \"..\/..\/dgl\/src\/WindowPrivateData.hpp\"\n# include \"..\/..\/dgl\/src\/pugl.hpp\"\n#endif\n\n#if defined(DISTRHO_PLUGIN_TARGET_JACK) || defined(DISTRHO_PLUGIN_TARGET_DSSI)\n# define DISTRHO_UI_IS_STANDALONE 1\n#else\n# define DISTRHO_UI_IS_STANDALONE 0\n#endif\n\n#if defined(DISTRHO_PLUGIN_TARGET_VST2)\n# undef DISTRHO_UI_USER_RESIZABLE\n# define DISTRHO_UI_USER_RESIZABLE 0\n#endif\n\n\/\/ -----------------------------------------------------------------------\n\nSTART_NAMESPACE_DGL\n\n\/\/ -----------------------------------------------------------------------\n\/\/ Plugin Application, will set class name based on plugin details\n\nclass PluginApplication : public Application\n{\npublic:\n explicit PluginApplication()\n : Application(DISTRHO_UI_IS_STANDALONE)\n {\n const char* const className = (\n#ifdef DISTRHO_PLUGIN_BRAND\n DISTRHO_PLUGIN_BRAND\n#else\n DISTRHO_MACRO_AS_STRING(DISTRHO_NAMESPACE)\n#endif\n \"-\" DISTRHO_PLUGIN_NAME\n );\n setClassName(className);\n }\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginApplication)\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ Plugin Window, will pass some Window events to UI\n\n#if DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n\/\/ TODO external ui stuff\nclass PluginWindow\n{\n DISTRHO_NAMESPACE::UI* const ui;\n\npublic:\n explicit PluginWindow(DISTRHO_NAMESPACE::UI* const uiPtr,\n PluginApplication& app,\n const uintptr_t parentWindowHandle,\n const uint width,\n const uint height,\n const double scaleFactor)\n : Window(app, parentWindowHandle, width, height, scaleFactor, DISTRHO_UI_USER_RESIZABLE),\n ui(uiPtr) {}\n\n uint getWidth() const noexcept\n {\n return ui->getWidth();\n }\n\n uint getHeight() const noexcept\n {\n return ui->getHeight();\n }\n\n bool isVisible() const noexcept\n {\n return ui->isRunning();\n }\n\n uintptr_t getNativeWindowHandle() const noexcept\n {\n return 0;\n }\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginWindow)\n};\n#else\nclass PluginWindow : public Window\n{\n DISTRHO_NAMESPACE::UI* const ui;\n\npublic:\n explicit PluginWindow(DISTRHO_NAMESPACE::UI* const uiPtr,\n PluginApplication& app,\n const uintptr_t parentWindowHandle,\n const uint width,\n const uint height,\n const double scaleFactor)\n : Window(app, parentWindowHandle, width, height, scaleFactor, DISTRHO_UI_USER_RESIZABLE),\n ui(uiPtr)\n {\n puglBackendEnter(pData->view);\n }\n\n void leaveContext()\n {\n puglBackendLeave(pData->view);\n }\n\nprotected:\n void onFocus(const bool focus, const DGL_NAMESPACE::CrossingMode mode) override\n {\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n ui->uiFocus(focus, mode);\n }\n\n void onReshape(const uint width, const uint height) override\n {\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n ui->uiReshape(width, height);\n }\n\n void onScaleFactorChanged(const double scaleFactor) override\n {\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n ui->uiScaleFactorChanged(scaleFactor);\n }\n\n# ifndef DGL_FILE_BROWSER_DISABLED\n void onFileSelected(const char* filename) override;\n# endif\n\n DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginWindow)\n};\n#endif \/\/ !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n\nEND_NAMESPACE_DGL\n\n\/\/ -----------------------------------------------------------------------\n\nSTART_NAMESPACE_DISTRHO\n\nusing DGL_NAMESPACE::PluginApplication;\nusing DGL_NAMESPACE::PluginWindow;\n\n\/\/ -----------------------------------------------------------------------\n\/\/ UI callbacks\n\ntypedef void (*editParamFunc) (void* ptr, uint32_t rindex, bool started);\ntypedef void (*setParamFunc) (void* ptr, uint32_t rindex, float value);\ntypedef void (*setStateFunc) (void* ptr, const char* key, const char* value);\ntypedef void (*sendNoteFunc) (void* ptr, uint8_t channel, uint8_t note, uint8_t velo);\ntypedef void (*setSizeFunc) (void* ptr, uint width, uint height);\ntypedef bool (*fileRequestFunc) (void* ptr, const char* key);\n\n\/\/ -----------------------------------------------------------------------\n\/\/ UI private data\n\nstruct UI::PrivateData {\n \/\/ DGL\n PluginApplication app;\n ScopedPointer window;\n\n \/\/ DSP\n double sampleRate;\n uint32_t parameterOffset;\n void* dspPtr;\n\n \/\/ UI\n uint bgColor;\n uint fgColor;\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n double scaleFactor;\n uintptr_t winId;\n# ifndef DGL_FILE_BROWSER_DISABLED\n char* uiStateFileKeyRequest;\n# endif\n#endif\n\n \/\/ Callbacks\n void* callbacksPtr;\n editParamFunc editParamCallbackFunc;\n setParamFunc setParamCallbackFunc;\n setStateFunc setStateCallbackFunc;\n sendNoteFunc sendNoteCallbackFunc;\n setSizeFunc setSizeCallbackFunc;\n fileRequestFunc fileRequestCallbackFunc;\n\n PrivateData() noexcept\n : app(),\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n window(nullptr),\n#endif\n sampleRate(0),\n parameterOffset(0),\n dspPtr(nullptr),\n bgColor(0),\n fgColor(0xffffffff),\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI\n scaleFactor(1.0),\n winId(0),\n# ifndef DGL_FILE_BROWSER_DISABLED\n uiStateFileKeyRequest(nullptr),\n# endif\n#endif\n callbacksPtr(nullptr),\n editParamCallbackFunc(nullptr),\n setParamCallbackFunc(nullptr),\n setStateCallbackFunc(nullptr),\n sendNoteCallbackFunc(nullptr),\n setSizeCallbackFunc(nullptr),\n fileRequestCallbackFunc(nullptr)\n {\n#if defined(DISTRHO_PLUGIN_TARGET_DSSI) || defined(DISTRHO_PLUGIN_TARGET_LV2)\n parameterOffset += DISTRHO_PLUGIN_NUM_INPUTS + DISTRHO_PLUGIN_NUM_OUTPUTS;\n# if DISTRHO_PLUGIN_WANT_LATENCY\n parameterOffset += 1;\n# endif\n#endif\n\n#ifdef DISTRHO_PLUGIN_TARGET_LV2\n# if (DISTRHO_PLUGIN_WANT_MIDI_INPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || DISTRHO_PLUGIN_WANT_STATE)\n parameterOffset += 1;\n# endif\n# if (DISTRHO_PLUGIN_WANT_MIDI_OUTPUT || DISTRHO_PLUGIN_WANT_STATE)\n parameterOffset += 1;\n# endif\n#endif\n }\n\n ~PrivateData() noexcept\n {\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI && !defined(DGL_FILE_BROWSER_DISABLED)\n std::free(uiStateFileKeyRequest);\n#endif\n }\n\n void editParamCallback(const uint32_t rindex, const bool started)\n {\n if (editParamCallbackFunc != nullptr)\n editParamCallbackFunc(callbacksPtr, rindex, started);\n }\n\n void setParamCallback(const uint32_t rindex, const float value)\n {\n if (setParamCallbackFunc != nullptr)\n setParamCallbackFunc(callbacksPtr, rindex, value);\n }\n\n void setStateCallback(const char* const key, const char* const value)\n {\n if (setStateCallbackFunc != nullptr)\n setStateCallbackFunc(callbacksPtr, key, value);\n }\n\n void sendNoteCallback(const uint8_t channel, const uint8_t note, const uint8_t velocity)\n {\n if (sendNoteCallbackFunc != nullptr)\n sendNoteCallbackFunc(callbacksPtr, channel, note, velocity);\n }\n\n void setSizeCallback(const uint width, const uint height)\n {\n if (setSizeCallbackFunc != nullptr)\n setSizeCallbackFunc(callbacksPtr, width, height);\n }\n\n \/\/ implemented below, after PluginWindow\n bool fileRequestCallback(const char* const key);\n\n static UI::PrivateData* s_nextPrivateData;\n static PluginWindow& createNextWindow(UI* ui, uint width, uint height);\n};\n\n\/\/ -----------------------------------------------------------------------\n\/\/ UI private data fileRequestCallback, which requires PluginWindow definitions\n\ninline bool UI::PrivateData::fileRequestCallback(const char* const key)\n{\n if (fileRequestCallbackFunc != nullptr)\n return fileRequestCallbackFunc(callbacksPtr, key);\n\n#if DISTRHO_PLUGIN_WANT_STATEFILES && !DISTRHO_PLUGIN_HAS_EXTERNAL_UI && !defined(DGL_FILE_BROWSER_DISABLED)\n std::free(uiStateFileKeyRequest);\n uiStateFileKeyRequest = strdup(key);\n DISTRHO_SAFE_ASSERT_RETURN(uiStateFileKeyRequest != nullptr, false);\n\n char title[0xff];\n snprintf(title, sizeof(title)-1u, DISTRHO_PLUGIN_NAME \": %s\", key);\n title[sizeof(title)-1u] = '\\0';\n\n DGL_NAMESPACE::Window::FileBrowserOptions opts;\n opts.title = title;\n return window->openFileBrowser(opts);\n#endif\n\n return false;\n}\n\nEND_NAMESPACE_DISTRHO\n\n\/\/ -----------------------------------------------------------------------\n\/\/ PluginWindow onFileSelected that require UI::PrivateData definitions\n\n#if !DISTRHO_PLUGIN_HAS_EXTERNAL_UI && !defined(DGL_FILE_BROWSER_DISABLED)\nSTART_NAMESPACE_DGL\n\ninline void PluginWindow::onFileSelected(const char* const filename)\n{\n DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,);\n\n# if DISTRHO_PLUGIN_WANT_STATEFILES\n if (char* const key = ui->uiData->uiStateFileKeyRequest)\n {\n ui->uiData->uiStateFileKeyRequest = nullptr;\n if (filename != nullptr)\n {\n \/\/ notify DSP\n ui->setState(key, filename);\n \/\/ notify UI\n ui->stateChanged(key, filename);\n }\n std::free(key);\n return;\n }\n# endif\n\n ui->uiFileBrowserSelected(filename);\n}\n\nEND_NAMESPACE_DGL\n#endif\n\n\/\/ -----------------------------------------------------------------------\n\n#endif \/\/ DISTRHO_UI_PRIVATE_DATA_HPP_INCLUDED\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2018 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \"graphics\/DataType.hpp\"\n#include \"graphics\/Vertex.hpp\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n class ShaderResource;\n\n class Shader final\n {\n public:\n struct ConstantInfo\n {\n ConstantInfo(const std::string& aName, DataType aDataType):\n name(aName), dataType(aDataType), size(getDataTypeSize(aDataType)) {}\n\n std::string name;\n DataType dataType;\n uint32_t size;\n };\n\n Shader();\n virtual ~Shader();\n\n Shader(const Shader&) = delete;\n Shader& operator=(const Shader&) = delete;\n\n Shader(Shader&&) = delete;\n Shader& operator=(Shader&&) = delete;\n\n bool init(const std::vector& newPixelShader,\n const std::vector& newVertexShader,\n const std::set& newVertexAttributes,\n const std::vector& newPixelShaderConstantInfo,\n const std::vector& newVertexShaderConstantInfo,\n uint32_t newPixelShaderDataAlignment = 0,\n uint32_t newVertexShaderDataAlignment = 0,\n const std::string& pixelShaderFunction = \"\",\n const std::string& vertexShaderFunction = \"\");\n bool init(const std::string& newPixelShader,\n const std::string& newVertexShader,\n const std::set& newVertexAttributes,\n const std::vector& newPixelShaderConstantInfo,\n const std::vector& newVertexShaderConstantInfo,\n uint32_t newPixelShaderDataAlignment = 0,\n uint32_t newVertexShaderDataAlignment = 0,\n const std::string& newPixelShaderFunction = \"\",\n const std::string& newVertexShaderFunction = \"\");\n\n inline ShaderResource* getResource() const { return resource; }\n\n const std::set& getVertexAttributes() const;\n\n private:\n ShaderResource* resource = nullptr;\n\n std::set vertexAttributes;\n\n std::string pixelShaderFilename;\n std::string vertexShaderFilename;\n };\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\nPromote the ConstantInfo struct to a class\/\/ Copyright (C) 2018 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \"graphics\/DataType.hpp\"\n#include \"graphics\/Vertex.hpp\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n class ShaderResource;\n\n class Shader final\n {\n public:\n class ConstantInfo\n {\n public:\n ConstantInfo(const std::string& aName, DataType aDataType):\n name(aName), dataType(aDataType), size(getDataTypeSize(aDataType)) {}\n\n std::string name;\n DataType dataType;\n uint32_t size;\n };\n\n Shader();\n virtual ~Shader();\n\n Shader(const Shader&) = delete;\n Shader& operator=(const Shader&) = delete;\n\n Shader(Shader&&) = delete;\n Shader& operator=(Shader&&) = delete;\n\n bool init(const std::vector& newPixelShader,\n const std::vector& newVertexShader,\n const std::set& newVertexAttributes,\n const std::vector& newPixelShaderConstantInfo,\n const std::vector& newVertexShaderConstantInfo,\n uint32_t newPixelShaderDataAlignment = 0,\n uint32_t newVertexShaderDataAlignment = 0,\n const std::string& pixelShaderFunction = \"\",\n const std::string& vertexShaderFunction = \"\");\n bool init(const std::string& newPixelShader,\n const std::string& newVertexShader,\n const std::set& newVertexAttributes,\n const std::vector& newPixelShaderConstantInfo,\n const std::vector& newVertexShaderConstantInfo,\n uint32_t newPixelShaderDataAlignment = 0,\n uint32_t newVertexShaderDataAlignment = 0,\n const std::string& newPixelShaderFunction = \"\",\n const std::string& newVertexShaderFunction = \"\");\n\n inline ShaderResource* getResource() const { return resource; }\n\n const std::set& getVertexAttributes() const;\n\n private:\n ShaderResource* resource = nullptr;\n\n std::set vertexAttributes;\n\n std::string pixelShaderFilename;\n std::string vertexShaderFilename;\n };\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"\/*\r\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\r\n *\/\r\n#ifndef\t_Stroia_Foundation_Execution_Exceptions_inl_\r\n#define\t_Stroia_Foundation_Execution_Exceptions_inl_\t1\r\n\r\n\r\n\/*\r\n ********************************************************************************\r\n ***************************** Implementation Details ***************************\r\n ********************************************************************************\r\n *\/\r\nnamespace\tStroika {\t\r\n\tnamespace\tFoundation {\r\n\t\tnamespace\tExecution {\r\n\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\/\/\tclass\tWin32ErrorException\r\n\t\t\tinline\tWin32ErrorException::Win32ErrorException (DWORD error):\r\n\t\t\t\tfError (error)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\tinline\tWin32ErrorException::operator DWORD () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fError;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\tWin32ErrorException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fError);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\t\t\/\/\tclass\tWin32StructuredException\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tWin32StructuredException::Win32StructuredException (unsigned int seCode):\r\n\t\t\t\tfSECode (seCode)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\tinline\tWin32StructuredException::operator unsigned int () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fSECode;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\tWin32StructuredException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fSECode);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\r\n\r\n\t\t\/\/\tclass\tHRESULTErrorException\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tHRESULTErrorException::HRESULTErrorException (HRESULT hresult):\r\n\t\t\t\tfHResult (hresult)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\tinline\tHRESULTErrorException::operator HRESULT () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fHResult;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\tHRESULTErrorException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fHResult);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\t\r\n\t\t\/\/\tclass\terrno_ErrorException\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\terrno_ErrorException::operator errno_t () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fError;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\terrno_ErrorException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fError);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\r\n\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\t\tvoid\t DoThrow (const T& e2Throw) \r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing exception: %s\", typeid (T).name ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\tvoid\t\tDoThrow (const T& e2Throw, const char* traceMsg)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"%s\", traceMsg);\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\tvoid\t\tDoThrow (const T& e2Throw, const wchar_t* traceMsg)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (L\"%s\", traceMsg);\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\tinline\tvoid\tDoReThrow ()\r\n\t\t\t\t{\r\n\t\t\t\t\tDbgTrace (\"DoReThrow\");\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\t\t\tinline\tvoid\tDoReThrow (const char* traceMsg)\r\n\t\t\t\t{\r\n\t\t\t\t\tDbgTrace (\"DoReThrow: %s\", traceMsg);\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\t\t\tinline\tvoid\tDoReThrow (const wchar_t* traceMsg)\r\n\t\t\t\t{\r\n\t\t\t\t\tDbgTrace (L\"DoReThrow: %s\", traceMsg);\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const Win32ErrorException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing Win32ErrorException: DWORD = 0x%x\", static_cast (e2Throw));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const StringException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (L\"Throwing StringException: '%s'\", static_cast (e2Throw).substr (0, 20).c_str ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const Win32StructuredException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing Win32StructuredException: fSECode = 0x%x\", static_cast (e2Throw));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t#endif\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const HRESULTErrorException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing HRESULTErrorException: HRESULT = 0x%x\", static_cast (e2Throw));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t#endif\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const IO::FileFormatException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing FileFormatException: fFileName = '%s'\"), e2Throw.fFileName.c_str ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const SilentException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing SilentException\"));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const UserCanceledException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing UserCanceledException\"));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\tDoThrow (const IO::FileBusyException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing FileBusyException: fFileName = '%s'\"), e2Throw.fFileName.c_str ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\r\n\r\n\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfFalseGetLastError (bool test)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (not test) {\r\n\t\t\t\t\t\tWin32ErrorException::DoThrow (::GetLastError ());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfFalseGetLastError (BOOL test)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (not test) {\r\n\t\t\t\t\t\tWin32ErrorException::DoThrow (::GetLastError ());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfNotERROR_SUCCESS (DWORD win32ErrCode)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (win32ErrCode != ERROR_SUCCESS) {\r\n\t\t\t\t\t\tWin32ErrorException::DoThrow (win32ErrCode);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfErrorHRESULT (HRESULT hr)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (not SUCCEEDED (hr)) {\r\n\t\t\t\t\t\tDoThrow (HRESULTErrorException (hr));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfError_errno_t (errno_t e)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (e != 0) {\r\n\t\t\t\t\t\terrno_ErrorException::DoThrow (e);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\tinline\tvoid\tThrowIfNull (const void* p)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (p == NULL) {\r\n\t\t\t\t\t\tDoThrow (bad_alloc (), _T (\"ThrowIfNull (NULL) - throwing bad_alloc\"));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\tvoid\tThrowIfNull (const void* p, const E& e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (p == NULL) {\r\n\t\t\t\t\t\t\tDoThrow (e, _T (\"ThrowIfNull (NULL,X) - throwing X\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate<>\r\n\t\t\t\tinline\tvoid\tThrowIfNull (const void* p, const HRESULT& hr)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tThrowIfNull (p, HRESULTErrorException (hr));\r\n\t\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\t\/*_Stroia_Foundation_Execution_Exceptions_inl_*\/\r\n_NoReturn_ stuff needed on DEFINITIONS as well as DECLARATIONS for DoThrow\/DoRethrow() functions (at least on MSVC - still not tested UNIX)\/*\r\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\r\n *\/\r\n#ifndef\t_Stroia_Foundation_Execution_Exceptions_inl_\r\n#define\t_Stroia_Foundation_Execution_Exceptions_inl_\t1\r\n\r\n\r\n\/*\r\n ********************************************************************************\r\n ***************************** Implementation Details ***************************\r\n ********************************************************************************\r\n *\/\r\nnamespace\tStroika {\t\r\n\tnamespace\tFoundation {\r\n\t\tnamespace\tExecution {\r\n\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\/\/\tclass\tWin32ErrorException\r\n\t\t\tinline\tWin32ErrorException::Win32ErrorException (DWORD error):\r\n\t\t\t\tfError (error)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\tinline\tWin32ErrorException::operator DWORD () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fError;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\tWin32ErrorException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fError);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\t\t\/\/\tclass\tWin32StructuredException\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tWin32StructuredException::Win32StructuredException (unsigned int seCode):\r\n\t\t\t\tfSECode (seCode)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\tinline\tWin32StructuredException::operator unsigned int () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fSECode;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\tWin32StructuredException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fSECode);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\r\n\r\n\t\t\/\/\tclass\tHRESULTErrorException\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tHRESULTErrorException::HRESULTErrorException (HRESULT hresult):\r\n\t\t\t\tfHResult (hresult)\r\n\t\t\t\t{\r\n\t\t\t\t}\r\n\t\t\tinline\tHRESULTErrorException::operator HRESULT () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fHResult;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\tHRESULTErrorException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fHResult);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\t\r\n\t\t\/\/\tclass\terrno_ErrorException\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\terrno_ErrorException::operator errno_t () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn fError;\r\n\t\t\t\t}\r\n\t\t\tinline\tTString\terrno_ErrorException::LookupMessage () const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn LookupMessage (fError);\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\r\n\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\t\tvoid\t _NoReturn_\tDoThrow (const T& e2Throw) \r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing exception: %s\", typeid (T).name ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\tvoid\t\t_NoReturn_\tDoThrow (const T& e2Throw, const char* traceMsg)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"%s\", traceMsg);\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\tvoid\t\t_NoReturn_\tDoThrow (const T& e2Throw, const wchar_t* traceMsg)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (L\"%s\", traceMsg);\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\tinline\tvoid\t_NoReturn_\tDoReThrow ()\r\n\t\t\t\t{\r\n\t\t\t\t\tDbgTrace (\"DoReThrow\");\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\t\t\tinline\tvoid\t_NoReturn_\tDoReThrow (const char* traceMsg)\r\n\t\t\t\t{\r\n\t\t\t\t\tDbgTrace (\"DoReThrow: %s\", traceMsg);\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\t\t\tinline\tvoid\t_NoReturn_\tDoReThrow (const wchar_t* traceMsg)\r\n\t\t\t\t{\r\n\t\t\t\t\tDbgTrace (L\"DoReThrow: %s\", traceMsg);\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\r\n\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const Win32ErrorException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing Win32ErrorException: DWORD = 0x%x\", static_cast (e2Throw));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const StringException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (L\"Throwing StringException: '%s'\", static_cast (e2Throw).substr (0, 20).c_str ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const Win32StructuredException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing Win32StructuredException: fSECode = 0x%x\", static_cast (e2Throw));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t#endif\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const HRESULTErrorException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (\"Throwing HRESULTErrorException: HRESULT = 0x%x\", static_cast (e2Throw));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t#endif\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const IO::FileFormatException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing FileFormatException: fFileName = '%s'\"), e2Throw.fFileName.c_str ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const SilentException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing SilentException\"));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const UserCanceledException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing UserCanceledException\"));\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\t\t\ttemplate\t<>\r\n\t\t\t\tinline\tvoid\t_NoReturn_\tDoThrow (const IO::FileBusyException& e2Throw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDbgTrace (_T (\"Throwing FileBusyException: fFileName = '%s'\"), e2Throw.fFileName.c_str ());\r\n\t\t\t\t\t\tthrow e2Throw;\r\n\t\t\t\t\t}\r\n\r\n\r\n\r\n\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfFalseGetLastError (bool test)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (not test) {\r\n\t\t\t\t\t\tWin32ErrorException::DoThrow (::GetLastError ());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfFalseGetLastError (BOOL test)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (not test) {\r\n\t\t\t\t\t\tWin32ErrorException::DoThrow (::GetLastError ());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfNotERROR_SUCCESS (DWORD win32ErrCode)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (win32ErrCode != ERROR_SUCCESS) {\r\n\t\t\t\t\t\tWin32ErrorException::DoThrow (win32ErrCode);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfErrorHRESULT (HRESULT hr)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (not SUCCEEDED (hr)) {\r\n\t\t\t\t\t\tDoThrow (HRESULTErrorException (hr));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\tinline\tvoid\tThrowIfError_errno_t (errno_t e)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (e != 0) {\r\n\t\t\t\t\t\terrno_ErrorException::DoThrow (e);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\tinline\tvoid\tThrowIfNull (const void* p)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (p == NULL) {\r\n\t\t\t\t\t\tDoThrow (bad_alloc (), _T (\"ThrowIfNull (NULL) - throwing bad_alloc\"));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\ttemplate\t\r\n\t\t\t\tinline\tvoid\tThrowIfNull (const void* p, const E& e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (p == NULL) {\r\n\t\t\t\t\t\t\tDoThrow (e, _T (\"ThrowIfNull (NULL,X) - throwing X\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t#if\t\tqPlatform_Windows\r\n\t\t\ttemplate<>\r\n\t\t\t\tinline\tvoid\tThrowIfNull (const void* p, const HRESULT& hr)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tThrowIfNull (p, HRESULTErrorException (hr));\r\n\t\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\t\/*_Stroia_Foundation_Execution_Exceptions_inl_*\/\r\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Characters\/CString\/Utilities.h\"\n#include \"..\/Characters\/StringBuilder.h\"\n#include \"..\/Characters\/ToString.h\"\n#include \"..\/Memory\/BlockAllocated.h\"\n\n#include \"Common.h\"\n#include \"Sleep.h\"\n#include \"TimeOutException.h\"\n\n#include \"ThreadPool.h\"\n\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Execution;\n\n\nusing Characters::String;\nusing Characters::StringBuilder;\n\n\nclass ThreadPool::MyRunnable_ {\npublic:\n MyRunnable_ (ThreadPool& threadPool)\n : fCurTaskUpdateCritSection_ ()\n , fThreadPool_ (threadPool)\n , fCurTask_ ()\n , fNextTask_ ()\n {\n }\n\npublic:\n ThreadPool::TaskType GetCurrentTask () const\n {\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n \/\/ THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK\n \/\/ Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either\n Assert (fCurTask_ == nullptr or fNextTask_ == nullptr); \/\/ one or both must be null\n return fCurTask_ == nullptr ? fNextTask_ : fCurTask_;\n }\n\npublic:\n nonvirtual void Run ()\n {\n \/\/ For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability\n\n \/\/ Keep grabbing new tasks, and running them\n while (true) {\n {\n fThreadPool_.WaitForNextTask_ (&fNextTask_); \/\/ This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n Assert (fNextTask_ != nullptr);\n Assert (fCurTask_ == nullptr);\n fCurTask_ = fNextTask_;\n fNextTask_ = nullptr;\n Assert (fCurTask_ != nullptr);\n Assert (fNextTask_ == nullptr);\n }\n try {\n fCurTask_ ();\n fCurTask_ = nullptr;\n }\n catch (const Thread::AbortException&) {\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n fCurTask_ = nullptr;\n throw; \/\/ cancel this thread\n }\n catch (...) {\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n fCurTask_ = nullptr;\n \/\/ other exceptions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT\/IGNORE\n }\n }\n }\n\nprivate:\n mutable recursive_mutex fCurTaskUpdateCritSection_;\n ThreadPool& fThreadPool_;\n ThreadPool::TaskType fCurTask_;\n ThreadPool::TaskType fNextTask_;\n};\n\n\n\n\n\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************************** Execution::ThreadPool ***************************\n ********************************************************************************\n *\/\nThreadPool::ThreadPool (unsigned int nThreads)\n : fCriticalSection_ ()\n , fAborted_ (false)\n , fThreads_ ()\n , fPendingTasks_ ()\n , fTasksMaybeAdded_ (WaitableEvent::eAutoReset)\n{\n SetPoolSize (nThreads);\n}\n\nThreadPool::~ThreadPool ()\n{\n try {\n this->AbortAndWaitForDone ();\n }\n catch (...) {\n DbgTrace (\"Ignore exception in destroying thread pool ** probably bad thing...\");\n }\n}\n\nunsigned int ThreadPool::GetPoolSize () const\n{\n return static_cast (fThreads_.size ());\n}\n\nvoid ThreadPool::SetPoolSize (unsigned int poolSize)\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::SetPoolSize\");\n Require (not fAborted_);\n auto critSec { make_unique_lock (fCriticalSection_) };\n while (poolSize > fThreads_.size ()) {\n fThreads_.Add (mkThread_ ());\n }\n\n \/\/ Still quite weak implementation of REMOVAL\n while (poolSize < fThreads_.size ()) {\n \/\/ iterate over threads if any not busy, remove that one\n bool anyFoundToKill = false;\n for (Iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType ct { tr->GetCurrentTask () };\n if (ct == nullptr) {\n \/\/ since we have fCriticalSection_ - we can safely remove this thread\n fThreads_.Remove (i);\n anyFoundToKill = true;\n break;\n }\n }\n if (not anyFoundToKill) {\n \/\/ @todo - fix this better\/eventually\n DbgTrace (\"Failed to lower the loop size - cuz all threads busy - giving up\");\n return;\n }\n }\n}\n\nThreadPool::TaskType ThreadPool::AddTask (const TaskType& task)\n{\n \/\/Debug::TraceContextBumper ctx (\"ThreadPool::AddTask\");\n Require (not fAborted_);\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n fPendingTasks_.push_back (task);\n }\n\n \/\/ Notify any waiting threads to wakeup and claim the next task\n fTasksMaybeAdded_.Set ();\n \/\/ this would be a race - if aborting and adding tasks at the same time\n Require (not fAborted_);\n return task;\n}\n\nvoid ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::AbortTask\");\n {\n \/\/ First see if its in the Q\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) {\n if (*i == task) {\n fPendingTasks_.erase (i);\n return;\n }\n }\n }\n\n \/\/ If we got here - its NOT in the task Q, so maybe its already running.\n \/\/\n \/\/\n\n \/\/ TODO:\n \/\/ We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.\n \/\/ But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK\n \/\/ actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for something\n \/\/ quite rare.\n \/\/\n \/\/ Anyhow SB OK for now to just not allow aborting a task which has already started....\n Thread thread2Kill;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (Iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType ct { tr->GetCurrentTask () };\n if (task == ct) {\n thread2Kill = i->fThread;\n fThreads_.Update (i, mkThread_ ());\n break;\n }\n }\n }\n if (thread2Kill.GetStatus () != Thread::Status::eNull) {\n thread2Kill.AbortAndWaitForDone (timeout);\n }\n}\n\nvoid ThreadPool::AbortTasks (Time::DurationSecondsType timeout)\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::AbortTasks\");\n auto tps = GetPoolSize ();\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n fPendingTasks_.clear ();\n }\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (TPInfo_ ti : fThreads_) {\n ti.fThread.Abort ();\n }\n }\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (TPInfo_ ti : fThreads_) {\n \/\/ @todo fix wrong timeout value here\n ti.fThread.AbortAndWaitForDone (timeout);\n }\n fThreads_.RemoveAll ();\n }\n \/\/ hack - not a good design or impl!!! - waste to recreate if not needed!\n SetPoolSize (tps);\n}\n\nbool ThreadPool::IsPresent (const TaskType& task) const\n{\n Require (task != nullptr);\n {\n \/\/ First see if its in the Q\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) {\n if (*i == task) {\n return true;\n }\n }\n }\n return IsRunning (task);\n}\n\nbool ThreadPool::IsRunning (const TaskType& task) const\n{\n Require (task != nullptr);\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType rTask { tr->GetCurrentTask () };\n if (task == rTask) {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::WaitForTask\");\n \/\/ Inefficient \/ VERY SLOPPY impl\n using Time::DurationSecondsType;\n DurationSecondsType timeoutAt = timeout + Time::GetTickCount ();\n while (true) {\n if (not IsPresent (task)) {\n return;\n }\n DurationSecondsType remaining = timeoutAt - Time::GetTickCount ();\n Execution::ThrowTimeoutExceptionAfter (timeoutAt);\n Execution::Sleep (min (remaining, 1.0));\n }\n}\n\nCollection ThreadPool::GetTasks () const\n{\n Collection result;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n result.AddAll (fPendingTasks_.begin (), fPendingTasks_.end ()); \/\/ copy pending tasks\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType task { tr->GetCurrentTask () };\n if (task != nullptr) {\n result.Add (task);\n }\n }\n }\n return result;\n}\n\nCollection ThreadPool::GetRunningTasks () const\n{\n Collection result;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType task { tr->GetCurrentTask () };\n if (task != nullptr) {\n result.Add (task);\n }\n }\n }\n return result;\n}\n\nsize_t ThreadPool::GetTasksCount () const\n{\n size_t count = 0;\n {\n \/\/ First see if its in the Q\n auto critSec { make_unique_lock (fCriticalSection_) };\n count += fPendingTasks_.size ();\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType task { tr->GetCurrentTask () };\n if (task != nullptr) {\n count++;\n }\n }\n }\n return count;\n}\n\nsize_t ThreadPool::GetPendingTasksCount () const\n{\n size_t count = 0;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n count += fPendingTasks_.size ();\n }\n return count;\n}\n\nvoid ThreadPool::WaitForDoneUntil (Time::DurationSecondsType timeoutAt) const\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::WaitForDoneUntil\");\n DbgTrace (L\"this-status: %s\", ToString ().c_str ());\n Require (fAborted_);\n {\n Collection threadsToShutdown; \/\/ cannot keep critical section while waiting on subthreads since they may need to acquire the critsection for whatever they are doing...\n#if qDefaultTracingOn\n Collection threadsNotAlreadyDone; \/\/ just for DbgTrace message purposes\n#endif\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto ti : fThreads_) {\n threadsToShutdown.Add (ti.fThread);\n#if qDefaultTracingOn\n if (not ti.fThread.IsDone ()) {\n threadsNotAlreadyDone.Add (Execution::FormatThreadID (ti.fThread.GetID ()));\n }\n#endif\n }\n }\n DbgTrace (L\"threadsToShutdown.size = %d\", threadsToShutdown.size ());\n#if qDefaultTracingOn\n DbgTrace (L\"threadsNotAlreadyDone = %s\", Characters::ToString (threadsNotAlreadyDone).c_str ());\n#endif\n for (auto t : threadsToShutdown) {\n t.WaitForDoneUntil (timeoutAt);\n }\n }\n}\n\nvoid ThreadPool::Abort ()\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::Abort\");\n Thread::SuppressInterruptionInContext suppressCtx; \/\/ must cleanly shut down each of our subthreads - even if our thread is aborting...\n DbgTrace (L\"this-status: %s\", ToString ().c_str ());\n fAborted_ = true; \/\/ No race, because fAborted never 'unset'\n \/\/ no need to set fTasksMaybeAdded_, since aborting each thread should be sufficient\n {\n \/\/ Clear the task Q and then abort each thread\n auto critSec { make_unique_lock (fCriticalSection_) };\n fPendingTasks_.clear ();\n for (TPInfo_ && ti : fThreads_) {\n ti.fThread.Abort ();\n }\n }\n}\n\nvoid ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)\n{\n Debug::TraceContextBumper traceCtx (\"ThreadPool::AbortAndWaitForDone\");\n Thread::SuppressInterruptionInContext suppressCtx; \/\/ must cleanly shut down each of our subthreads - even if our thread is aborting...\n DbgTrace (L\"this-status: %s\", ToString ().c_str ());\n Abort ();\n WaitForDone (timeout);\n}\n\nString ThreadPool::ToString () const\n{\n auto critSec { make_unique_lock (fCriticalSection_) };\n StringBuilder sb;\n sb += L\"{\";\n sb += Characters::Format (L\"pending-task-count: %d\", GetPendingTasksCount ()) + L\", \";\n sb += Characters::Format (L\"running-task-count: %d\", GetRunningTasks ().size ()) + L\", \";\n sb += Characters::Format (L\"pool-thread-count: %d\", fThreads_.size ()) + L\", \";\n sb += L\"}\";\n return sb.str ();\n}\n\n\/\/ THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool\nvoid ThreadPool::WaitForNextTask_ (TaskType* result)\n{\n RequireNotNull (result);\n if (fAborted_) {\n Execution::Throw (Thread::AbortException ());\n }\n\n while (true) {\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n if (not fPendingTasks_.empty ()) {\n *result = fPendingTasks_.front ();\n fPendingTasks_.pop_front ();\n DbgTrace (\"ThreadPool::WaitForNextTask_ () is starting a new task\");\n return;\n }\n }\n\n \/\/ Prevent spinwaiting... This event is SET when any new item arrives\n \/\/DbgTrace (\"ThreadPool::WaitForNextTask_ () - about to wait for added tasks\");\n fTasksMaybeAdded_.Wait ();\n \/\/DbgTrace (\"ThreadPool::WaitForNextTask_ () - completed wait for added tasks\");\n }\n}\n\nThreadPool::TPInfo_ ThreadPool::mkThread_ ()\n{\n shared_ptr r { make_shared (*this) };\n static int sThreadNum_ = 1; \/\/ race condition for updating this number, but who cares - its purely cosmetic...\n Thread t {\n [r] () { r->Run (); }\n , Thread::eAutoStart\n , Characters::Format (L\"Thread Pool Entry %d\", sThreadNum_++)\n };\n return TPInfo_ { t, r };\n}\nUSE_NOISY_TRACE_IN_THIS_MODULE_ define support foir ThreadPool module\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Characters\/CString\/Utilities.h\"\n#include \"..\/Characters\/StringBuilder.h\"\n#include \"..\/Characters\/ToString.h\"\n#include \"..\/Memory\/BlockAllocated.h\"\n\n#include \"Common.h\"\n#include \"Sleep.h\"\n#include \"TimeOutException.h\"\n\n#include \"ThreadPool.h\"\n\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Execution;\n\n\nusing Characters::String;\nusing Characters::StringBuilder;\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\nclass ThreadPool::MyRunnable_ {\npublic:\n MyRunnable_ (ThreadPool& threadPool)\n : fCurTaskUpdateCritSection_ ()\n , fThreadPool_ (threadPool)\n , fCurTask_ ()\n , fNextTask_ ()\n {\n }\n\npublic:\n ThreadPool::TaskType GetCurrentTask () const\n {\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n \/\/ THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK\n \/\/ Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either\n Assert (fCurTask_ == nullptr or fNextTask_ == nullptr); \/\/ one or both must be null\n return fCurTask_ == nullptr ? fNextTask_ : fCurTask_;\n }\n\npublic:\n nonvirtual void Run ()\n {\n \/\/ For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability\n\n \/\/ Keep grabbing new tasks, and running them\n while (true) {\n {\n fThreadPool_.WaitForNextTask_ (&fNextTask_); \/\/ This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n Assert (fNextTask_ != nullptr);\n Assert (fCurTask_ == nullptr);\n fCurTask_ = fNextTask_;\n fNextTask_ = nullptr;\n Assert (fCurTask_ != nullptr);\n Assert (fNextTask_ == nullptr);\n }\n try {\n fCurTask_ ();\n fCurTask_ = nullptr;\n }\n catch (const Thread::AbortException&) {\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n fCurTask_ = nullptr;\n throw; \/\/ cancel this thread\n }\n catch (...) {\n auto critSec { make_unique_lock (fCurTaskUpdateCritSection_) };\n fCurTask_ = nullptr;\n \/\/ other exceptions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT\/IGNORE\n }\n }\n }\n\nprivate:\n mutable recursive_mutex fCurTaskUpdateCritSection_;\n ThreadPool& fThreadPool_;\n ThreadPool::TaskType fCurTask_;\n ThreadPool::TaskType fNextTask_;\n};\n\n\n\n\n\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************************** Execution::ThreadPool ***************************\n ********************************************************************************\n *\/\nThreadPool::ThreadPool (unsigned int nThreads)\n : fCriticalSection_ ()\n , fAborted_ (false)\n , fThreads_ ()\n , fPendingTasks_ ()\n , fTasksMaybeAdded_ (WaitableEvent::eAutoReset)\n{\n SetPoolSize (nThreads);\n}\n\nThreadPool::~ThreadPool ()\n{\n try {\n this->AbortAndWaitForDone ();\n }\n catch (...) {\n DbgTrace (\"Ignore exception in destroying thread pool ** probably bad thing...\");\n }\n}\n\nunsigned int ThreadPool::GetPoolSize () const\n{\n return static_cast (fThreads_.size ());\n}\n\nvoid ThreadPool::SetPoolSize (unsigned int poolSize)\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::SetPoolSize\");\n Require (not fAborted_);\n auto critSec { make_unique_lock (fCriticalSection_) };\n while (poolSize > fThreads_.size ()) {\n fThreads_.Add (mkThread_ ());\n }\n\n \/\/ Still quite weak implementation of REMOVAL\n while (poolSize < fThreads_.size ()) {\n \/\/ iterate over threads if any not busy, remove that one\n bool anyFoundToKill = false;\n for (Iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType ct { tr->GetCurrentTask () };\n if (ct == nullptr) {\n \/\/ since we have fCriticalSection_ - we can safely remove this thread\n fThreads_.Remove (i);\n anyFoundToKill = true;\n break;\n }\n }\n if (not anyFoundToKill) {\n \/\/ @todo - fix this better\/eventually\n DbgTrace (\"Failed to lower the loop size - cuz all threads busy - giving up\");\n return;\n }\n }\n}\n\nThreadPool::TaskType ThreadPool::AddTask (const TaskType& task)\n{\n \/\/Debug::TraceContextBumper ctx (\"ThreadPool::AddTask\");\n Require (not fAborted_);\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n fPendingTasks_.push_back (task);\n }\n\n \/\/ Notify any waiting threads to wakeup and claim the next task\n fTasksMaybeAdded_.Set ();\n \/\/ this would be a race - if aborting and adding tasks at the same time\n Require (not fAborted_);\n return task;\n}\n\nvoid ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::AbortTask\");\n {\n \/\/ First see if its in the Q\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) {\n if (*i == task) {\n fPendingTasks_.erase (i);\n return;\n }\n }\n }\n\n \/\/ If we got here - its NOT in the task Q, so maybe its already running.\n \/\/\n \/\/\n\n \/\/ TODO:\n \/\/ We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.\n \/\/ But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK\n \/\/ actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for something\n \/\/ quite rare.\n \/\/\n \/\/ Anyhow SB OK for now to just not allow aborting a task which has already started....\n Thread thread2Kill;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (Iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType ct { tr->GetCurrentTask () };\n if (task == ct) {\n thread2Kill = i->fThread;\n fThreads_.Update (i, mkThread_ ());\n break;\n }\n }\n }\n if (thread2Kill.GetStatus () != Thread::Status::eNull) {\n thread2Kill.AbortAndWaitForDone (timeout);\n }\n}\n\nvoid ThreadPool::AbortTasks (Time::DurationSecondsType timeout)\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::AbortTasks\");\n auto tps = GetPoolSize ();\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n fPendingTasks_.clear ();\n }\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (TPInfo_ ti : fThreads_) {\n ti.fThread.Abort ();\n }\n }\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (TPInfo_ ti : fThreads_) {\n \/\/ @todo fix wrong timeout value here\n ti.fThread.AbortAndWaitForDone (timeout);\n }\n fThreads_.RemoveAll ();\n }\n \/\/ hack - not a good design or impl!!! - waste to recreate if not needed!\n SetPoolSize (tps);\n}\n\nbool ThreadPool::IsPresent (const TaskType& task) const\n{\n Require (task != nullptr);\n {\n \/\/ First see if its in the Q\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fPendingTasks_.begin (); i != fPendingTasks_.end (); ++i) {\n if (*i == task) {\n return true;\n }\n }\n }\n return IsRunning (task);\n}\n\nbool ThreadPool::IsRunning (const TaskType& task) const\n{\n Require (task != nullptr);\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType rTask { tr->GetCurrentTask () };\n if (task == rTask) {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::WaitForTask\");\n \/\/ Inefficient \/ VERY SLOPPY impl\n using Time::DurationSecondsType;\n DurationSecondsType timeoutAt = timeout + Time::GetTickCount ();\n while (true) {\n if (not IsPresent (task)) {\n return;\n }\n DurationSecondsType remaining = timeoutAt - Time::GetTickCount ();\n Execution::ThrowTimeoutExceptionAfter (timeoutAt);\n Execution::Sleep (min (remaining, 1.0));\n }\n}\n\nCollection ThreadPool::GetTasks () const\n{\n Collection result;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n result.AddAll (fPendingTasks_.begin (), fPendingTasks_.end ()); \/\/ copy pending tasks\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType task { tr->GetCurrentTask () };\n if (task != nullptr) {\n result.Add (task);\n }\n }\n }\n return result;\n}\n\nCollection ThreadPool::GetRunningTasks () const\n{\n Collection result;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType task { tr->GetCurrentTask () };\n if (task != nullptr) {\n result.Add (task);\n }\n }\n }\n return result;\n}\n\nsize_t ThreadPool::GetTasksCount () const\n{\n size_t count = 0;\n {\n \/\/ First see if its in the Q\n auto critSec { make_unique_lock (fCriticalSection_) };\n count += fPendingTasks_.size ();\n for (auto i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n shared_ptr tr { i->fRunnable };\n TaskType task { tr->GetCurrentTask () };\n if (task != nullptr) {\n count++;\n }\n }\n }\n return count;\n}\n\nsize_t ThreadPool::GetPendingTasksCount () const\n{\n size_t count = 0;\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n count += fPendingTasks_.size ();\n }\n return count;\n}\n\nvoid ThreadPool::WaitForDoneUntil (Time::DurationSecondsType timeoutAt) const\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::WaitForDoneUntil\");\n DbgTrace (L\"this-status: %s\", ToString ().c_str ());\n Require (fAborted_);\n {\n Collection threadsToShutdown; \/\/ cannot keep critical section while waiting on subthreads since they may need to acquire the critsection for whatever they are doing...\n#if qDefaultTracingOn\n Collection threadsNotAlreadyDone; \/\/ just for DbgTrace message purposes\n#endif\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n for (auto ti : fThreads_) {\n threadsToShutdown.Add (ti.fThread);\n#if qDefaultTracingOn\n if (not ti.fThread.IsDone ()) {\n threadsNotAlreadyDone.Add (Execution::FormatThreadID (ti.fThread.GetID ()));\n }\n#endif\n }\n }\n DbgTrace (L\"threadsToShutdown.size = %d\", threadsToShutdown.size ());\n#if qDefaultTracingOn\n DbgTrace (L\"threadsNotAlreadyDone = %s\", Characters::ToString (threadsNotAlreadyDone).c_str ());\n#endif\n for (auto t : threadsToShutdown) {\n t.WaitForDoneUntil (timeoutAt);\n }\n }\n}\n\nvoid ThreadPool::Abort ()\n{\n Debug::TraceContextBumper ctx (\"ThreadPool::Abort\");\n Thread::SuppressInterruptionInContext suppressCtx; \/\/ must cleanly shut down each of our subthreads - even if our thread is aborting...\n DbgTrace (L\"this-status: %s\", ToString ().c_str ());\n fAborted_ = true; \/\/ No race, because fAborted never 'unset'\n \/\/ no need to set fTasksMaybeAdded_, since aborting each thread should be sufficient\n {\n \/\/ Clear the task Q and then abort each thread\n auto critSec { make_unique_lock (fCriticalSection_) };\n fPendingTasks_.clear ();\n for (TPInfo_ && ti : fThreads_) {\n ti.fThread.Abort ();\n }\n }\n}\n\nvoid ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)\n{\n Debug::TraceContextBumper traceCtx (\"ThreadPool::AbortAndWaitForDone\");\n Thread::SuppressInterruptionInContext suppressCtx; \/\/ must cleanly shut down each of our subthreads - even if our thread is aborting...\n DbgTrace (L\"this-status: %s\", ToString ().c_str ());\n Abort ();\n WaitForDone (timeout);\n}\n\nString ThreadPool::ToString () const\n{\n auto critSec { make_unique_lock (fCriticalSection_) };\n StringBuilder sb;\n sb += L\"{\";\n sb += Characters::Format (L\"pending-task-count: %d\", GetPendingTasksCount ()) + L\", \";\n sb += Characters::Format (L\"running-task-count: %d\", GetRunningTasks ().size ()) + L\", \";\n sb += Characters::Format (L\"pool-thread-count: %d\", fThreads_.size ()) + L\", \";\n sb += L\"}\";\n return sb.str ();\n}\n\n\/\/ THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool\nvoid ThreadPool::WaitForNextTask_ (TaskType* result)\n{\n RequireNotNull (result);\n if (fAborted_) {\n Execution::Throw (Thread::AbortException ());\n }\n\n while (true) {\n {\n auto critSec { make_unique_lock (fCriticalSection_) };\n if (not fPendingTasks_.empty ()) {\n *result = fPendingTasks_.front ();\n fPendingTasks_.pop_front ();\n DbgTrace (\"ThreadPool::WaitForNextTask_ () is starting a new task\");\n return;\n }\n }\n\n \/\/ Prevent spinwaiting... This event is SET when any new item arrives\n \/\/DbgTrace (\"ThreadPool::WaitForNextTask_ () - about to wait for added tasks\");\n fTasksMaybeAdded_.Wait ();\n \/\/DbgTrace (\"ThreadPool::WaitForNextTask_ () - completed wait for added tasks\");\n }\n}\n\nThreadPool::TPInfo_ ThreadPool::mkThread_ ()\n{\n shared_ptr r { make_shared (*this) };\n static int sThreadNum_ = 1; \/\/ race condition for updating this number, but who cares - its purely cosmetic...\n Thread t {\n [r] () { r->Run (); }\n , Thread::eAutoStart\n , Characters::Format (L\"Thread Pool Entry %d\", sThreadNum_++)\n };\n return TPInfo_ { t, r };\n}\n<|endoftext|>"} {"text":"fix: revert formating<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ozone\/wayland_display.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ozone\/wayland_input_device.h\"\n#include \"ozone\/wayland_screen.h\"\n#include \"ozone\/wayland_window.h\"\n#include \"ozone\/wayland_input_method_event_filter.h\"\n#include \"base\/message_loop.h\"\n\n#ifdef USE_CAIRO_GLESV2\n#include \n#include \n#else\n#include \n#endif\n\n#include \n#include \n\nnamespace ui {\n\nWaylandDisplay* g_display = NULL;\n\nWaylandDisplay* WaylandDisplay::GetDisplay()\n{\n if (!g_display)\n g_display = WaylandDisplay::Connect(NULL);\n return g_display;\n}\n\nvoid WaylandDisplay::DestroyDisplay()\n{\n if(g_display)\n delete g_display;\n g_display = NULL;\n}\n\n\/\/ static\nWaylandDisplay* WaylandDisplay::Connect(char* name)\n{\n static const struct wl_registry_listener registry_listener = {\n WaylandDisplay::DisplayHandleGlobal\n };\n\n WaylandDisplay* display = new WaylandDisplay(name);\n if (!display->display_) {\n delete display;\n return NULL;\n }\n\n wl_display_set_user_data(display->display_, display);\n\n display->registry_ = wl_display_get_registry(display->display_);\n wl_registry_add_listener(display->registry_, ®istry_listener, display);\n\n wl_display_dispatch(display->display_);\n\n display->CreateCursors();\n\n return display;\n}\n\nvoid WaylandDisplay::AddWindow(WaylandWindow* window)\n{\n if(window)\n window_list_.push_back(window);\n}\n\nvoid WaylandDisplay::AddTask(WaylandTask* task)\n{\n if(task)\n task_list_.push_back(task);\n}\n\nvoid WaylandDisplay::ProcessTasks()\n{\n WaylandTask *task = NULL;\n\n while(!task_list_.empty())\n {\n task = task_list_.front();\n task->Run();\n task_list_.pop_front();\n delete task;\n }\n}\n\nvoid WaylandDisplay::RemoveWindow(WaylandWindow* window)\n{\n if(!window)\n return;\n\n WaylandTask *task = NULL;\n\n for (std::list::iterator i = task_list_.begin();\n i != task_list_.end(); ++i) {\n if((*i)->GetWindow() == window)\n {\n delete *i;\n i = task_list_.erase(i);\n }\n }\n\n for (std::list::iterator i = window_list_.begin();\n i != window_list_.end(); ++i) {\n if((*i) == window)\n {\n i = window_list_.erase(i);\n break;\n }\n }\n\n if(window_list_.size() < 1)\n {\n base::MessageLoop::current()->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());\n }\n}\n\nbool WaylandDisplay::IsWindow(WaylandWindow* window)\n{\n for (std::list::iterator i = window_list_.begin();\n i != window_list_.end(); ++i) {\n if((*i) == window)\n {\n return true;\n }\n }\n\n return false;\n}\n\nInputMethod* WaylandDisplay::GetInputMethod() const\n{\n return input_method_filter_ ? input_method_filter_->GetInputMethod(): NULL;\n}\n\n\/\/ static\nWaylandDisplay* WaylandDisplay::GetDisplay(wl_display* display)\n{\n return static_cast(wl_display_get_user_data(display));\n}\n\nWaylandDisplay::WaylandDisplay(char* name) : display_(NULL),\n cursor_theme_(NULL),\n cursors_(NULL),\n compositor_(NULL),\n shell_(NULL),\n shm_(NULL)\n{\n display_ = wl_display_connect(name);\n input_method_filter_ = new WaylandInputMethodEventFilter;\n}\n\nWaylandDisplay::~WaylandDisplay()\n{\n if (window_list_.size() > 0)\n fprintf(stderr, \"toytoolkit warning: windows exist.\\n\");\n\n if (task_list_.size() > 0)\n fprintf(stderr, \"toytoolkit warning: deferred tasks exist.\\n\");\n\n for (std::list::iterator i = input_list_.begin();\n i != input_list_.end(); ++i) {\n delete *i;\n }\n\n for (std::list::iterator i = screen_list_.begin();\n i != screen_list_.end(); ++i) {\n delete *i;\n }\n\n DestroyCursors();\n\n if (compositor_)\n wl_compositor_destroy(compositor_);\n if (shell_)\n wl_shell_destroy(shell_);\n if (shm_)\n wl_shm_destroy(shm_);\n if (display_)\n wl_display_disconnect(display_);\n\n delete input_method_filter_;\n}\n\nwl_surface* WaylandDisplay::CreateSurface()\n{\n return wl_compositor_create_surface(compositor_);\n}\n\nstd::list WaylandDisplay::GetScreenList() const {\n return screen_list_;\n}\n\n\/\/ static\nvoid WaylandDisplay::DisplayHandleGlobal(void *data,\n struct wl_registry *registry,\n uint32_t name,\n const char *interface,\n uint32_t version)\n{\n\n WaylandDisplay* disp = static_cast(data);\n\n if (strcmp(interface, \"wl_compositor\") == 0) {\n disp->compositor_ = static_cast(\n wl_registry_bind(registry, name, &wl_compositor_interface, 1));\n } else if (strcmp(interface, \"wl_output\") == 0) {\n WaylandScreen* screen = new WaylandScreen(disp, name);\n disp->screen_list_.push_back(screen);\n } else if (strcmp(interface, \"wl_seat\") == 0) {\n WaylandInputDevice *input_device = new WaylandInputDevice(disp, name);\n disp->input_list_.push_back(input_device);\n } else if (strcmp(interface, \"wl_shell\") == 0) {\n disp->shell_ = static_cast(\n wl_registry_bind(registry, name, &wl_shell_interface, 1));\n } else if (strcmp(interface, \"wl_shm\") == 0) {\n disp->shm_ = static_cast(\n wl_registry_bind(registry, name, &wl_shm_interface, 1));\n }\n}\n\nstatic const char *cursor_names[] = {\n \"bottom_left_corner\",\n \"bottom_right_corner\",\n \"bottom_side\",\n \"grabbing\",\n \"left_ptr\",\n \"left_side\",\n \"right_side\",\n \"top_left_corner\",\n \"top_right_corner\",\n \"top_side\",\n \"xterm\",\n \"hand1\",\n};\n\nvoid WaylandDisplay::CreateCursors()\n{\n unsigned int i, array_size = sizeof(cursor_names) \/ sizeof(cursor_names[0]);\n cursor_theme_ = wl_cursor_theme_load(NULL, 32, shm_);\n cursors_ = new wl_cursor*[array_size];\n memset(cursors_, 0, sizeof(wl_cursor*) * array_size);\n\n for(i = 0; i < array_size; i++)\n cursors_[i] = wl_cursor_theme_get_cursor(cursor_theme_, cursor_names[i]);\n}\n\nvoid WaylandDisplay::DestroyCursors()\n{\n if(cursor_theme_)\n {\n wl_cursor_theme_destroy(cursor_theme_);\n cursor_theme_ = NULL;\n }\n\n if(cursors_)\n {\n delete[] cursors_;\n cursors_ = NULL;\n }\n}\n\nvoid WaylandDisplay::SetPointerImage(WaylandInputDevice *device, uint32_t time, int index)\n{\n struct wl_buffer *buffer;\n struct wl_cursor *cursor;\n struct wl_cursor_image *image;\n\n if (index == device->GetCurrentPointerImage())\n return;\n\n cursor = cursors_[index];\n if (!cursor)\n return;\n\n image = cursor->images[0];\n buffer = wl_cursor_image_get_buffer(image);\n if (!buffer)\n return;\n\n device->SetCurrentPointerImage(index);\n \/\/ TODO:\n \/\/ wl_pointer_set_cursor(device->GetPointer(), time, buffer,\n \/\/ image->hotspot_x, image->hotspot_y);\n}\n\ncairo_surface_t* WaylandDisplay::CreateSurfaceFromFile(const char *filename, gfx::Rect *rect)\n{\n return NULL;\n}\n\nvoid WaylandDisplay::AddWindowCallback(const wl_callback_listener *listener, WaylandWindow *window)\n{\n wl_callback *cb;\n cb = wl_display_sync(display_);\n wl_callback_add_listener(cb, listener, window);\n}\n\ncairo_surface_t* WaylandDisplay::CreateSurface(wl_surface *surface, gfx::Rect *rect, uint32_t flags)\n{\n return NULL;\n}\n\n} \/\/ namespace ui\nTrack Chromium base\/message_loop headers directory change\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ozone\/wayland_display.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ozone\/wayland_input_device.h\"\n#include \"ozone\/wayland_screen.h\"\n#include \"ozone\/wayland_window.h\"\n#include \"ozone\/wayland_input_method_event_filter.h\"\n#include \"base\/message_loop\/message_loop.h\"\n\n#ifdef USE_CAIRO_GLESV2\n#include \n#include \n#else\n#include \n#endif\n\n#include \n#include \n\nnamespace ui {\n\nWaylandDisplay* g_display = NULL;\n\nWaylandDisplay* WaylandDisplay::GetDisplay()\n{\n if (!g_display)\n g_display = WaylandDisplay::Connect(NULL);\n return g_display;\n}\n\nvoid WaylandDisplay::DestroyDisplay()\n{\n if(g_display)\n delete g_display;\n g_display = NULL;\n}\n\n\/\/ static\nWaylandDisplay* WaylandDisplay::Connect(char* name)\n{\n static const struct wl_registry_listener registry_listener = {\n WaylandDisplay::DisplayHandleGlobal\n };\n\n WaylandDisplay* display = new WaylandDisplay(name);\n if (!display->display_) {\n delete display;\n return NULL;\n }\n\n wl_display_set_user_data(display->display_, display);\n\n display->registry_ = wl_display_get_registry(display->display_);\n wl_registry_add_listener(display->registry_, ®istry_listener, display);\n\n wl_display_dispatch(display->display_);\n\n display->CreateCursors();\n\n return display;\n}\n\nvoid WaylandDisplay::AddWindow(WaylandWindow* window)\n{\n if(window)\n window_list_.push_back(window);\n}\n\nvoid WaylandDisplay::AddTask(WaylandTask* task)\n{\n if(task)\n task_list_.push_back(task);\n}\n\nvoid WaylandDisplay::ProcessTasks()\n{\n WaylandTask *task = NULL;\n\n while(!task_list_.empty())\n {\n task = task_list_.front();\n task->Run();\n task_list_.pop_front();\n delete task;\n }\n}\n\nvoid WaylandDisplay::RemoveWindow(WaylandWindow* window)\n{\n if(!window)\n return;\n\n WaylandTask *task = NULL;\n\n for (std::list::iterator i = task_list_.begin();\n i != task_list_.end(); ++i) {\n if((*i)->GetWindow() == window)\n {\n delete *i;\n i = task_list_.erase(i);\n }\n }\n\n for (std::list::iterator i = window_list_.begin();\n i != window_list_.end(); ++i) {\n if((*i) == window)\n {\n i = window_list_.erase(i);\n break;\n }\n }\n\n if(window_list_.size() < 1)\n {\n base::MessageLoop::current()->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());\n }\n}\n\nbool WaylandDisplay::IsWindow(WaylandWindow* window)\n{\n for (std::list::iterator i = window_list_.begin();\n i != window_list_.end(); ++i) {\n if((*i) == window)\n {\n return true;\n }\n }\n\n return false;\n}\n\nInputMethod* WaylandDisplay::GetInputMethod() const\n{\n return input_method_filter_ ? input_method_filter_->GetInputMethod(): NULL;\n}\n\n\/\/ static\nWaylandDisplay* WaylandDisplay::GetDisplay(wl_display* display)\n{\n return static_cast(wl_display_get_user_data(display));\n}\n\nWaylandDisplay::WaylandDisplay(char* name) : display_(NULL),\n cursor_theme_(NULL),\n cursors_(NULL),\n compositor_(NULL),\n shell_(NULL),\n shm_(NULL)\n{\n display_ = wl_display_connect(name);\n input_method_filter_ = new WaylandInputMethodEventFilter;\n}\n\nWaylandDisplay::~WaylandDisplay()\n{\n if (window_list_.size() > 0)\n fprintf(stderr, \"toytoolkit warning: windows exist.\\n\");\n\n if (task_list_.size() > 0)\n fprintf(stderr, \"toytoolkit warning: deferred tasks exist.\\n\");\n\n for (std::list::iterator i = input_list_.begin();\n i != input_list_.end(); ++i) {\n delete *i;\n }\n\n for (std::list::iterator i = screen_list_.begin();\n i != screen_list_.end(); ++i) {\n delete *i;\n }\n\n DestroyCursors();\n\n if (compositor_)\n wl_compositor_destroy(compositor_);\n if (shell_)\n wl_shell_destroy(shell_);\n if (shm_)\n wl_shm_destroy(shm_);\n if (display_)\n wl_display_disconnect(display_);\n\n delete input_method_filter_;\n}\n\nwl_surface* WaylandDisplay::CreateSurface()\n{\n return wl_compositor_create_surface(compositor_);\n}\n\nstd::list WaylandDisplay::GetScreenList() const {\n return screen_list_;\n}\n\n\/\/ static\nvoid WaylandDisplay::DisplayHandleGlobal(void *data,\n struct wl_registry *registry,\n uint32_t name,\n const char *interface,\n uint32_t version)\n{\n\n WaylandDisplay* disp = static_cast(data);\n\n if (strcmp(interface, \"wl_compositor\") == 0) {\n disp->compositor_ = static_cast(\n wl_registry_bind(registry, name, &wl_compositor_interface, 1));\n } else if (strcmp(interface, \"wl_output\") == 0) {\n WaylandScreen* screen = new WaylandScreen(disp, name);\n disp->screen_list_.push_back(screen);\n } else if (strcmp(interface, \"wl_seat\") == 0) {\n WaylandInputDevice *input_device = new WaylandInputDevice(disp, name);\n disp->input_list_.push_back(input_device);\n } else if (strcmp(interface, \"wl_shell\") == 0) {\n disp->shell_ = static_cast(\n wl_registry_bind(registry, name, &wl_shell_interface, 1));\n } else if (strcmp(interface, \"wl_shm\") == 0) {\n disp->shm_ = static_cast(\n wl_registry_bind(registry, name, &wl_shm_interface, 1));\n }\n}\n\nstatic const char *cursor_names[] = {\n \"bottom_left_corner\",\n \"bottom_right_corner\",\n \"bottom_side\",\n \"grabbing\",\n \"left_ptr\",\n \"left_side\",\n \"right_side\",\n \"top_left_corner\",\n \"top_right_corner\",\n \"top_side\",\n \"xterm\",\n \"hand1\",\n};\n\nvoid WaylandDisplay::CreateCursors()\n{\n unsigned int i, array_size = sizeof(cursor_names) \/ sizeof(cursor_names[0]);\n cursor_theme_ = wl_cursor_theme_load(NULL, 32, shm_);\n cursors_ = new wl_cursor*[array_size];\n memset(cursors_, 0, sizeof(wl_cursor*) * array_size);\n\n for(i = 0; i < array_size; i++)\n cursors_[i] = wl_cursor_theme_get_cursor(cursor_theme_, cursor_names[i]);\n}\n\nvoid WaylandDisplay::DestroyCursors()\n{\n if(cursor_theme_)\n {\n wl_cursor_theme_destroy(cursor_theme_);\n cursor_theme_ = NULL;\n }\n\n if(cursors_)\n {\n delete[] cursors_;\n cursors_ = NULL;\n }\n}\n\nvoid WaylandDisplay::SetPointerImage(WaylandInputDevice *device, uint32_t time, int index)\n{\n struct wl_buffer *buffer;\n struct wl_cursor *cursor;\n struct wl_cursor_image *image;\n\n if (index == device->GetCurrentPointerImage())\n return;\n\n cursor = cursors_[index];\n if (!cursor)\n return;\n\n image = cursor->images[0];\n buffer = wl_cursor_image_get_buffer(image);\n if (!buffer)\n return;\n\n device->SetCurrentPointerImage(index);\n \/\/ TODO:\n \/\/ wl_pointer_set_cursor(device->GetPointer(), time, buffer,\n \/\/ image->hotspot_x, image->hotspot_y);\n}\n\ncairo_surface_t* WaylandDisplay::CreateSurfaceFromFile(const char *filename, gfx::Rect *rect)\n{\n return NULL;\n}\n\nvoid WaylandDisplay::AddWindowCallback(const wl_callback_listener *listener, WaylandWindow *window)\n{\n wl_callback *cb;\n cb = wl_display_sync(display_);\n wl_callback_add_listener(cb, listener, window);\n}\n\ncairo_surface_t* WaylandDisplay::CreateSurface(wl_surface *surface, gfx::Rect *rect, uint32_t flags)\n{\n return NULL;\n}\n\n} \/\/ namespace ui\n<|endoftext|>"} {"text":"Prevent div by zero.<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: 2008-05-30\n Version: 2.2.0\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbSIXSTraits.h\"\n\n#include \"otb_6S.h\"\n#include \"main_6s.h\"\n#include \"otbMacro.h\"\n\n#include \n\nnamespace otb\n{\n\nvoid\nSIXSTraits::ComputeAtmosphericParameters(\n const double SolarZenithalAngle, \/** The Solar zenithal angle *\/\n const double SolarAzimutalAngle, \/** The Solar azimutal angle *\/\n const double ViewingZenithalAngle, \/** The Viewing zenithal angle *\/\n const double ViewingAzimutalAngle, \/** The Viewing azimutal angle *\/\n const unsigned int Month, \/** The Month *\/\n const unsigned int Day, \/** The Day (in the month) *\/\n const double AtmosphericPressure, \/** The Atmospheric pressure *\/\n const double WaterVaporAmount, \/** The Water vapor amount (Total water vapor content over vertical atmospheric column) *\/\n const double OzoneAmount, \/** The Ozone amount (Stratospheric ozone layer content) *\/\n const AerosolModelType& AerosolModel, \/** The Aerosol model *\/\n const double AerosolOptical, \/** The Aerosol optical (radiative impact of aerosol for the reference wavelength 550-nm) *\/\n WavelengthSpectralType* WavelengthSpectralBand, \/** Wavelength for the spectral band definition *\/\n \/** Note : The Max wavelength spectral band value must be updated ! *\/\n double& AtmosphericReflectance, \/** Atmospheric reflectance *\/\n double& AtmosphericSphericalAlbedo, \/** atmospheric spherical albedo *\/\n double& TotalGaseousTransmission, \/** Total gaseous transmission *\/\n double& DownwardTransmittance, \/** downward transmittance *\/\n double& UpwardTransmittance, \/** upward transmittance *\/\n double& UpwardDiffuseTransmittance, \/** upward diffuse transmittance *\/\n double& UpwardDirectTransmittance, \/** Upward direct transmittance *\/\n double& UpwardDiffuseTransmittanceForRayleigh, \/** upward diffuse transmittance for rayleigh *\/\n double& UpwardDiffuseTransmittanceForAerosol \/** supward diffuse transmittance for aerosols *\/\n )\n{\n\/\/ geometrical conditions\n otb_6s_doublereal asol(static_cast(SolarZenithalAngle));\n otb_6s_doublereal phi0(static_cast(SolarAzimutalAngle));\n otb_6s_doublereal avis(static_cast(ViewingZenithalAngle));\n otb_6s_doublereal phiv(static_cast(ViewingAzimutalAngle));\n otb_6s_integer month(static_cast(Month));\n otb_6s_integer jday(static_cast(Day));\n otb_6s_doublereal pressure(static_cast(AtmosphericPressure));\n otb_6s_doublereal uw(static_cast(WaterVaporAmount));\n otb_6s_doublereal uo3(static_cast(OzoneAmount));\n\/\/ atmospheric model\n otb_6s_integer iaer(static_cast(AerosolModel));\n otb_6s_doublereal taer55(static_cast(AerosolOptical));\n\n \/\/ Init output parameters\n AtmosphericReflectance = 0.;\n AtmosphericSphericalAlbedo = 0.;\n TotalGaseousTransmission = 0.;\n DownwardTransmittance = 0.;\n UpwardTransmittance = 0.;\n UpwardDiffuseTransmittance = 0.;\n UpwardDirectTransmittance = 0.;\n UpwardDiffuseTransmittanceForRayleigh = 0.;\n UpwardDiffuseTransmittanceForAerosol = 0.;\n\n otb_6s_doublereal wlinf(0.), wlsup(0.);\n otb_6s_doublereal otb_ratm__(0.), sast(0.), tgasm(0.), sdtott(0.), sutott(0.);\n otb_6s_doublereal tdif_up(0.), tdir_up(0.), tdif_up_ray(0.), tdif_up_aer(0.);\n\n \/\/ 6S official Wavelength Spectral Band step value\n const float SIXSStepOfWavelengthSpectralBandValues = .0025;\n \/\/ Generate 6s Wavelength Spectral Band with the offcicial step value\n ComputeWavelengthSpectralBandValuesFor6S(SIXSStepOfWavelengthSpectralBandValues,\n WavelengthSpectralBand \/\/ Update\n );\n try\n {\n\n \/\/ 6S official tab size Wavelength Spectral\n const otb_6s_integer S_6S_SIZE = 1501;\n \/\/ Generate WavelengthSpectralBand in 6S compatible buffer s[1501]\n wlinf = static_cast(WavelengthSpectralBand->GetMinSpectralValue());\n wlsup = static_cast(WavelengthSpectralBand->GetMaxSpectralValue());\n otb_6s_integer iinf =\n static_cast((wlinf - (float) .25) \/ SIXSStepOfWavelengthSpectralBandValues + (float) 1.5);\n otb_6s_integer cpt = iinf - 1;\n otb_6s_doublereal * s(ITK_NULLPTR);\n s = new otb_6s_doublereal[S_6S_SIZE];\n memset(s, 0, S_6S_SIZE * sizeof(otb_6s_doublereal));\n const ValuesVectorType& FilterFunctionValues6S = WavelengthSpectralBand->GetFilterFunctionValues6S();\n \/\/ Set the values of FilterFunctionValues6S in s between [iinf-1; isup]\n for (unsigned int i = 0; i < FilterFunctionValues6S.size() && cpt < S_6S_SIZE; ++i)\n {\n s[cpt] = FilterFunctionValues6S[i];\n ++cpt;\n }\n\n \/\/ Call 6s main function\n otbMsgDevMacro(<< \"Start call 6S main function ...\");\n otb_6s_ssssss_otb_main_function(&asol, &phi0, &avis, &phiv, &month, &jday,\n &pressure, &uw, &uo3,\n &iaer,\n &taer55,\n &wlinf, &wlsup,\n s,\n &otb_ratm__,\n &sast,\n &tgasm,\n &sdtott,\n &sutott,\n &tdif_up,\n &tdir_up,\n &tdif_up_ray,\n &tdif_up_aer);\n otbMsgDevMacro(<< \"Done call 6S main function!\");\n delete[] s;\n s = ITK_NULLPTR;\n }\n catch (std::bad_alloc& err)\n {\n itkGenericExceptionMacro(<< \"Exception bad_alloc in SIXSTraits class: \" << (char*) err.what());\n }\n catch (...)\n {\n itkGenericExceptionMacro(<< \"Unknown exception in SIXSTraits class (catch(...)\");\n }\n\n \/\/ Set outputs parameters\n AtmosphericReflectance = static_cast(otb_ratm__);\n AtmosphericSphericalAlbedo = static_cast(sast);\n TotalGaseousTransmission = static_cast(tgasm);\n DownwardTransmittance = static_cast(sdtott);\n UpwardTransmittance = static_cast(sutott);\n UpwardDiffuseTransmittance = static_cast(tdif_up);\n UpwardDirectTransmittance = static_cast(tdir_up);\n UpwardDiffuseTransmittanceForRayleigh = static_cast(tdif_up_ray);\n UpwardDiffuseTransmittanceForAerosol = static_cast(tdif_up_aer);\n}\n\nvoid\nSIXSTraits::ComputeWavelengthSpectralBandValuesFor6S(\n const double SIXSStepOfWavelengthSpectralBandValues,\n WavelengthSpectralType* WavelengthSpectralBand\n )\n{\n const double epsilon(.000001);\n const double L_min = static_cast(WavelengthSpectralBand->GetMinSpectralValue());\n const double L_max = static_cast(WavelengthSpectralBand->GetMaxSpectralValue());\n const double L_userStep = static_cast(WavelengthSpectralBand->GetUserStep());\n const ValuesVectorType& FilterFunctionValues = WavelengthSpectralBand->GetFilterFunctionValues();\n unsigned int i = 1;\n unsigned int j = 1;\n const double invStep = static_cast(1. \/ L_userStep);\n double value(0.);\n\n if (FilterFunctionValues.size() <= 1)\n {\n itkGenericExceptionMacro(<< \"The FilterFunctionValues vector must have more than 1 values !\");\n }\n if (! (L_min + static_cast(FilterFunctionValues.size() - 1) * L_userStep < (L_max + epsilon) ) )\n {\n itkGenericExceptionMacro(\n << \"The following condition: \" << L_min << \"+(\" << FilterFunctionValues.size() << \"-1)*\" << L_userStep <<\n \" < (\" << L_max << \"+\" << epsilon << \") is not respected !\" << \"val1 \" << L_min + static_cast(FilterFunctionValues.size() - 1) * L_userStep << \" val2 \" << L_max - epsilon);\n }\n\n \/\/ Generate WavelengthSpectralBand if the step is not the offical 6S step value\n if (vcl_abs(L_userStep - SIXSStepOfWavelengthSpectralBandValues) > epsilon)\n {\n ValuesVectorType values(1, FilterFunctionValues[0]); \/\/vector size 1 with the value vect[0]\n\n \/\/ Stop the interpolation at the max spectral value.\n value = SIXSStepOfWavelengthSpectralBandValues;\n while (L_min + value <= L_max)\n {\n \/\/ Search the User interval that surround the StepOfWavelengthSpectralBandValues current value.\n\n \/\/ removed the <= here, might be wrong\n while (j * L_userStep < value)\n {\n ++j;\n }\n\n \/\/ Check if we are not out of bound\n if (j >= FilterFunctionValues.size())\n {\n itkGenericExceptionMacro(\n << \"Index \" << j << \" out of bound for FilterFunctionValues vector (size: \" << FilterFunctionValues.size() <<\n \").\" << \" and value is \" << value << \" and SIXSStepOfWavelengthSpectralBandValues is \" << SIXSStepOfWavelengthSpectralBandValues<< \" and i is \" << i);\n }\n\n double valueTemp;\n valueTemp = static_cast(FilterFunctionValues[j - 1])\n + ((static_cast(FilterFunctionValues[j]) -\n static_cast(FilterFunctionValues[j - 1])) * invStep)\n * (value - L_userStep * (j - 1));\n values.push_back(static_cast(valueTemp));\n\n ++i;\n value += SIXSStepOfWavelengthSpectralBandValues;\n }\n\n if (L_min + (i - 1) * SIXSStepOfWavelengthSpectralBandValues != L_max)\n {\n values.push_back(0);\n }\n \/\/ Store this values\n WavelengthSpectralBand->SetFilterFunctionValues6S(values);\n \/\/ Store the new Max MaxSpectralValue\n WavelengthSpectralBand->SetMaxSpectralValue(static_cast(L_min + i *\n SIXSStepOfWavelengthSpectralBandValues));\n\n }\n else\n {\n \/\/ Init with copy of FilterFunctionValues input vector values\n WavelengthSpectralBand->SetFilterFunctionValues6S(FilterFunctionValues);\n }\n}\n\nvoid\nSIXSTraits::ComputeEnvironmentalContribution(const double diffuseTransmittanceForRayleighScattering,\n const double diffuseTransmittanceForAerosolScattering,\n const double radiusInKilometers,\n const double altitude,\n const double cosineOfViewingAngle,\n double& rayleighEstimation,\n double& aerosolEstimation,\n double& globalEstimation)\n{\n otb_6s_doublereal difr(static_cast(diffuseTransmittanceForRayleighScattering));\n otb_6s_doublereal difa(static_cast(diffuseTransmittanceForAerosolScattering));\n otb_6s_doublereal rad(static_cast(radiusInKilometers));\n otb_6s_doublereal palt(static_cast(altitude));\n otb_6s_doublereal xmuv(static_cast(cosineOfViewingAngle));\n otb_6s_doublereal fra(0.), fae(0.), fr(0.);\n otb_6s_enviro_(&difr, &difa, &rad, &palt, &xmuv, &fra, &fae, &fr);\n rayleighEstimation = static_cast(fra);\n aerosolEstimation = static_cast(fae);\n globalEstimation = static_cast(fr);\n}\n\n} \/\/ namespace otb\nBUG: use non-pointer array inside try\/catch\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: 2008-05-30\n Version: 2.2.0\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbSIXSTraits.h\"\n\n#include \"otb_6S.h\"\n#include \"main_6s.h\"\n#include \"otbMacro.h\"\n\n#include \n\nnamespace otb\n{\n\nvoid\nSIXSTraits::ComputeAtmosphericParameters(\n const double SolarZenithalAngle, \/** The Solar zenithal angle *\/\n const double SolarAzimutalAngle, \/** The Solar azimutal angle *\/\n const double ViewingZenithalAngle, \/** The Viewing zenithal angle *\/\n const double ViewingAzimutalAngle, \/** The Viewing azimutal angle *\/\n const unsigned int Month, \/** The Month *\/\n const unsigned int Day, \/** The Day (in the month) *\/\n const double AtmosphericPressure, \/** The Atmospheric pressure *\/\n const double WaterVaporAmount, \/** The Water vapor amount (Total water vapor content over vertical atmospheric column) *\/\n const double OzoneAmount, \/** The Ozone amount (Stratospheric ozone layer content) *\/\n const AerosolModelType& AerosolModel, \/** The Aerosol model *\/\n const double AerosolOptical, \/** The Aerosol optical (radiative impact of aerosol for the reference wavelength 550-nm) *\/\n WavelengthSpectralType* WavelengthSpectralBand, \/** Wavelength for the spectral band definition *\/\n \/** Note : The Max wavelength spectral band value must be updated ! *\/\n double& AtmosphericReflectance, \/** Atmospheric reflectance *\/\n double& AtmosphericSphericalAlbedo, \/** atmospheric spherical albedo *\/\n double& TotalGaseousTransmission, \/** Total gaseous transmission *\/\n double& DownwardTransmittance, \/** downward transmittance *\/\n double& UpwardTransmittance, \/** upward transmittance *\/\n double& UpwardDiffuseTransmittance, \/** upward diffuse transmittance *\/\n double& UpwardDirectTransmittance, \/** Upward direct transmittance *\/\n double& UpwardDiffuseTransmittanceForRayleigh, \/** upward diffuse transmittance for rayleigh *\/\n double& UpwardDiffuseTransmittanceForAerosol \/** supward diffuse transmittance for aerosols *\/\n )\n{\n\/\/ geometrical conditions\n otb_6s_doublereal asol(static_cast(SolarZenithalAngle));\n otb_6s_doublereal phi0(static_cast(SolarAzimutalAngle));\n otb_6s_doublereal avis(static_cast(ViewingZenithalAngle));\n otb_6s_doublereal phiv(static_cast(ViewingAzimutalAngle));\n otb_6s_integer month(static_cast(Month));\n otb_6s_integer jday(static_cast(Day));\n otb_6s_doublereal pressure(static_cast(AtmosphericPressure));\n otb_6s_doublereal uw(static_cast(WaterVaporAmount));\n otb_6s_doublereal uo3(static_cast(OzoneAmount));\n\/\/ atmospheric model\n otb_6s_integer iaer(static_cast(AerosolModel));\n otb_6s_doublereal taer55(static_cast(AerosolOptical));\n\n \/\/ Init output parameters\n AtmosphericReflectance = 0.;\n AtmosphericSphericalAlbedo = 0.;\n TotalGaseousTransmission = 0.;\n DownwardTransmittance = 0.;\n UpwardTransmittance = 0.;\n UpwardDiffuseTransmittance = 0.;\n UpwardDirectTransmittance = 0.;\n UpwardDiffuseTransmittanceForRayleigh = 0.;\n UpwardDiffuseTransmittanceForAerosol = 0.;\n\n otb_6s_doublereal wlinf(0.), wlsup(0.);\n otb_6s_doublereal otb_ratm__(0.), sast(0.), tgasm(0.), sdtott(0.), sutott(0.);\n otb_6s_doublereal tdif_up(0.), tdir_up(0.), tdif_up_ray(0.), tdif_up_aer(0.);\n\n \/\/ 6S official Wavelength Spectral Band step value\n const float SIXSStepOfWavelengthSpectralBandValues = .0025;\n \/\/ Generate 6s Wavelength Spectral Band with the offcicial step value\n ComputeWavelengthSpectralBandValuesFor6S(SIXSStepOfWavelengthSpectralBandValues,\n WavelengthSpectralBand \/\/ Update\n );\n try\n {\n\n \/\/ 6S official tab size Wavelength Spectral\n const otb_6s_integer S_6S_SIZE = 1501;\n \/\/ Generate WavelengthSpectralBand in 6S compatible buffer s[1501]\n wlinf = static_cast(WavelengthSpectralBand->GetMinSpectralValue());\n wlsup = static_cast(WavelengthSpectralBand->GetMaxSpectralValue());\n otb_6s_integer iinf =\n static_cast((wlinf - (float) .25) \/ SIXSStepOfWavelengthSpectralBandValues + (float) 1.5);\n otb_6s_integer cpt = iinf - 1;\n otb_6s_doublereal s[S_6S_SIZE];\n const ValuesVectorType& FilterFunctionValues6S = WavelengthSpectralBand->GetFilterFunctionValues6S();\n \/\/ Set the values of FilterFunctionValues6S in s between [iinf-1; isup]\n for (unsigned int i = 0; i < FilterFunctionValues6S.size() && cpt < S_6S_SIZE; ++i)\n {\n s[cpt] = FilterFunctionValues6S[i];\n ++cpt;\n }\n\n \/\/ Call 6s main function\n otbMsgDevMacro(<< \"Start call 6S main function ...\");\n otb_6s_ssssss_otb_main_function(&asol, &phi0, &avis, &phiv, &month, &jday,\n &pressure, &uw, &uo3,\n &iaer,\n &taer55,\n &wlinf, &wlsup,\n s,\n &otb_ratm__,\n &sast,\n &tgasm,\n &sdtott,\n &sutott,\n &tdif_up,\n &tdir_up,\n &tdif_up_ray,\n &tdif_up_aer);\n otbMsgDevMacro(<< \"Done call 6S main function!\");\n }\n catch (std::bad_alloc& err)\n {\n itkGenericExceptionMacro(<< \"Exception bad_alloc in SIXSTraits class: \" << (char*) err.what());\n }\n catch (...)\n {\n itkGenericExceptionMacro(<< \"Unknown exception in SIXSTraits class (catch(...)\");\n }\n\n \/\/ Set outputs parameters\n AtmosphericReflectance = static_cast(otb_ratm__);\n AtmosphericSphericalAlbedo = static_cast(sast);\n TotalGaseousTransmission = static_cast(tgasm);\n DownwardTransmittance = static_cast(sdtott);\n UpwardTransmittance = static_cast(sutott);\n UpwardDiffuseTransmittance = static_cast(tdif_up);\n UpwardDirectTransmittance = static_cast(tdir_up);\n UpwardDiffuseTransmittanceForRayleigh = static_cast(tdif_up_ray);\n UpwardDiffuseTransmittanceForAerosol = static_cast(tdif_up_aer);\n}\n\nvoid\nSIXSTraits::ComputeWavelengthSpectralBandValuesFor6S(\n const double SIXSStepOfWavelengthSpectralBandValues,\n WavelengthSpectralType* WavelengthSpectralBand\n )\n{\n const double epsilon(.000001);\n const double L_min = static_cast(WavelengthSpectralBand->GetMinSpectralValue());\n const double L_max = static_cast(WavelengthSpectralBand->GetMaxSpectralValue());\n const double L_userStep = static_cast(WavelengthSpectralBand->GetUserStep());\n const ValuesVectorType& FilterFunctionValues = WavelengthSpectralBand->GetFilterFunctionValues();\n unsigned int i = 1;\n unsigned int j = 1;\n const double invStep = static_cast(1. \/ L_userStep);\n double value(0.);\n\n if (FilterFunctionValues.size() <= 1)\n {\n itkGenericExceptionMacro(<< \"The FilterFunctionValues vector must have more than 1 values !\");\n }\n if (! (L_min + static_cast(FilterFunctionValues.size() - 1) * L_userStep < (L_max + epsilon) ) )\n {\n itkGenericExceptionMacro(\n << \"The following condition: \" << L_min << \"+(\" << FilterFunctionValues.size() << \"-1)*\" << L_userStep <<\n \" < (\" << L_max << \"+\" << epsilon << \") is not respected !\" << \"val1 \" << L_min + static_cast(FilterFunctionValues.size() - 1) * L_userStep << \" val2 \" << L_max - epsilon);\n }\n\n \/\/ Generate WavelengthSpectralBand if the step is not the offical 6S step value\n if (vcl_abs(L_userStep - SIXSStepOfWavelengthSpectralBandValues) > epsilon)\n {\n ValuesVectorType values(1, FilterFunctionValues[0]); \/\/vector size 1 with the value vect[0]\n\n \/\/ Stop the interpolation at the max spectral value.\n value = SIXSStepOfWavelengthSpectralBandValues;\n while (L_min + value <= L_max)\n {\n \/\/ Search the User interval that surround the StepOfWavelengthSpectralBandValues current value.\n\n \/\/ removed the <= here, might be wrong\n while (j * L_userStep < value)\n {\n ++j;\n }\n\n \/\/ Check if we are not out of bound\n if (j >= FilterFunctionValues.size())\n {\n itkGenericExceptionMacro(\n << \"Index \" << j << \" out of bound for FilterFunctionValues vector (size: \" << FilterFunctionValues.size() <<\n \").\" << \" and value is \" << value << \" and SIXSStepOfWavelengthSpectralBandValues is \" << SIXSStepOfWavelengthSpectralBandValues<< \" and i is \" << i);\n }\n\n double valueTemp;\n valueTemp = static_cast(FilterFunctionValues[j - 1])\n + ((static_cast(FilterFunctionValues[j]) -\n static_cast(FilterFunctionValues[j - 1])) * invStep)\n * (value - L_userStep * (j - 1));\n values.push_back(static_cast(valueTemp));\n\n ++i;\n value += SIXSStepOfWavelengthSpectralBandValues;\n }\n\n if (L_min + (i - 1) * SIXSStepOfWavelengthSpectralBandValues != L_max)\n {\n values.push_back(0);\n }\n \/\/ Store this values\n WavelengthSpectralBand->SetFilterFunctionValues6S(values);\n \/\/ Store the new Max MaxSpectralValue\n WavelengthSpectralBand->SetMaxSpectralValue(static_cast(L_min + i *\n SIXSStepOfWavelengthSpectralBandValues));\n\n }\n else\n {\n \/\/ Init with copy of FilterFunctionValues input vector values\n WavelengthSpectralBand->SetFilterFunctionValues6S(FilterFunctionValues);\n }\n}\n\nvoid\nSIXSTraits::ComputeEnvironmentalContribution(const double diffuseTransmittanceForRayleighScattering,\n const double diffuseTransmittanceForAerosolScattering,\n const double radiusInKilometers,\n const double altitude,\n const double cosineOfViewingAngle,\n double& rayleighEstimation,\n double& aerosolEstimation,\n double& globalEstimation)\n{\n otb_6s_doublereal difr(static_cast(diffuseTransmittanceForRayleighScattering));\n otb_6s_doublereal difa(static_cast(diffuseTransmittanceForAerosolScattering));\n otb_6s_doublereal rad(static_cast(radiusInKilometers));\n otb_6s_doublereal palt(static_cast(altitude));\n otb_6s_doublereal xmuv(static_cast(cosineOfViewingAngle));\n otb_6s_doublereal fra(0.), fae(0.), fr(0.);\n otb_6s_enviro_(&difr, &difa, &rad, &palt, &xmuv, &fra, &fae, &fr);\n rayleighEstimation = static_cast(fra);\n aerosolEstimation = static_cast(fae);\n globalEstimation = static_cast(fr);\n}\n\n} \/\/ namespace otb\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n\/*\r\n* Copyright (c) 2007-2009 SlimDX Group\r\n* \r\n* Permission is hereby granted, free of charge, to any person obtaining a copy\r\n* of this software and associated documentation files (the \"Software\"), to deal\r\n* in the Software without restriction, including without limitation the rights\r\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n* copies of the Software, and to permit persons to whom the Software is\r\n* furnished to do so, subject to the following conditions:\r\n* \r\n* The above copyright notice and this permission notice shall be included in\r\n* all copies or substantial portions of the Software.\r\n* \r\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n* THE SOFTWARE.\r\n*\/\r\n\r\n#include \r\n\r\n#include \"BoundingBox.h\"\r\n#include \"BoundingSphere.h\"\r\n#include \"Plane.h\"\r\n#include \"Ray.h\"\r\n\r\nusing namespace System;\r\nusing namespace System::Globalization;\r\n\r\nnamespace SlimDX\r\n{\r\n\tRay::Ray( Vector3 position, Vector3 direction )\r\n\t{\r\n\t\tPosition = position;\r\n\t\tDirection = direction;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, Plane plane, [Out] float% distance )\r\n\t{\r\n\t\tfloat dotDirection = (plane.Normal.X * ray.Direction.X) + (plane.Normal.Y * ray.Direction.Y) + (plane.Normal.Z * ray.Direction.Z);\r\n\r\n\t\tif( Math::Abs( dotDirection ) < 0.000001f )\r\n\t\t{\r\n\t\t\tdistance = 0;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tfloat dotPosition = (plane.Normal.X * ray.Position.X) + (plane.Normal.Y * ray.Position.Y) + (plane.Normal.Z * ray.Position.Z);\r\n\t\tfloat num = ( -plane.D - dotPosition ) \/ dotDirection;\r\n\r\n\t\tif( num < 0.0f )\r\n\t\t{\r\n\t\t\tif( num < -0.000001f )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tnum = 0.0f;\r\n\t\t}\r\n\r\n\t\tdistance = num;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, Vector3 vertex1, Vector3 vertex2, Vector3 vertex3, [Out] float% distance )\r\n\t{\r\n\t\tFLOAT u, v;\r\n\t\tpin_ptr pinnedDist = &distance;\r\n\r\n\t\tif( D3DXIntersectTri( reinterpret_cast( &vertex1 ), \r\n\t\t\treinterpret_cast( &vertex2 ), reinterpret_cast( &vertex3 ),\r\n\t\t\treinterpret_cast( &ray.Position ), reinterpret_cast( &ray.Direction ),\r\n\t\t\t&u, &v, reinterpret_cast( pinnedDist ) ) )\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, BoundingBox box, [Out] float% distance )\r\n\t{\r\n\t\tfloat d = 0.0f;\r\n\t\tfloat maxValue = float::MaxValue;\r\n\r\n\t\tif( Math::Abs( ray.Direction.X ) < 0.0000001 )\r\n\t\t{\r\n\t\t\tif( ray.Position.X < box.Minimum.X || ray.Position.X > box.Maximum.X )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat inv = 1.0f \/ ray.Direction.X;\r\n\t\t\tfloat min = (box.Minimum.X - ray.Position.X) * inv;\r\n\t\t\tfloat max = (box.Maximum.X - ray.Position.X) * inv;\r\n\r\n\t\t\tif( min > max )\r\n\t\t\t{\r\n\t\t\t\tfloat temp = min;\r\n\t\t\t\tmin = max;\r\n\t\t\t\tmax = temp;\r\n\t\t\t}\r\n\r\n\t\t\td = Math::Max( min, d );\r\n\t\t\tmaxValue = Math::Min( max, maxValue );\r\n\r\n\t\t\tif( d > maxValue )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif( Math::Abs( ray.Direction.Y ) < 0.0000001 )\r\n\t\t{\r\n\t\t\tif( ray.Position.Y < box.Minimum.Y || ray.Position.Y > box.Maximum.Y )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat inv = 1.0f \/ ray.Direction.Y;\r\n\t\t\tfloat min = (box.Minimum.Y - ray.Position.Y) * inv;\r\n\t\t\tfloat max = (box.Maximum.Y - ray.Position.Y) * inv;\r\n\r\n\t\t\tif( min > max )\r\n\t\t\t{\r\n\t\t\t\tfloat temp = min;\r\n\t\t\t\tmin = max;\r\n\t\t\t\tmax = temp;\r\n\t\t\t}\r\n\r\n\t\t\td = Math::Max( min, d );\r\n\t\t\tmaxValue = Math::Min( max, maxValue );\r\n\r\n\t\t\tif( d > maxValue )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif( Math::Abs( ray.Direction.Z ) < 0.0000001 )\r\n\t\t{\r\n\t\t\tif( ray.Position.Z < box.Minimum.Z || ray.Position.Z > box.Maximum.Z )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat inv = 1.0f \/ ray.Direction.Z;\r\n\t\t\tfloat min = (box.Minimum.Z - ray.Position.Z) * inv;\r\n\t\t\tfloat max = (box.Maximum.Z - ray.Position.Z) * inv;\r\n\r\n\t\t\tif( min > max )\r\n\t\t\t{\r\n\t\t\t\tfloat temp = min;\r\n\t\t\t\tmin = max;\r\n\t\t\t\tmax = temp;\r\n\t\t\t}\r\n\r\n\t\t\td = Math::Max( min, d );\r\n\t\t\tmaxValue = Math::Min( max, maxValue );\r\n\r\n\t\t\tif( d > maxValue )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tdistance = d;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, BoundingSphere sphere, [Out] float% distance )\r\n\t{\r\n\t\tfloat x = sphere.Center.X - ray.Position.X;\r\n\t\tfloat y = sphere.Center.Y - ray.Position.Y;\r\n\t\tfloat z = sphere.Center.Z - ray.Position.Z;\r\n\t\tfloat pyth = (x * x) + (y * y) + (z * z);\r\n\t\tfloat rr = sphere.Radius * sphere.Radius;\r\n\r\n\t\tif( pyth <= rr )\r\n\t\t{\r\n\t\t\tdistance = 0.0f;\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tfloat dot = (x * ray.Direction.X) + (y * ray.Direction.Y) + (z * ray.Direction.Z);\r\n\t\tif( dot < 0.0f )\r\n\t\t{\r\n\t\t\tdistance = 0.0f;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tfloat temp = pyth - (dot * dot);\r\n\t\tif( temp > rr )\r\n\t\t{\r\n\t\t\tdistance = 0.0f;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tdistance = dot - static_cast( Math::Sqrt( static_cast( rr - temp ) ) );\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool Ray::operator == ( Ray left, Ray right )\r\n\t{\r\n\t\treturn Ray::Equals( left, right );\r\n\t}\r\n\r\n\tbool Ray::operator != ( Ray left, Ray right )\r\n\t{\r\n\t\treturn !Ray::Equals( left, right );\r\n\t}\r\n\r\n\tString^ Ray::ToString()\r\n\t{\r\n\t\treturn String::Format( CultureInfo::CurrentCulture, \"Position:{0} Direction:{1}\", Position.ToString(), Direction.ToString() );\r\n\t}\r\n\r\n\tint Ray::GetHashCode()\r\n\t{\r\n\t\treturn Position.GetHashCode() + Direction.GetHashCode();\r\n\t}\r\n\r\n\tbool Ray::Equals( Object^ value )\r\n\t{\r\n\t\tif( value == nullptr )\r\n\t\t\treturn false;\r\n\r\n\t\tif( value->GetType() != GetType() )\r\n\t\t\treturn false;\r\n\r\n\t\treturn Equals( safe_cast( value ) );\r\n\t}\r\n\r\n\tbool Ray::Equals( Ray value )\r\n\t{\r\n\t\treturn ( Position == value.Position && Direction == value.Direction );\r\n\t}\r\n\r\n\tbool Ray::Equals( Ray% value1, Ray% value2 )\r\n\t{\r\n\t\treturn ( value1.Position == value2.Position && value1.Direction == value2.Direction );\r\n\t}\r\n}Patching ray intersection methods to normalize the input ray's direction.#include \"stdafx.h\"\r\n\/*\r\n* Copyright (c) 2007-2009 SlimDX Group\r\n* \r\n* Permission is hereby granted, free of charge, to any person obtaining a copy\r\n* of this software and associated documentation files (the \"Software\"), to deal\r\n* in the Software without restriction, including without limitation the rights\r\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n* copies of the Software, and to permit persons to whom the Software is\r\n* furnished to do so, subject to the following conditions:\r\n* \r\n* The above copyright notice and this permission notice shall be included in\r\n* all copies or substantial portions of the Software.\r\n* \r\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n* THE SOFTWARE.\r\n*\/\r\n\r\n#include \r\n\r\n#include \"BoundingBox.h\"\r\n#include \"BoundingSphere.h\"\r\n#include \"Plane.h\"\r\n#include \"Ray.h\"\r\n\r\nusing namespace System;\r\nusing namespace System::Globalization;\r\n\r\nnamespace SlimDX\r\n{\r\n\tRay::Ray( Vector3 position, Vector3 direction )\r\n\t{\r\n\t\tPosition = position;\r\n\t\tDirection = direction;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, Plane plane, [Out] float% distance )\r\n\t{\r\n\t\tray.Direction.Normalize();\r\n\t\tfloat dotDirection = (plane.Normal.X * ray.Direction.X) + (plane.Normal.Y * ray.Direction.Y) + (plane.Normal.Z * ray.Direction.Z);\r\n\r\n\t\tif( Math::Abs( dotDirection ) < 0.000001f )\r\n\t\t{\r\n\t\t\tdistance = 0;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tfloat dotPosition = (plane.Normal.X * ray.Position.X) + (plane.Normal.Y * ray.Position.Y) + (plane.Normal.Z * ray.Position.Z);\r\n\t\tfloat num = ( -plane.D - dotPosition ) \/ dotDirection;\r\n\r\n\t\tif( num < 0.0f )\r\n\t\t{\r\n\t\t\tif( num < -0.000001f )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\tnum = 0.0f;\r\n\t\t}\r\n\r\n\t\tdistance = num;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, Vector3 vertex1, Vector3 vertex2, Vector3 vertex3, [Out] float% distance )\r\n\t{\r\n\t\tFLOAT u, v;\r\n\t\tpin_ptr pinnedDist = &distance;\r\n\r\n\t\tif( D3DXIntersectTri( reinterpret_cast( &vertex1 ), \r\n\t\t\treinterpret_cast( &vertex2 ), reinterpret_cast( &vertex3 ),\r\n\t\t\treinterpret_cast( &ray.Position ), reinterpret_cast( &ray.Direction ),\r\n\t\t\t&u, &v, reinterpret_cast( pinnedDist ) ) )\r\n\t\t\treturn true;\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, BoundingBox box, [Out] float% distance )\r\n\t{\r\n\t\tfloat d = 0.0f;\r\n\t\tfloat maxValue = float::MaxValue;\r\n\r\n\t\tray.Direction.Normalize();\r\n\t\tif( Math::Abs( ray.Direction.X ) < 0.0000001 )\r\n\t\t{\r\n\t\t\tif( ray.Position.X < box.Minimum.X || ray.Position.X > box.Maximum.X )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat inv = 1.0f \/ ray.Direction.X;\r\n\t\t\tfloat min = (box.Minimum.X - ray.Position.X) * inv;\r\n\t\t\tfloat max = (box.Maximum.X - ray.Position.X) * inv;\r\n\r\n\t\t\tif( min > max )\r\n\t\t\t{\r\n\t\t\t\tfloat temp = min;\r\n\t\t\t\tmin = max;\r\n\t\t\t\tmax = temp;\r\n\t\t\t}\r\n\r\n\t\t\td = Math::Max( min, d );\r\n\t\t\tmaxValue = Math::Min( max, maxValue );\r\n\r\n\t\t\tif( d > maxValue )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif( Math::Abs( ray.Direction.Y ) < 0.0000001 )\r\n\t\t{\r\n\t\t\tif( ray.Position.Y < box.Minimum.Y || ray.Position.Y > box.Maximum.Y )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat inv = 1.0f \/ ray.Direction.Y;\r\n\t\t\tfloat min = (box.Minimum.Y - ray.Position.Y) * inv;\r\n\t\t\tfloat max = (box.Maximum.Y - ray.Position.Y) * inv;\r\n\r\n\t\t\tif( min > max )\r\n\t\t\t{\r\n\t\t\t\tfloat temp = min;\r\n\t\t\t\tmin = max;\r\n\t\t\t\tmax = temp;\r\n\t\t\t}\r\n\r\n\t\t\td = Math::Max( min, d );\r\n\t\t\tmaxValue = Math::Min( max, maxValue );\r\n\r\n\t\t\tif( d > maxValue )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif( Math::Abs( ray.Direction.Z ) < 0.0000001 )\r\n\t\t{\r\n\t\t\tif( ray.Position.Z < box.Minimum.Z || ray.Position.Z > box.Maximum.Z )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfloat inv = 1.0f \/ ray.Direction.Z;\r\n\t\t\tfloat min = (box.Minimum.Z - ray.Position.Z) * inv;\r\n\t\t\tfloat max = (box.Maximum.Z - ray.Position.Z) * inv;\r\n\r\n\t\t\tif( min > max )\r\n\t\t\t{\r\n\t\t\t\tfloat temp = min;\r\n\t\t\t\tmin = max;\r\n\t\t\t\tmax = temp;\r\n\t\t\t}\r\n\r\n\t\t\td = Math::Max( min, d );\r\n\t\t\tmaxValue = Math::Min( max, maxValue );\r\n\r\n\t\t\tif( d > maxValue )\r\n\t\t\t{\r\n\t\t\t\tdistance = 0.0f;\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tdistance = d;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool Ray::Intersects( Ray ray, BoundingSphere sphere, [Out] float% distance )\r\n\t{\r\n\t\tfloat x = sphere.Center.X - ray.Position.X;\r\n\t\tfloat y = sphere.Center.Y - ray.Position.Y;\r\n\t\tfloat z = sphere.Center.Z - ray.Position.Z;\r\n\t\tfloat pyth = (x * x) + (y * y) + (z * z);\r\n\t\tfloat rr = sphere.Radius * sphere.Radius;\r\n\r\n\t\tif( pyth <= rr )\r\n\t\t{\r\n\t\t\tdistance = 0.0f;\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tray.Direction.Normalize();\r\n\t\tfloat dot = (x * ray.Direction.X) + (y * ray.Direction.Y) + (z * ray.Direction.Z);\r\n\t\tif( dot < 0.0f )\r\n\t\t{\r\n\t\t\tdistance = 0.0f;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tfloat temp = pyth - (dot * dot);\r\n\t\tif( temp > rr )\r\n\t\t{\r\n\t\t\tdistance = 0.0f;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tdistance = dot - static_cast( Math::Sqrt( static_cast( rr - temp ) ) );\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool Ray::operator == ( Ray left, Ray right )\r\n\t{\r\n\t\treturn Ray::Equals( left, right );\r\n\t}\r\n\r\n\tbool Ray::operator != ( Ray left, Ray right )\r\n\t{\r\n\t\treturn !Ray::Equals( left, right );\r\n\t}\r\n\r\n\tString^ Ray::ToString()\r\n\t{\r\n\t\treturn String::Format( CultureInfo::CurrentCulture, \"Position:{0} Direction:{1}\", Position.ToString(), Direction.ToString() );\r\n\t}\r\n\r\n\tint Ray::GetHashCode()\r\n\t{\r\n\t\treturn Position.GetHashCode() + Direction.GetHashCode();\r\n\t}\r\n\r\n\tbool Ray::Equals( Object^ value )\r\n\t{\r\n\t\tif( value == nullptr )\r\n\t\t\treturn false;\r\n\r\n\t\tif( value->GetType() != GetType() )\r\n\t\t\treturn false;\r\n\r\n\t\treturn Equals( safe_cast( value ) );\r\n\t}\r\n\r\n\tbool Ray::Equals( Ray value )\r\n\t{\r\n\t\treturn ( Position == value.Position && Direction == value.Direction );\r\n\t}\r\n\r\n\tbool Ray::Equals( Ray% value1, Ray% value2 )\r\n\t{\r\n\t\treturn ( value1.Position == value2.Position && value1.Direction == value2.Direction );\r\n\t}\r\n}<|endoftext|>"} {"text":"#ifndef HMLIB_ALGORITHM_COMPARE_INC\n#define HMLIB_ALGORITHM_COMPARE_INC 201\n#\n\/*===algorithm::compare===\n大小関係のアルゴリズムを提供\nalgorithm::compare v2_00\/170207 hmIto\n\tsort_value is now renamed to sorting_swap\nalgorithm::compare v2_01\/170207 hmIto\n\tRename sort_value to sorting_swap\nalgorithm::compare v2_00\/160509 hmIto\n\tRename min\/max with multiple arguments to min_value\/max_value\n\tRename swap_sort to sort_value\nalgorithm::compare v1_00\/130328 hmIto\n\tIndepdendent from algorithm.hpp\n*\/\n#include\n#include\nnamespace hmLib{\n\t\/\/sort non-container variables\n\ttemplate\n\tinline void sorting_swap(T& val1,T& val2){\n\t\tif(val1>val2)std::swap(val1,val2);\n\t}\n\t\/\/sort non-container variables (three arguments)\n\ttemplate\n\tinline void sorting_swap(T& val1,T& val2, T& val3){\n\t\tif(val1>val2){\n\t\t\tif(val2>val3){\n\t\t\t\t\/\/val3 < val2 < val1\n\t\t\t\tstd::swap(val1,val3);\n\t\t\t}else if(val1>val3){\n\t\t\t\t\/\/val2 < val3 < val1\n\t\t\t\tstd::swap(val1,val2);\n\t\t\t\tstd::swap(val2,val3);\n\t\t\t}else{\n\t\t\t\t\/\/val2 < val1 < val3\n\t\t\t\tstd::swap(val1,val2);\n\t\t\t}\n\t\t}else{\n\t\t\tif(val1>val3){\n\t\t\t\t\/\/val3 < val1 < val2\n\t\t\t\tstd::swap(val1,val3);\n\t\t\t\tstd::swap(val2,val3);\n\t\t\t}else if(val2>val3){\n\t\t\t\t\/\/val1 < val3 < val2\n\t\t\t\tstd::swap(val2,val3);\t\t\t\t\t\n\t\t\t}else return;\n\t\t}\n\t}\n\t\/\/median value of three arguments\n\ttemplate\n\tinline constexpr T median(T val1,T val2,T val3){\n\t\tif(val1>val2){\n\t\t\tif(val2>val3)return val2;\n\t\t\telse if(val1>val3)return val3;\n\t\t\telse return val1;\n\t\t}else{\n\t\t\tif(val1>val3)return val1;\n\t\t\telse if(val2>val3)return val3;\n\t\t\telse return val2;\n\t\t}\n\t}\n\n\t\/\/clamp value by lower and upper\n\ttemplate\n\tinline constexpr T clamp(T val, T lower, T upper) {\n\t\treturn std::min(std::max(lower, val), upper);\n\t}\n\n\ttemplate\n\tinline constexpr T min_value(T val1,T val2,Others... vals){return std::min(val1,min_value(val2,vals...));}\n\ttemplate\n\tinline constexpr T min_value(T val){return val;}\n\ttemplate\n\tinline constexpr T max_value(T val1,T val2,Others... vals){return std::max(val1,max_value(val2,vals...));}\n\ttemplate\n\tinline constexpr T max_value(T val){return val;}\n\t\n\t\/\/mod with positive value\n\ttemplate\n\t[[deprecated(\"please use euclidean_mod() function\")]]\n\tinline T positive_mod(T num,T divisor){\n\t\tnum %= divisor;\n\t\tif(num < 0)return num + divisor;\n\t\treturn num;\n\t}\n\n\ttemplate\n\tinline T euclidean_mod(T n, T divisor){\n\t\tn %= divisor;\n\t\tif(n < 0)return n + divisor;\n\t\treturn n;\n\t}\n\ttemplate\n\tinline T euclidean_div(T n, T divisor){\n\t\treturn (n-euclidean_mod(n,divisor))\/divisor;\n\t}\n\ttemplate\n\tinline std::pair eucledian_divmod(T n, T divisor){\n\t\tT m = euclidean_mod(n,divisor);\n\t\treturn std::pair((n-m)\/divisor,m);\n\t}\n\n}\n#\n#endif\nFix: remove Japanese character #ifndef HMLIB_ALGORITHM_COMPARE_INC\n#define HMLIB_ALGORITHM_COMPARE_INC 201\n#\n\/*===algorithm::compare===\nalgorithm::compare v2_00\/170207 hmIto\n\tsort_value is now renamed to sorting_swap\nalgorithm::compare v2_01\/170207 hmIto\n\tRename sort_value to sorting_swap\nalgorithm::compare v2_00\/160509 hmIto\n\tRename min\/max with multiple arguments to min_value\/max_value\n\tRename swap_sort to sort_value\nalgorithm::compare v1_00\/130328 hmIto\n\tIndepdendent from algorithm.hpp\n*\/\n#include\n#include\nnamespace hmLib{\n\t\/\/sort non-container variables\n\ttemplate\n\tinline void sorting_swap(T& val1,T& val2){\n\t\tif(val1>val2)std::swap(val1,val2);\n\t}\n\t\/\/sort non-container variables (three arguments)\n\ttemplate\n\tinline void sorting_swap(T& val1,T& val2, T& val3){\n\t\tif(val1>val2){\n\t\t\tif(val2>val3){\n\t\t\t\t\/\/val3 < val2 < val1\n\t\t\t\tstd::swap(val1,val3);\n\t\t\t}else if(val1>val3){\n\t\t\t\t\/\/val2 < val3 < val1\n\t\t\t\tstd::swap(val1,val2);\n\t\t\t\tstd::swap(val2,val3);\n\t\t\t}else{\n\t\t\t\t\/\/val2 < val1 < val3\n\t\t\t\tstd::swap(val1,val2);\n\t\t\t}\n\t\t}else{\n\t\t\tif(val1>val3){\n\t\t\t\t\/\/val3 < val1 < val2\n\t\t\t\tstd::swap(val1,val3);\n\t\t\t\tstd::swap(val2,val3);\n\t\t\t}else if(val2>val3){\n\t\t\t\t\/\/val1 < val3 < val2\n\t\t\t\tstd::swap(val2,val3);\t\t\t\t\t\n\t\t\t}else return;\n\t\t}\n\t}\n\t\/\/median value of three arguments\n\ttemplate\n\tinline constexpr T median(T val1,T val2,T val3){\n\t\tif(val1>val2){\n\t\t\tif(val2>val3)return val2;\n\t\t\telse if(val1>val3)return val3;\n\t\t\telse return val1;\n\t\t}else{\n\t\t\tif(val1>val3)return val1;\n\t\t\telse if(val2>val3)return val3;\n\t\t\telse return val2;\n\t\t}\n\t}\n\n\t\/\/clamp value by lower and upper\n\ttemplate\n\tinline constexpr T clamp(T val, T lower, T upper) {\n\t\treturn std::min(std::max(lower, val), upper);\n\t}\n\n\ttemplate\n\tinline constexpr T min_value(T val1,T val2,Others... vals){return std::min(val1,min_value(val2,vals...));}\n\ttemplate\n\tinline constexpr T min_value(T val){return val;}\n\ttemplate\n\tinline constexpr T max_value(T val1,T val2,Others... vals){return std::max(val1,max_value(val2,vals...));}\n\ttemplate\n\tinline constexpr T max_value(T val){return val;}\n\t\n\t\/\/mod with positive value\n\ttemplate\n\t[[deprecated(\"please use euclidean_mod() function\")]]\n\tinline T positive_mod(T num,T divisor){\n\t\tnum %= divisor;\n\t\tif(num < 0)return num + divisor;\n\t\treturn num;\n\t}\n\n\ttemplate\n\tinline T euclidean_mod(T n, T divisor){\n\t\tn %= divisor;\n\t\tif(n < 0)return n + divisor;\n\t\treturn n;\n\t}\n\ttemplate\n\tinline T euclidean_div(T n, T divisor){\n\t\treturn (n-euclidean_mod(n,divisor))\/divisor;\n\t}\n\ttemplate\n\tinline std::pair eucledian_divmod(T n, T divisor){\n\t\tT m = euclidean_mod(n,divisor);\n\t\treturn std::pair((n-m)\/divisor,m);\n\t}\n\n}\n#\n#endif\n<|endoftext|>"} {"text":"\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam .\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace bohrium {\nnamespace jitk {\n\n\/\/ Unnamed namespace for all fuser help functions\nnamespace {\n\n\/\/ Check if 'a' and 'b' supports data-parallelism when merged\nbool data_parallel_compatible(const bh_instruction *a, const bh_instruction *b)\n{\n if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))\n return true;\n\n const int a_nop = bh_noperands(a->opcode);\n for(int i=0; ioperand[0], &a->operand[i])\n && not bh_view_aligned(&b->operand[0], &a->operand[i]))\n return false;\n }\n const int b_nop = bh_noperands(b->opcode);\n for(int i=0; ioperand[0], &b->operand[i])\n && not bh_view_aligned(&a->operand[0], &b->operand[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Check if 'b1' and 'b2' supports data-parallelism when merged\nbool data_parallel_compatible(const Block &b1, const Block &b2) {\n for (const bh_instruction *i1 : b1.getAllInstr()) {\n for (const bh_instruction *i2 : b2.getAllInstr()) {\n if (not data_parallel_compatible(i1, i2))\n return false;\n }\n }\n return true;\n}\n\n\/\/ Check if 'block' accesses the output of a sweep in 'sweeps'\nbool sweeps_accessed_by_block(const set &sweeps, const Block &block) {\n for (bh_instruction *instr: sweeps) {\n assert(bh_noperands(instr->opcode) > 0);\n auto bases = block.getAllBases();\n if (bases.find(instr->operand[0].base) != bases.end())\n return true;\n }\n return false;\n}\n} \/\/ Unnamed namespace\n\n\nvector fuser_singleton(vector &instr_list, const set &news) {\n\n \/\/ Creates the _block_list based on the instr_list\n vector block_list;\n for (auto instr=instr_list.begin(); instr != instr_list.end(); ++instr) {\n int nop = bh_noperands(instr->opcode);\n if (nop == 0)\n continue; \/\/ Ignore noop instructions such as BH_NONE or BH_TALLY\n\n \/\/ Let's try to simplify the shape of the instruction\n if (instr->reshapable()) {\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n\n const int64_t totalsize = std::accumulate(dominating_shape.begin(), dominating_shape.end(), 1, \\\n std::multiplies());\n const vector shape = {totalsize};\n instr->reshape(shape);\n }\n \/\/ Let's create the block\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n int64_t size_of_rank_dim = dominating_shape[0];\n vector single_instr = {&instr[0]};\n block_list.push_back(create_nested_block(single_instr, 0, size_of_rank_dim, news));\n }\n return block_list;\n}\n\n\/\/ Merges the two blocks 'a' and 'a' (in that order)\npair block_merge(const Block &a, const Block &b, const set &news) {\n\n \/\/ First we check for data incompatibility\n if (b.isInstr() or not data_parallel_compatible(a, b) or sweeps_accessed_by_block(a._sweeps, b)) {\n return make_pair(Block(), false);\n }\n\n \/\/ Check for perfect match, which is directly mergeable\n if (a.size == b.size) {\n return make_pair(merge(a, b), true);\n }\n \/\/ Check fusibility of reshapable blocks\n if (b._reshapable && b.size % a.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, b.rank, a.size, news), true);\n }\n if (a._reshapable && a.size % b.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, a.rank, b.size, news), true);\n }\n return make_pair(Block(), false);\n}\n\nvector fuser_serial(vector &block_list, const set &news) {\n vector ret;\n for (auto it = block_list.begin(); it != block_list.end(); ) {\n ret.push_back(*it);\n Block &cur = ret.back();\n ++it;\n if (cur.isInstr()) {\n continue; \/\/ We should never fuse instruction blocks\n }\n \/\/ Let's search for fusible blocks\n for (; it != block_list.end(); ++it) {\n const pair res = block_merge(cur, *it, news);\n if (res.second) {\n cur = res.first;\n } else {\n break; \/\/ We couldn't find any shape match\n }\n }\n \/\/ Let's fuse at the next rank level\n cur._block_list = fuser_serial(cur._block_list, news);\n }\n return ret;\n}\n\nnamespace dag {\n\n\/\/The type declaration of the boost graphs, vertices and edges.\ntypedef boost::adjacency_list DAG;\ntypedef typename boost::graph_traits::edge_descriptor Edge;\ntypedef uint64_t Vertex;\n\n\/* Determines whether there exist a path from 'a' to 'b'\n *\n * Complexity: O(E + V)\n *\n * @a The first vertex\n * @b The second vertex\n * @dag The DAG\n * @only_long_path Only accept path of length greater than one\n * @return True if there is a path\n *\/\nbool path_exist(Vertex a, Vertex b, const DAG &dag, bool only_long_path) {\n using namespace boost;\n\n struct path_visitor:default_bfs_visitor {\n const Vertex dst;\n path_visitor(Vertex b):dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const {\n if(target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n struct long_visitor:default_bfs_visitor {\n const Vertex src, dst;\n long_visitor(Vertex a, Vertex b):src(a),dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const\n {\n if(source(e,g) != src and target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n try {\n if(only_long_path)\n breadth_first_search(dag, a, visitor(long_visitor(a,b)));\n else\n breadth_first_search(dag, a, visitor(path_visitor(b)));\n }\n catch (const runtime_error &e) {\n return true;\n }\n return false;\n}\n\n\nDAG from_block_list(const vector &block_list) {\n DAG graph;\n map > base2vertices;\n for (const Block &block: block_list) {\n Vertex vertex = boost::add_vertex(&block, graph);\n\n \/\/ Find all vertices that must connect to 'vertex'\n \/\/ using and updating 'base2vertices'\n set connecting_vertices;\n for (bh_base *base: block.getAllBases()) {\n set &vs = base2vertices[base];\n connecting_vertices.insert(vs.begin(), vs.end());\n vs.insert(vertex);\n }\n\n \/\/ Finally, let's add edges to 'vertex'\n BOOST_REVERSE_FOREACH (Vertex v, connecting_vertices) {\n if (vertex != v and block.depend_on(*graph[v])) {\n boost::add_edge(v, vertex, graph);\n }\n }\n }\n return graph;\n}\n\nvoid pprint(const DAG &dag, const string &filename) {\n\n \/\/We define a graph and a kernel writer for graphviz\n struct graph_writer {\n const DAG &graph;\n graph_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out) const {\n out << \"graph [bgcolor=white, fontname=\\\"Courier New\\\"]\" << endl;\n out << \"node [shape=box color=black, fontname=\\\"Courier New\\\"]\" << endl;\n }\n };\n struct kernel_writer {\n const DAG &graph;\n kernel_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Vertex& v) const {\n out << \"[label=\\\"Kernel \" << v;\n\n out << \", Instructions: \\\\l\";\n for (const bh_instruction *instr: graph[v]->getAllInstr()) {\n out << *instr << \"\\\\l\";\n }\n out << \"\\\"]\";\n }\n };\n struct edge_writer {\n const DAG &graph;\n edge_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Edge& e) const {\n\n }\n };\n\n static int count=0;\n stringstream ss;\n ss << filename << \"-\" << count++ << \".dot\";\n ofstream file;\n cout << ss.str() << endl;\n file.open(ss.str());\n boost::write_graphviz(file, dag, kernel_writer(dag), edge_writer(dag), graph_writer(dag));\n file.close();\n}\n\nvector topological(DAG &dag) {\n vector ret;\n pprint(dag, \"before\");\n\n set roots; \/\/ Set of root vertices\n \/\/ Initiate 'roots'\n BOOST_FOREACH (Vertex v, boost::vertices(dag)) {\n if (boost::in_degree(v, dag) == 0) {\n roots.insert(v);\n }\n }\n\n while (not roots.empty()) {\n pprint(dag, \"start\");\n Vertex vertex = *roots.begin();\n roots.erase(vertex);\n ret.emplace_back(*dag[vertex]);\n Block &block = ret.back();\n\n BOOST_FOREACH (Vertex v, boost::adjacent_vertices(vertex, dag)) {\n if (boost::in_degree(v, dag) <= 1) {\n roots.insert(v);\n }\n }\n boost::clear_vertex(vertex, dag);\n\n vector merged_roots;\n for (Vertex v: roots) {\n const Block &b = *dag[v];\n if (b.isInstr())\n continue;\n if (not data_parallel_compatible(block, b))\n continue;\n if (sweeps_accessed_by_block(block._sweeps, b))\n continue;\n assert(block.rank == b.rank);\n\n \/\/ Check for perfect match, which is directly mergeable\n if (block.size == b.size) {\n block = merge(block, b);\n } else {\n continue;\n }\n pprint(dag, \"merged\");\n\n \/\/ Merged succeed\n merged_roots.push_back(v);\n }\n\n for (Vertex root: merged_roots) {\n roots.erase(root);\n BOOST_FOREACH (Vertex v, boost::adjacent_vertices(root, dag)) {\n if (boost::in_degree(v, dag) <= 1) {\n roots.insert(v);\n }\n }\n boost::clear_vertex(root, dag);\n }\n }\n return ret;\n}\n\n} \/\/ dag\n\nvector fuser_topological(vector &block_list, const set &news) {\n\n dag::DAG dag = dag::from_block_list(block_list);\n\n return dag::topological(dag);\n}\n\n} \/\/ jitk\n} \/\/ bohrium\njitk: now topological fully fuse\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam .\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace bohrium {\nnamespace jitk {\n\n\/\/ Unnamed namespace for all fuser help functions\nnamespace {\n\n\/\/ Check if 'a' and 'b' supports data-parallelism when merged\nbool data_parallel_compatible(const bh_instruction *a, const bh_instruction *b)\n{\n if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))\n return true;\n\n const int a_nop = bh_noperands(a->opcode);\n for(int i=0; ioperand[0], &a->operand[i])\n && not bh_view_aligned(&b->operand[0], &a->operand[i]))\n return false;\n }\n const int b_nop = bh_noperands(b->opcode);\n for(int i=0; ioperand[0], &b->operand[i])\n && not bh_view_aligned(&a->operand[0], &b->operand[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Check if 'b1' and 'b2' supports data-parallelism when merged\nbool data_parallel_compatible(const Block &b1, const Block &b2) {\n for (const bh_instruction *i1 : b1.getAllInstr()) {\n for (const bh_instruction *i2 : b2.getAllInstr()) {\n if (not data_parallel_compatible(i1, i2))\n return false;\n }\n }\n return true;\n}\n\n\/\/ Check if 'block' accesses the output of a sweep in 'sweeps'\nbool sweeps_accessed_by_block(const set &sweeps, const Block &block) {\n for (bh_instruction *instr: sweeps) {\n assert(bh_noperands(instr->opcode) > 0);\n auto bases = block.getAllBases();\n if (bases.find(instr->operand[0].base) != bases.end())\n return true;\n }\n return false;\n}\n} \/\/ Unnamed namespace\n\n\nvector fuser_singleton(vector &instr_list, const set &news) {\n\n \/\/ Creates the _block_list based on the instr_list\n vector block_list;\n for (auto instr=instr_list.begin(); instr != instr_list.end(); ++instr) {\n int nop = bh_noperands(instr->opcode);\n if (nop == 0)\n continue; \/\/ Ignore noop instructions such as BH_NONE or BH_TALLY\n\n \/\/ Let's try to simplify the shape of the instruction\n if (instr->reshapable()) {\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n\n const int64_t totalsize = std::accumulate(dominating_shape.begin(), dominating_shape.end(), 1, \\\n std::multiplies());\n const vector shape = {totalsize};\n instr->reshape(shape);\n }\n \/\/ Let's create the block\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n int64_t size_of_rank_dim = dominating_shape[0];\n vector single_instr = {&instr[0]};\n block_list.push_back(create_nested_block(single_instr, 0, size_of_rank_dim, news));\n }\n return block_list;\n}\n\n\/\/ Merges the two blocks 'a' and 'a' (in that order)\npair block_merge(const Block &a, const Block &b, const set &news) {\n\n \/\/ First we check for data incompatibility\n if (b.isInstr() or not data_parallel_compatible(a, b) or sweeps_accessed_by_block(a._sweeps, b)) {\n return make_pair(Block(), false);\n }\n \/\/ Check for perfect match, which is directly mergeable\n if (a.size == b.size) {\n return make_pair(merge(a, b), true);\n }\n \/\/ Check fusibility of reshapable blocks\n if (b._reshapable && b.size % a.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, b.rank, a.size, news), true);\n }\n if (a._reshapable && a.size % b.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, a.rank, b.size, news), true);\n }\n return make_pair(Block(), false);\n}\n\nvector fuser_serial(vector &block_list, const set &news) {\n vector ret;\n for (auto it = block_list.begin(); it != block_list.end(); ) {\n ret.push_back(*it);\n Block &cur = ret.back();\n ++it;\n if (cur.isInstr()) {\n continue; \/\/ We should never fuse instruction blocks\n }\n \/\/ Let's search for fusible blocks\n for (; it != block_list.end(); ++it) {\n const pair res = block_merge(cur, *it, news);\n if (res.second) {\n cur = res.first;\n } else {\n break; \/\/ We couldn't find any shape match\n }\n }\n \/\/ Let's fuse at the next rank level\n cur._block_list = fuser_serial(cur._block_list, news);\n }\n return ret;\n}\n\nnamespace dag {\n\n\/\/The type declaration of the boost graphs, vertices and edges.\ntypedef boost::adjacency_list DAG;\ntypedef typename boost::graph_traits::edge_descriptor Edge;\ntypedef uint64_t Vertex;\n\n\/* Determines whether there exist a path from 'a' to 'b'\n *\n * Complexity: O(E + V)\n *\n * @a The first vertex\n * @b The second vertex\n * @dag The DAG\n * @only_long_path Only accept path of length greater than one\n * @return True if there is a path\n *\/\nbool path_exist(Vertex a, Vertex b, const DAG &dag, bool only_long_path) {\n using namespace boost;\n\n struct path_visitor:default_bfs_visitor {\n const Vertex dst;\n path_visitor(Vertex b):dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const {\n if(target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n struct long_visitor:default_bfs_visitor {\n const Vertex src, dst;\n long_visitor(Vertex a, Vertex b):src(a),dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const\n {\n if(source(e,g) != src and target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n try {\n if(only_long_path)\n breadth_first_search(dag, a, visitor(long_visitor(a,b)));\n else\n breadth_first_search(dag, a, visitor(path_visitor(b)));\n }\n catch (const runtime_error &e) {\n return true;\n }\n return false;\n}\n\n\nDAG from_block_list(const vector &block_list) {\n DAG graph;\n map > base2vertices;\n for (const Block &block: block_list) {\n Vertex vertex = boost::add_vertex(&block, graph);\n\n \/\/ Find all vertices that must connect to 'vertex'\n \/\/ using and updating 'base2vertices'\n set connecting_vertices;\n for (bh_base *base: block.getAllBases()) {\n set &vs = base2vertices[base];\n connecting_vertices.insert(vs.begin(), vs.end());\n vs.insert(vertex);\n }\n\n \/\/ Finally, let's add edges to 'vertex'\n BOOST_REVERSE_FOREACH (Vertex v, connecting_vertices) {\n if (vertex != v and block.depend_on(*graph[v])) {\n boost::add_edge(v, vertex, graph);\n }\n }\n }\n return graph;\n}\n\nvoid pprint(const DAG &dag, const string &filename) {\n\n \/\/We define a graph and a kernel writer for graphviz\n struct graph_writer {\n const DAG &graph;\n graph_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out) const {\n out << \"graph [bgcolor=white, fontname=\\\"Courier New\\\"]\" << endl;\n out << \"node [shape=box color=black, fontname=\\\"Courier New\\\"]\" << endl;\n }\n };\n struct kernel_writer {\n const DAG &graph;\n kernel_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Vertex& v) const {\n out << \"[label=\\\"Kernel \" << v;\n\n out << \", Instructions: \\\\l\";\n for (const bh_instruction *instr: graph[v]->getAllInstr()) {\n out << *instr << \"\\\\l\";\n }\n out << \"\\\"]\";\n }\n };\n struct edge_writer {\n const DAG &graph;\n edge_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Edge& e) const {\n\n }\n };\n\n static int count=0;\n stringstream ss;\n ss << filename << \"-\" << count++ << \".dot\";\n ofstream file;\n cout << ss.str() << endl;\n file.open(ss.str());\n boost::write_graphviz(file, dag, kernel_writer(dag), edge_writer(dag), graph_writer(dag));\n file.close();\n}\n\nvector topological(DAG &dag, const set &news) {\n vector ret;\n vector roots; \/\/ Set of root vertices\n \/\/ Initiate 'roots'\n BOOST_FOREACH (Vertex v, boost::vertices(dag)) {\n if (boost::in_degree(v, dag) == 0) {\n roots.push_back(v);\n }\n }\n\n while (not roots.empty()) { \/\/ Each iteration creates a new block\n const Vertex vertex = roots.back();\n roots.erase(roots.end()-1);\n ret.emplace_back(*dag[vertex]);\n Block &block = ret.back();\n\n \/\/ Add adjacent vertices and remove the block from 'dag'\n BOOST_FOREACH (const Vertex v, boost::adjacent_vertices(vertex, dag)) {\n if (boost::in_degree(v, dag) <= 1) {\n roots.push_back(v);\n }\n }\n boost::clear_vertex(vertex, dag);\n\n \/\/ Roots not fusible with 'block'\n vector nonfusible_roots;\n \/\/ Search for fusible blocks within the root blocks\n while (not roots.empty()) {\n const Vertex v = roots.back();\n roots.erase(roots.end()-1);\n const Block &b = *dag[v];\n\n const pair res = block_merge(block, b, news);\n if (res.second) {\n block = res.first;\n\n \/\/ Add adjacent vertices and remove the block 'b' from 'dag'\n BOOST_FOREACH (const Vertex adj, boost::adjacent_vertices(v, dag)) {\n if (boost::in_degree(adj, dag) <= 1) {\n roots.push_back(adj);\n }\n }\n boost::clear_vertex(v, dag);\n } else {\n nonfusible_roots.push_back(v);\n }\n }\n roots = nonfusible_roots;\n }\n return ret;\n}\n\n} \/\/ dag\n\nvector fuser_topological(vector &block_list, const set &news) {\n\n dag::DAG dag = dag::from_block_list(block_list);\n\n return dag::topological(dag, news);\n}\n\n} \/\/ jitk\n} \/\/ bohrium\n<|endoftext|>"} {"text":"\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam .\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace bohrium {\nnamespace jitk {\n\n\/\/ Unnamed namespace for all fuser help functions\nnamespace {\n\n\/\/ Check if 'a' and 'b' supports data-parallelism when merged\nbool data_parallel_compatible(const bh_instruction *a, const bh_instruction *b)\n{\n if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))\n return true;\n\n const int a_nop = bh_noperands(a->opcode);\n for(int i=0; ioperand[0], &a->operand[i])\n && not bh_view_aligned(&b->operand[0], &a->operand[i]))\n return false;\n }\n const int b_nop = bh_noperands(b->opcode);\n for(int i=0; ioperand[0], &b->operand[i])\n && not bh_view_aligned(&a->operand[0], &b->operand[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Check if 'b1' and 'b2' supports data-parallelism when merged\nbool data_parallel_compatible(const Block &b1, const Block &b2) {\n for (const bh_instruction *i1 : b1.getAllInstr()) {\n for (const bh_instruction *i2 : b2.getAllInstr()) {\n if (not data_parallel_compatible(i1, i2))\n return false;\n }\n }\n return true;\n}\n\n\/\/ Check if 'block' accesses the output of a sweep in 'sweeps'\nbool sweeps_accessed_by_block(const set &sweeps, const Block &block) {\n for (bh_instruction *instr: sweeps) {\n assert(bh_noperands(instr->opcode) > 0);\n auto bases = block.getAllBases();\n if (bases.find(instr->operand[0].base) != bases.end())\n return true;\n }\n return false;\n}\n} \/\/ Unnamed namespace\n\n\nvector fuser_singleton(vector &instr_list, const set &news) {\n\n \/\/ Creates the _block_list based on the instr_list\n vector block_list;\n for (auto instr=instr_list.begin(); instr != instr_list.end(); ++instr) {\n int nop = bh_noperands(instr->opcode);\n if (nop == 0)\n continue; \/\/ Ignore noop instructions such as BH_NONE or BH_TALLY\n\n \/\/ Let's try to simplify the shape of the instruction\n if (instr->reshapable()) {\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n\n const int64_t totalsize = std::accumulate(dominating_shape.begin(), dominating_shape.end(), 1, \\\n std::multiplies());\n const vector shape = {totalsize};\n instr->reshape(shape);\n }\n \/\/ Let's create the block\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n int64_t size_of_rank_dim = dominating_shape[0];\n vector single_instr = {&instr[0]};\n block_list.push_back(create_nested_block(single_instr, 0, size_of_rank_dim, news));\n }\n return block_list;\n}\n\n\/\/ Merges the two blocks 'a' and 'a' (in that order)\npair block_merge(const Block &a, const Block &b, const set &news) {\n assert(a.validation());\n assert(b.validation());\n\n \/\/ First we check for data incompatibility\n if (a.isInstr() or b.isInstr() or not data_parallel_compatible(a, b) or sweeps_accessed_by_block(a._sweeps, b)) {\n return make_pair(Block(), false);\n }\n \/\/ Check for perfect match, which is directly mergeable\n if (a.size == b.size) {\n return make_pair(merge(a, b), true);\n }\n\n \/\/ System-only blocks are very flexible because they array sizes does not have to match when reshaping\n \/\/ thus we can simply prepend\/append system instructions without further checks.\n if (b.isSystemOnly()) {\n Block block(a);\n assert(block.validation());\n block.append_instr_list(b.getAllInstr());\n assert(block.validation());\n return make_pair(block, true);\n } else if (a.isSystemOnly()){\n Block block(b);\n assert(block.validation());\n block.prepend_instr_list(a.getAllInstr());\n assert(block.validation());\n return make_pair(block, true);\n }\n\n \/\/ Check fusibility of reshapable blocks\n if (b._reshapable && b.size % a.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, b.rank, a.size, news), true);\n }\n if (a._reshapable && a.size % b.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, a.rank, b.size, news), true);\n }\n return make_pair(Block(), false);\n}\n\nvector fuser_serial(const vector &block_list, const set &news) {\n vector ret;\n for (auto it = block_list.begin(); it != block_list.end(); ) {\n ret.push_back(*it);\n Block &cur = ret.back();\n ++it;\n if (cur.isInstr()) {\n continue; \/\/ We should never fuse instruction blocks\n }\n \/\/ Let's search for fusible blocks\n for (; it != block_list.end(); ++it) {\n const pair res = block_merge(cur, *it, news);\n if (res.second) {\n cur = res.first;\n } else {\n break; \/\/ We couldn't find any shape match\n }\n }\n \/\/ Let's fuse at the next rank level\n cur._block_list = fuser_serial(cur._block_list, news);\n }\n return ret;\n}\n\nnamespace dag {\n\n\/\/The type declaration of the boost graphs, vertices and edges.\ntypedef boost::adjacency_list DAG;\ntypedef typename boost::graph_traits::edge_descriptor Edge;\ntypedef uint64_t Vertex;\n\n\/* Determines whether there exist a path from 'a' to 'b'\n *\n * Complexity: O(E + V)\n *\n * @a The first vertex\n * @b The second vertex\n * @dag The DAG\n * @only_long_path Only accept path of length greater than one\n * @return True if there is a path\n *\/\nbool path_exist(Vertex a, Vertex b, const DAG &dag, bool only_long_path) {\n using namespace boost;\n\n struct path_visitor:default_bfs_visitor {\n const Vertex dst;\n path_visitor(Vertex b):dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const {\n if(target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n struct long_visitor:default_bfs_visitor {\n const Vertex src, dst;\n long_visitor(Vertex a, Vertex b):src(a),dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const\n {\n if(source(e,g) != src and target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n try {\n if(only_long_path)\n breadth_first_search(dag, a, visitor(long_visitor(a,b)));\n else\n breadth_first_search(dag, a, visitor(path_visitor(b)));\n }\n catch (const runtime_error &e) {\n return true;\n }\n return false;\n}\n\n\/\/ Create a DAG based on the 'block_list'\nDAG from_block_list(const vector &block_list) {\n DAG graph;\n map > base2vertices;\n for (const Block &block: block_list) {\n assert(block.validation());\n Vertex vertex = boost::add_vertex(&block, graph);\n\n \/\/ Find all vertices that must connect to 'vertex'\n \/\/ using and updating 'base2vertices'\n set connecting_vertices;\n for (bh_base *base: block.getAllBases()) {\n set &vs = base2vertices[base];\n connecting_vertices.insert(vs.begin(), vs.end());\n vs.insert(vertex);\n }\n\n \/\/ Finally, let's add edges to 'vertex'\n BOOST_REVERSE_FOREACH (Vertex v, connecting_vertices) {\n if (vertex != v and block.depend_on(*graph[v])) {\n boost::add_edge(v, vertex, graph);\n }\n }\n }\n return graph;\n}\n\n\/\/ Pretty print the DAG. A \"-.dot\" is append the filename.\nvoid pprint(const DAG &dag, const string &filename) {\n\n \/\/We define a graph and a kernel writer for graphviz\n struct graph_writer {\n const DAG &graph;\n graph_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out) const {\n out << \"graph [bgcolor=white, fontname=\\\"Courier New\\\"]\" << endl;\n out << \"node [shape=box color=black, fontname=\\\"Courier New\\\"]\" << endl;\n }\n };\n struct kernel_writer {\n const DAG &graph;\n kernel_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Vertex& v) const {\n out << \"[label=\\\"Kernel \" << v;\n\n out << \", Instructions: \\\\l\";\n for (const bh_instruction *instr: graph[v]->getAllInstr()) {\n out << *instr << \"\\\\l\";\n }\n out << \"\\\"]\";\n }\n };\n struct edge_writer {\n const DAG &graph;\n edge_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Edge& e) const {\n\n }\n };\n\n static int count=0;\n stringstream ss;\n ss << filename << \"-\" << count++ << \".dot\";\n ofstream file;\n cout << ss.str() << endl;\n file.open(ss.str());\n boost::write_graphviz(file, dag, kernel_writer(dag), edge_writer(dag), graph_writer(dag));\n file.close();\n}\n\n\/\/ Merges the vertices in 'dag' topologically using 'Queue' as the Vertex qeueue.\n\/\/ 'Queue' is a collection of 'Vertex' that support push(), pop(), and empty().\ntemplate \nvector topological(DAG &dag, const set &news) {\n vector ret;\n Queue roots; \/\/ The root vertices\n\n \/\/ Initiate 'roots'\n BOOST_FOREACH (Vertex v, boost::vertices(dag)) {\n if (boost::in_degree(v, dag) == 0) {\n roots.push(v);\n }\n }\n\n while (not roots.empty()) { \/\/ Each iteration creates a new block\n const Vertex vertex = roots.pop();\n ret.emplace_back(*dag[vertex]);\n Block &block = ret.back();\n\n \/\/ Add adjacent vertices and remove the block from 'dag'\n BOOST_FOREACH (const Vertex v, boost::adjacent_vertices(vertex, dag)) {\n if (boost::in_degree(v, dag) <= 1) {\n roots.push(v);\n }\n }\n boost::clear_vertex(vertex, dag);\n\n \/\/ Instruction blocks should never be merged\n if (block.isInstr()) {\n continue;\n }\n\n \/\/ Roots not fusible with 'block'\n Queue nonfusible_roots;\n \/\/ Search for fusible blocks within the root blocks\n while (not roots.empty()) {\n const Vertex v = roots.pop();\n const Block &b = *dag[v];\n const pair res = block_merge(block, b, news);\n if (res.second) {\n block = res.first;\n assert(block.validation());\n\n \/\/ Add adjacent vertices and remove the block 'b' from 'dag'\n BOOST_FOREACH (const Vertex adj, boost::adjacent_vertices(v, dag)) {\n if (boost::in_degree(adj, dag) <= 1) {\n roots.push(adj);\n }\n }\n boost::clear_vertex(v, dag);\n } else {\n nonfusible_roots.push(v);\n }\n }\n roots = nonfusible_roots;\n }\n return ret;\n}\n\n} \/\/ dag\n\nvector fuser_breadth_first(const vector &block_list, const set &news) {\n\n \/\/ Let's define a FIFO queue, which makes dag::topological() do a breadth first search\n class FifoQueue {\n queue _queue;\n public:\n void push(dag::Vertex v) {\n _queue.push(v);\n }\n dag::Vertex pop() {\n dag::Vertex ret = _queue.front();\n _queue.pop();\n return ret;\n }\n bool empty() {\n return _queue.empty();\n }\n };\n\n dag::DAG dag = dag::from_block_list(block_list);\n vector ret = dag::topological(dag, news);\n\n \/\/ Let's fuse at the next rank level\n for (Block &b: ret) {\n if (not b.isInstr()) {\n b._block_list = fuser_breadth_first(b._block_list, news);\n }\n }\n return ret;\n}\n\n} \/\/ jitk\n} \/\/ bohrium\njitk: the queue template now takes the dag\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam .\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace bohrium {\nnamespace jitk {\n\n\/\/ Unnamed namespace for all fuser help functions\nnamespace {\n\n\/\/ Check if 'a' and 'b' supports data-parallelism when merged\nbool data_parallel_compatible(const bh_instruction *a, const bh_instruction *b)\n{\n if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))\n return true;\n\n const int a_nop = bh_noperands(a->opcode);\n for(int i=0; ioperand[0], &a->operand[i])\n && not bh_view_aligned(&b->operand[0], &a->operand[i]))\n return false;\n }\n const int b_nop = bh_noperands(b->opcode);\n for(int i=0; ioperand[0], &b->operand[i])\n && not bh_view_aligned(&a->operand[0], &b->operand[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Check if 'b1' and 'b2' supports data-parallelism when merged\nbool data_parallel_compatible(const Block &b1, const Block &b2) {\n for (const bh_instruction *i1 : b1.getAllInstr()) {\n for (const bh_instruction *i2 : b2.getAllInstr()) {\n if (not data_parallel_compatible(i1, i2))\n return false;\n }\n }\n return true;\n}\n\n\/\/ Check if 'block' accesses the output of a sweep in 'sweeps'\nbool sweeps_accessed_by_block(const set &sweeps, const Block &block) {\n for (bh_instruction *instr: sweeps) {\n assert(bh_noperands(instr->opcode) > 0);\n auto bases = block.getAllBases();\n if (bases.find(instr->operand[0].base) != bases.end())\n return true;\n }\n return false;\n}\n} \/\/ Unnamed namespace\n\n\nvector fuser_singleton(vector &instr_list, const set &news) {\n\n \/\/ Creates the _block_list based on the instr_list\n vector block_list;\n for (auto instr=instr_list.begin(); instr != instr_list.end(); ++instr) {\n int nop = bh_noperands(instr->opcode);\n if (nop == 0)\n continue; \/\/ Ignore noop instructions such as BH_NONE or BH_TALLY\n\n \/\/ Let's try to simplify the shape of the instruction\n if (instr->reshapable()) {\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n\n const int64_t totalsize = std::accumulate(dominating_shape.begin(), dominating_shape.end(), 1, \\\n std::multiplies());\n const vector shape = {totalsize};\n instr->reshape(shape);\n }\n \/\/ Let's create the block\n const vector dominating_shape = instr->dominating_shape();\n assert(dominating_shape.size() > 0);\n int64_t size_of_rank_dim = dominating_shape[0];\n vector single_instr = {&instr[0]};\n block_list.push_back(create_nested_block(single_instr, 0, size_of_rank_dim, news));\n }\n return block_list;\n}\n\n\/\/ Merges the two blocks 'a' and 'a' (in that order)\npair block_merge(const Block &a, const Block &b, const set &news) {\n assert(a.validation());\n assert(b.validation());\n\n \/\/ First we check for data incompatibility\n if (a.isInstr() or b.isInstr() or not data_parallel_compatible(a, b) or sweeps_accessed_by_block(a._sweeps, b)) {\n return make_pair(Block(), false);\n }\n \/\/ Check for perfect match, which is directly mergeable\n if (a.size == b.size) {\n return make_pair(merge(a, b), true);\n }\n\n \/\/ System-only blocks are very flexible because they array sizes does not have to match when reshaping\n \/\/ thus we can simply prepend\/append system instructions without further checks.\n if (b.isSystemOnly()) {\n Block block(a);\n assert(block.validation());\n block.append_instr_list(b.getAllInstr());\n assert(block.validation());\n return make_pair(block, true);\n } else if (a.isSystemOnly()){\n Block block(b);\n assert(block.validation());\n block.prepend_instr_list(a.getAllInstr());\n assert(block.validation());\n return make_pair(block, true);\n }\n\n \/\/ Check fusibility of reshapable blocks\n if (b._reshapable && b.size % a.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, b.rank, a.size, news), true);\n }\n if (a._reshapable && a.size % b.size == 0) {\n vector cur_instr = a.getAllInstr();\n vector it_instr = b.getAllInstr();\n cur_instr.insert(cur_instr.end(), it_instr.begin(), it_instr.end());\n return make_pair(create_nested_block(cur_instr, a.rank, b.size, news), true);\n }\n return make_pair(Block(), false);\n}\n\nvector fuser_serial(const vector &block_list, const set &news) {\n vector ret;\n for (auto it = block_list.begin(); it != block_list.end(); ) {\n ret.push_back(*it);\n Block &cur = ret.back();\n ++it;\n if (cur.isInstr()) {\n continue; \/\/ We should never fuse instruction blocks\n }\n \/\/ Let's search for fusible blocks\n for (; it != block_list.end(); ++it) {\n const pair res = block_merge(cur, *it, news);\n if (res.second) {\n cur = res.first;\n } else {\n break; \/\/ We couldn't find any shape match\n }\n }\n \/\/ Let's fuse at the next rank level\n cur._block_list = fuser_serial(cur._block_list, news);\n }\n return ret;\n}\n\nnamespace dag {\n\n\/\/The type declaration of the boost graphs, vertices and edges.\ntypedef boost::adjacency_list DAG;\ntypedef typename boost::graph_traits::edge_descriptor Edge;\ntypedef uint64_t Vertex;\n\n\/* Determines whether there exist a path from 'a' to 'b'\n *\n * Complexity: O(E + V)\n *\n * @a The first vertex\n * @b The second vertex\n * @dag The DAG\n * @only_long_path Only accept path of length greater than one\n * @return True if there is a path\n *\/\nbool path_exist(Vertex a, Vertex b, const DAG &dag, bool only_long_path) {\n using namespace boost;\n\n struct path_visitor:default_bfs_visitor {\n const Vertex dst;\n path_visitor(Vertex b):dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const {\n if(target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n struct long_visitor:default_bfs_visitor {\n const Vertex src, dst;\n long_visitor(Vertex a, Vertex b):src(a),dst(b){};\n\n void examine_edge(Edge e, const DAG &g) const\n {\n if(source(e,g) != src and target(e,g) == dst)\n throw runtime_error(\"\");\n }\n };\n try {\n if(only_long_path)\n breadth_first_search(dag, a, visitor(long_visitor(a,b)));\n else\n breadth_first_search(dag, a, visitor(path_visitor(b)));\n }\n catch (const runtime_error &e) {\n return true;\n }\n return false;\n}\n\n\/\/ Create a DAG based on the 'block_list'\nDAG from_block_list(const vector &block_list) {\n DAG graph;\n map > base2vertices;\n for (const Block &block: block_list) {\n assert(block.validation());\n Vertex vertex = boost::add_vertex(&block, graph);\n\n \/\/ Find all vertices that must connect to 'vertex'\n \/\/ using and updating 'base2vertices'\n set connecting_vertices;\n for (bh_base *base: block.getAllBases()) {\n set &vs = base2vertices[base];\n connecting_vertices.insert(vs.begin(), vs.end());\n vs.insert(vertex);\n }\n\n \/\/ Finally, let's add edges to 'vertex'\n BOOST_REVERSE_FOREACH (Vertex v, connecting_vertices) {\n if (vertex != v and block.depend_on(*graph[v])) {\n boost::add_edge(v, vertex, graph);\n }\n }\n }\n return graph;\n}\n\n\/\/ Pretty print the DAG. A \"-.dot\" is append the filename.\nvoid pprint(const DAG &dag, const string &filename) {\n\n \/\/We define a graph and a kernel writer for graphviz\n struct graph_writer {\n const DAG &graph;\n graph_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out) const {\n out << \"graph [bgcolor=white, fontname=\\\"Courier New\\\"]\" << endl;\n out << \"node [shape=box color=black, fontname=\\\"Courier New\\\"]\" << endl;\n }\n };\n struct kernel_writer {\n const DAG &graph;\n kernel_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Vertex& v) const {\n out << \"[label=\\\"Kernel \" << v;\n\n out << \", Instructions: \\\\l\";\n for (const bh_instruction *instr: graph[v]->getAllInstr()) {\n out << *instr << \"\\\\l\";\n }\n out << \"\\\"]\";\n }\n };\n struct edge_writer {\n const DAG &graph;\n edge_writer(const DAG &g) : graph(g) {};\n void operator()(std::ostream& out, const Edge& e) const {\n\n }\n };\n\n static int count=0;\n stringstream ss;\n ss << filename << \"-\" << count++ << \".dot\";\n ofstream file;\n cout << ss.str() << endl;\n file.open(ss.str());\n boost::write_graphviz(file, dag, kernel_writer(dag), edge_writer(dag), graph_writer(dag));\n file.close();\n}\n\n\/\/ Merges the vertices in 'dag' topologically using 'Queue' as the Vertex qeueue.\n\/\/ 'Queue' is a collection of 'Vertex' that is constructoed with the DAG and supports push(), pop(), and empty()\ntemplate \nvector topological(DAG &dag, const set &news) {\n vector ret;\n Queue roots(dag); \/\/ The root vertices\n\n \/\/ Initiate 'roots'\n BOOST_FOREACH (Vertex v, boost::vertices(dag)) {\n if (boost::in_degree(v, dag) == 0) {\n roots.push(v);\n }\n }\n\n while (not roots.empty()) { \/\/ Each iteration creates a new block\n const Vertex vertex = roots.pop();\n ret.emplace_back(*dag[vertex]);\n Block &block = ret.back();\n\n \/\/ Add adjacent vertices and remove the block from 'dag'\n BOOST_FOREACH (const Vertex v, boost::adjacent_vertices(vertex, dag)) {\n if (boost::in_degree(v, dag) <= 1) {\n roots.push(v);\n }\n }\n boost::clear_vertex(vertex, dag);\n\n \/\/ Instruction blocks should never be merged\n if (block.isInstr()) {\n continue;\n }\n\n \/\/ Roots not fusible with 'block'\n Queue nonfusible_roots(dag);\n \/\/ Search for fusible blocks within the root blocks\n while (not roots.empty()) {\n const Vertex v = roots.pop();\n const Block &b = *dag[v];\n const pair res = block_merge(block, b, news);\n if (res.second) {\n block = res.first;\n assert(block.validation());\n\n \/\/ Add adjacent vertices and remove the block 'b' from 'dag'\n BOOST_FOREACH (const Vertex adj, boost::adjacent_vertices(v, dag)) {\n if (boost::in_degree(adj, dag) <= 1) {\n roots.push(adj);\n }\n }\n boost::clear_vertex(v, dag);\n } else {\n nonfusible_roots.push(v);\n }\n }\n roots = nonfusible_roots;\n }\n return ret;\n}\n\n} \/\/ dag\n\nvector fuser_breadth_first(const vector &block_list, const set &news) {\n\n \/\/ Let's define a FIFO queue, which makes dag::topological() do a breadth first search\n class FifoQueue {\n queue _queue;\n public:\n FifoQueue(const dag::DAG &dag) {}\n void push(dag::Vertex v) {\n _queue.push(v);\n }\n dag::Vertex pop() {\n dag::Vertex ret = _queue.front();\n _queue.pop();\n return ret;\n }\n bool empty() {\n return _queue.empty();\n }\n };\n\n dag::DAG dag = dag::from_block_list(block_list);\n vector ret = dag::topological(dag, news);\n\n \/\/ Let's fuse at the next rank level\n for (Block &b: ret) {\n if (not b.isInstr()) {\n b._block_list = fuser_breadth_first(b._block_list, news);\n }\n }\n return ret;\n}\n\n} \/\/ jitk\n} \/\/ bohrium\n<|endoftext|>"} {"text":"#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint H, W, d;\n\nchar c[4] = {'R', 'Y', 'G', 'B'};\n\nint area(int x, int y) {\n int cnt = x\/(d+1) + y\/d;\n return cnt%2;\n}\n\nint which(int x, int y) {\n int nx = x % (d+1);\n int ny = y % d;\n if (nx + ny < d) {\n return 0;\n } else {\n return 1;\n }\n}\n\nint main () {\n cin >> H >> W >> d;\n int ans[510][510];\n for (auto i = 0; i < H; ++i) {\n for (auto j = 0; j < W; ++j) {\n ans[i][j] = area(i, j) * 2 + which(i, j);\n }\n }\n for (auto i = 0; i < H; ++i) {\n for (auto j = 0; j < W; ++j) {\n cout << c[ans[i][j]];\n if (j == W-1) {\n cout << endl;\n }\n }\n }\n}\ntried D.cpp to 'D'#include \n#include \/\/ << fixed << setprecision(xxx)\n#include \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include \n#include \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include \n#include \/\/ get(xxx)\n#include \n#include \n#include \/\/ if (M.find(key) != M.end()) { }\n#include \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include \/\/ random_device rd; mt19937 mt(rd());\n#include \n#include \n#include \n#include \n#include \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint H, W, D, d;\n\nchar c[4] = {'R', 'Y', 'G', 'B'};\n\nint area(int x, int y) {\n int cnt = x\/(d+1) + y\/d;\n return cnt%2;\n}\n\nint which(int x, int y) {\n int nx = x % (d+1);\n int ny = y % d;\n if (nx + ny < d) {\n return 0;\n } else {\n return 1;\n }\n}\n\nint main () {\n cin >> H >> W >> D;\n d = (D+1)\/2;\n int ans[510][510];\n for (auto i = 0; i < H; ++i) {\n for (auto j = 0; j < W; ++j) {\n ans[i][j] = area(i, j) * 2 + which(i, j);\n }\n }\n for (auto i = 0; i < H; ++i) {\n for (auto j = 0; j < W; ++j) {\n cout << c[ans[i][j]];\n if (j == W-1) {\n cout << endl;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Ҹ boost asio http:\/\/neive.tistory.com\/22\n\n#pragma once\n#include\"stdafx.h\"\n\nboostAsioServer::boostAsioServer() : m_acceptor(g_io_service, tcp::endpoint(tcp::v4(), SERVERPORT)), m_socket(g_io_service)\n{\n\tgetMyServerIP();\n\tCheckThisCPUcoreCount();\n\n\tacceptThread();\n\tstart_io_service();\n}\n\nboostAsioServer::~boostAsioServer()\n{\n\t\/\/ make_shared , ʿ䰡 پ ?\n\tfor (auto ptr : g_clients) { delete ptr; }\n}\n\nvoid boostAsioServer::getMyServerIP()\n{\n\ttcp::resolver\t\t\tm_resolver(g_io_service);\n\ttcp::resolver::query\tm_query(boost::asio::ip::host_name(), \"\");\n\ttcp::resolver::iterator m_resolver_iterator = m_resolver.resolve(m_query);\n\n\twhile (m_resolver_iterator != tcp::resolver::iterator()) {\n\t\tusing boost::asio::ip::address;\n\t\taddress addr = (m_resolver_iterator++)->endpoint().address();\n\t\tif (!addr.is_v6()) { cout << \"This Server's IPv4 address: \" << addr.to_string() << endl; }\n\t\t\/\/else if (addr.is_v6()) { cout << \"This Server's IPv6 address: \" << addr.to_string() << endl; }\n\t}\n}\n\nvoid boostAsioServer::CheckThisCPUcoreCount()\n{\n\tSYSTEM_INFO si;\n\tGetSystemInfo(&si);\n\tm_cpuCore = static_cast(si.dwNumberOfProcessors) * 2;\n\tprintf(\"CPU Core Count = %d, threads = %d\\n\", m_cpuCore \/ 2, m_cpuCore);\n}\n\nvoid boostAsioServer::start_io_service()\n{\t\n\tm_worker_threads.reserve(m_cpuCore);\n\n\tfor (int i = 0; i < m_cpuCore; ++i) { m_worker_threads.emplace_back(new thread{ [&]() -> void { g_io_service.run(); } }); }\n\t\n\twhile (m_ServerShutdown) { Sleep(1000); }\n\t\n\t\/\/ workerThread ߵ\n\tfor (auto thread : m_worker_threads) {\n\t\tthread->join();\n\t\tdelete thread;\n\t}\n}\n\nvoid boostAsioServer::acceptThread()\n{\n\tm_acceptor.async_accept(m_socket, [&](boost::system::error_code error_code) {\n\t\tif (true == (!error_code)) {\n\t\t\tcout << \"Client No. [ \" << ++m_playerIndex << \" ] Connected \\t:: IP = \" << m_socket.remote_endpoint().address().to_string() << \", Port = \" << m_socket.remote_endpoint().port() << \"\\n\";\n\t\t\tg_clients.emplace_back(new player_session (std::move(m_socket), m_playerIndex));\n\t\t\tg_clients[m_playerIndex]->Init();\n\t\t}\n\t\tif (false == m_ServerShutdown) { acceptThread(); }\t\t\n\t});\n}\n\n\n\/\/ player_session class ------------------------------------------------------------------------------------------------------------------------\n\nvoid player_session::Init()\n{\n\tm_connect_state = true;\n\n\t\/\/ ⺻ ʱȭ \n\tPacket init_this_player_buf[MAX_BUF_SIZE];\n\n\tinit_this_player_buf[0] = sizeof(player_data) + 2;\n\tinit_this_player_buf[1] = INIT_CLIENT;\n\n\tm_player_data.id = m_id;\n\tm_player_data.pos.x = 400;\n\tm_player_data.pos.y = 300;\n\n\tmemcpy(&init_this_player_buf[2], g_clients[m_id]->get_player_data(), init_this_player_buf[0]);\n\tg_clients[m_id]->send_packet(init_this_player_buf);\n\n\t\/\/ ʱȭ 2 - ٸ ֵ , ٸ ֵ \n\t\/*Packet other_info_to_me_buf[MAX_BUF_SIZE];*\/\n\tPacket my_info_to_other_buf[MAX_BUF_SIZE];\n\n\t\/*other_info_to_me_buf[0] =*\/ my_info_to_other_buf[0] = sizeof(player_data) + 2;\n\t\/*other_info_to_me_buf[1] =*\/ my_info_to_other_buf[1] = KEYINPUT;\n\tmy_info_to_other_buf[1] = INIT_CLIENT;\n\n\t\/\/ ٸ ÷̾ \n\tmemcpy(&my_info_to_other_buf[2], &m_player_data, my_info_to_other_buf[0]);\n\n\tfor (auto players : g_clients)\n\t{\n\t\tif (DISCONNECTED == players->get_current_connect_state()) { continue; }\n\t\tif (m_id == players->get_id()) { continue; }\n\n\t\t\/\/ ٸ ֵ ؼ ְ, ... ( ޴° ˼ ü... )\n\t\t\/*memcpy(&other_info_to_me_buf[2], players->get_player_data(), other_info_to_me_buf[0] - 2);\n\t\tsend_packet(other_info_to_me_buf);*\/\n\n\t\t\/\/ ٸ ֵ Ǵµ..\n\t\tplayers->send_packet(my_info_to_other_buf);\n\t}\n\t\n\t\/*\n\t\tó ÷̾, ÷̾ ˸\n\t\tview list ߰ ~ !!\n\t*\/\n\n\tm_recv_packet();\n}\n\nvoid player_session::m_recv_packet()\n{\n\t\/\/auto self(shared_from_this());\n\tm_socket.async_read_some(boost::asio::buffer(m_recv_buf, MAX_BUF_SIZE), [&](boost::system::error_code error_code, std::size_t length) -> void {\n\t\tif (error_code) {\n\t\t\tif (error_code.value() == boost::asio::error::operation_aborted) { return; }\n\t\t\t\/\/ client was disconnected\n\t\t\tif (false == g_clients[m_id]->get_current_connect_state()) { return; }\n\n\t\t\tcout << \"Client No. [ \" << m_id << \" ] Disonnected \\t:: IP = \" << m_socket.remote_endpoint().address().to_string() << \", Port = \" << m_socket.remote_endpoint().port() << \"\\n\";\n\t\t\tm_socket.shutdown(m_socket.shutdown_both);\n\t\t\tm_socket.close();\n\n\t\t\tm_connect_state = false;\n\n\t\t\t\/*\n\t\t\t\tó ÷̾, ÷̾ ˸\n\t\t\t\tview list ~ !!\n\t\t\t*\/\n\n\t\t\tPacket temp_buf[MAX_BUF_SIZE] = { sizeof(player_data) + 2, PLAYER_DISCONNECTED };\n\t\t\tmemcpy(&temp_buf[2], &m_player_data, temp_buf[0]);\n\n\t\t\tfor (auto players : g_clients)\n\t\t\t{\n\t\t\t\tif (DISCONNECTED == players->m_connect_state) { continue; }\n\t\t\t\tif (m_id == players->m_id) { continue; }\n\n\t\t\t\tplayers->send_packet(temp_buf);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tint current_data_processing = static_cast(length);\n\t\tPacket *buf = m_recv_buf;\n\t\twhile (0 < current_data_processing) {\n\t\t\tif (0 == m_packet_size_current) {\n\t\t\t\tm_packet_size_current = buf[0];\n\t\t\t\tif (buf[0] > MAX_BUF_SIZE) {\n\t\t\t\t\tcout << \"player_session::m_recv_packet() Error, Client No. [ \" << m_id << \" ] recv buf[0] is out of MAX_BUF_SIZE\\n\";\n\t\t\t\t\texit(-1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tint need_to_build = m_packet_size_current - m_packet_size_previous;\n\t\t\tif (need_to_build <= current_data_processing) {\n\t\t\t\t\/\/ Packet building Complete & Process Packet\n\t\t\t\tmemcpy(m_data_buf + m_packet_size_previous, buf, need_to_build);\n\n\t\t\t\tm_process_packet(m_id, m_data_buf);\n\n\t\t\t\tm_packet_size_current = 0;\n\t\t\t\tm_packet_size_previous = 0;\n\t\t\t\tcurrent_data_processing -= need_to_build;\n\t\t\t\tbuf += need_to_build;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ Packet build continue\n\t\t\t\tmemcpy(m_data_buf + m_packet_size_previous, buf, current_data_processing);\n\t\t\t\tm_packet_size_previous += current_data_processing;\n\t\t\t\tcurrent_data_processing = 0;\n\t\t\t\tbuf += current_data_processing;\n\t\t\t}\n\t\t}\n\t\tm_recv_packet();\n\t});\n}\n\nvoid player_session::send_packet(Packet *packet)\n{\n\tint packet_size = packet[0];\n\tPacket *sendBuf = new Packet[packet_size];\n\tmemcpy(sendBuf, packet, packet_size);\n\n\t\/\/auto self(shared_from_this());\n\tm_socket.async_write_some(boost::asio::buffer(sendBuf, packet_size), [=](boost::system::error_code error_code, std::size_t bytes_transferred) -> void {\n\t\tif (!error_code) {\n\t\t\tif (packet_size != bytes_transferred) { cout << \"Client No. [ \" << m_id << \" ] async_write_some packet bytes was NOT SAME !!\\n\"; }\n\t\t\tdelete[] sendBuf;\n\t\t}\n\t});\n}\n\nvoid player_session::m_process_packet(const unsigned int& id, Packet buf[])\n{\n\t\/\/ packet[0] = packet size\t\t> 0° ڸ , Ŷ ũⰡ ߸ Ѵ.\n\t\/\/ packet[1] = type\t\t\t\t> 1° ڸ Ŷ Ŷ Ӽ ִ ̴.\n\t\/\/ packet[...] = data\t\t\t> 2° ʹ Ӽ ´ ó ش.\n\n\t\/\/ buf[1] ° Ӽ з ڿ, ο 2° ͸ óϱ Ѵ.\n\n\t{\n\t\tswitch (buf[1])\n\t\t{\n\t\tcase TEST:\n\t\t\t\/\/ Ŷ ״ ش.\n\t\t\tcout << \"Client No. [ \" << m_id << \" ] TEST Packet Recived !!\\n\";\n\t\t\tprintf(\"buf[0] = %d, buf[1] = %d, buf[2] = %d\\n\\n\", buf[0], buf[1], buf[2]);\n\t\t\tg_clients[id]->send_packet(buf);\n\t\t\tbreak;\n\n\t\tcase KEYINPUT:\n\t\t\tg_clients[id]->m_player_data.pos = reinterpret_cast(&buf[2])->pos;\n\n\t\t\t\/\/ ʿ ֵ ̵ ѷ\n\t\t\tfor (auto players : g_clients)\n\t\t\t{\n\t\t\t\tif (DISCONNECTED == players->m_connect_state) { continue; }\n\t\t\t\tif (id == players->m_id) { continue; }\n\n\t\t\t\tplayers->send_packet(buf);\n\t\t\t}\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}[김형준] 100 100\/\/ Ҹ boost asio http:\/\/neive.tistory.com\/22\n\n#pragma once\n#include\"stdafx.h\"\n\nboostAsioServer::boostAsioServer() : m_acceptor(g_io_service, tcp::endpoint(tcp::v4(), SERVERPORT)), m_socket(g_io_service)\n{\n\tgetMyServerIP();\n\tCheckThisCPUcoreCount();\n\n\tacceptThread();\n\tstart_io_service();\n}\n\nboostAsioServer::~boostAsioServer()\n{\n\t\/\/ make_shared , ʿ䰡 پ ?\n\tfor (auto ptr : g_clients) { delete ptr; }\n}\n\nvoid boostAsioServer::getMyServerIP()\n{\n\ttcp::resolver\t\t\tm_resolver(g_io_service);\n\ttcp::resolver::query\tm_query(boost::asio::ip::host_name(), \"\");\n\ttcp::resolver::iterator m_resolver_iterator = m_resolver.resolve(m_query);\n\n\twhile (m_resolver_iterator != tcp::resolver::iterator()) {\n\t\tusing boost::asio::ip::address;\n\t\taddress addr = (m_resolver_iterator++)->endpoint().address();\n\t\tif (!addr.is_v6()) { cout << \"This Server's IPv4 address: \" << addr.to_string() << endl; }\n\t\t\/\/else if (addr.is_v6()) { cout << \"This Server's IPv6 address: \" << addr.to_string() << endl; }\n\t}\n}\n\nvoid boostAsioServer::CheckThisCPUcoreCount()\n{\n\tSYSTEM_INFO si;\n\tGetSystemInfo(&si);\n\tm_cpuCore = static_cast(si.dwNumberOfProcessors) * 2;\n\tprintf(\"CPU Core Count = %d, threads = %d\\n\", m_cpuCore \/ 2, m_cpuCore);\n}\n\nvoid boostAsioServer::start_io_service()\n{\t\n\tm_worker_threads.reserve(m_cpuCore);\n\n\tfor (int i = 0; i < m_cpuCore; ++i) { m_worker_threads.emplace_back(new thread{ [&]() -> void { g_io_service.run(); } }); }\n\t\n\twhile (m_ServerShutdown) { Sleep(1000); }\n\t\n\t\/\/ workerThread ߵ\n\tfor (auto thread : m_worker_threads) {\n\t\tthread->join();\n\t\tdelete thread;\n\t}\n}\n\nvoid boostAsioServer::acceptThread()\n{\n\tm_acceptor.async_accept(m_socket, [&](boost::system::error_code error_code) {\n\t\tif (true == (!error_code)) {\n\t\t\tcout << \"Client No. [ \" << ++m_playerIndex << \" ] Connected \\t:: IP = \" << m_socket.remote_endpoint().address().to_string() << \", Port = \" << m_socket.remote_endpoint().port() << \"\\n\";\n\t\t\tg_clients.emplace_back(new player_session (std::move(m_socket), m_playerIndex));\n\t\t\tg_clients[m_playerIndex]->Init();\n\t\t}\n\t\tif (false == m_ServerShutdown) { acceptThread(); }\t\t\n\t});\n}\n\n\n\/\/ player_session class ------------------------------------------------------------------------------------------------------------------------\n\nvoid player_session::Init()\n{\n\tm_connect_state = true;\n\n\t\/\/ ⺻ ʱȭ \n\tPacket init_this_player_buf[MAX_BUF_SIZE];\n\n\tinit_this_player_buf[0] = sizeof(player_data) + 2;\n\tinit_this_player_buf[1] = INIT_CLIENT;\n\n\tm_player_data.id = m_id;\n\tm_player_data.pos.x = 100;\n\tm_player_data.pos.y = 100;\n\n\tmemcpy(&init_this_player_buf[2], g_clients[m_id]->get_player_data(), init_this_player_buf[0]);\n\tg_clients[m_id]->send_packet(init_this_player_buf);\n\n\t\/\/ ʱȭ 2 - ٸ ֵ , ٸ ֵ \n\t\/*Packet other_info_to_me_buf[MAX_BUF_SIZE];*\/\n\tPacket my_info_to_other_buf[MAX_BUF_SIZE];\n\n\t\/*other_info_to_me_buf[0] =*\/ my_info_to_other_buf[0] = sizeof(player_data) + 2;\n\t\/*other_info_to_me_buf[1] =*\/ my_info_to_other_buf[1] = KEYINPUT;\n\tmy_info_to_other_buf[1] = INIT_CLIENT;\n\n\t\/\/ ٸ ÷̾ \n\tmemcpy(&my_info_to_other_buf[2], &m_player_data, my_info_to_other_buf[0]);\n\n\tfor (auto players : g_clients)\n\t{\n\t\tif (DISCONNECTED == players->get_current_connect_state()) { continue; }\n\t\tif (m_id == players->get_id()) { continue; }\n\n\t\t\/\/ ٸ ֵ ؼ ְ, ... ( ޴° ˼ ü... )\n\t\t\/*memcpy(&other_info_to_me_buf[2], players->get_player_data(), other_info_to_me_buf[0] - 2);\n\t\tsend_packet(other_info_to_me_buf);*\/\n\n\t\t\/\/ ٸ ֵ Ǵµ..\n\t\tplayers->send_packet(my_info_to_other_buf);\n\t}\n\t\n\t\/*\n\t\tó ÷̾, ÷̾ ˸\n\t\tview list ߰ ~ !!\n\t*\/\n\n\tm_recv_packet();\n}\n\nvoid player_session::m_recv_packet()\n{\n\t\/\/auto self(shared_from_this());\n\tm_socket.async_read_some(boost::asio::buffer(m_recv_buf, MAX_BUF_SIZE), [&](boost::system::error_code error_code, std::size_t length) -> void {\n\t\tif (error_code) {\n\t\t\tif (error_code.value() == boost::asio::error::operation_aborted) { return; }\n\t\t\t\/\/ client was disconnected\n\t\t\tif (false == g_clients[m_id]->get_current_connect_state()) { return; }\n\n\t\t\tcout << \"Client No. [ \" << m_id << \" ] Disonnected \\t:: IP = \" << m_socket.remote_endpoint().address().to_string() << \", Port = \" << m_socket.remote_endpoint().port() << \"\\n\";\n\t\t\tm_socket.shutdown(m_socket.shutdown_both);\n\t\t\tm_socket.close();\n\n\t\t\tm_connect_state = false;\n\n\t\t\t\/*\n\t\t\t\tó ÷̾, ÷̾ ˸\n\t\t\t\tview list ~ !!\n\t\t\t*\/\n\n\t\t\tPacket temp_buf[MAX_BUF_SIZE] = { sizeof(player_data) + 2, PLAYER_DISCONNECTED };\n\t\t\tmemcpy(&temp_buf[2], &m_player_data, temp_buf[0]);\n\n\t\t\tfor (auto players : g_clients)\n\t\t\t{\n\t\t\t\tif (DISCONNECTED == players->m_connect_state) { continue; }\n\t\t\t\tif (m_id == players->m_id) { continue; }\n\n\t\t\t\tplayers->send_packet(temp_buf);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tint current_data_processing = static_cast(length);\n\t\tPacket *buf = m_recv_buf;\n\t\twhile (0 < current_data_processing) {\n\t\t\tif (0 == m_packet_size_current) {\n\t\t\t\tm_packet_size_current = buf[0];\n\t\t\t\tif (buf[0] > MAX_BUF_SIZE) {\n\t\t\t\t\tcout << \"player_session::m_recv_packet() Error, Client No. [ \" << m_id << \" ] recv buf[0] is out of MAX_BUF_SIZE\\n\";\n\t\t\t\t\texit(-1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tint need_to_build = m_packet_size_current - m_packet_size_previous;\n\t\t\tif (need_to_build <= current_data_processing) {\n\t\t\t\t\/\/ Packet building Complete & Process Packet\n\t\t\t\tmemcpy(m_data_buf + m_packet_size_previous, buf, need_to_build);\n\n\t\t\t\tm_process_packet(m_id, m_data_buf);\n\n\t\t\t\tm_packet_size_current = 0;\n\t\t\t\tm_packet_size_previous = 0;\n\t\t\t\tcurrent_data_processing -= need_to_build;\n\t\t\t\tbuf += need_to_build;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ Packet build continue\n\t\t\t\tmemcpy(m_data_buf + m_packet_size_previous, buf, current_data_processing);\n\t\t\t\tm_packet_size_previous += current_data_processing;\n\t\t\t\tcurrent_data_processing = 0;\n\t\t\t\tbuf += current_data_processing;\n\t\t\t}\n\t\t}\n\t\tm_recv_packet();\n\t});\n}\n\nvoid player_session::send_packet(Packet *packet)\n{\n\tint packet_size = packet[0];\n\tPacket *sendBuf = new Packet[packet_size];\n\tmemcpy(sendBuf, packet, packet_size);\n\n\t\/\/auto self(shared_from_this());\n\tm_socket.async_write_some(boost::asio::buffer(sendBuf, packet_size), [=](boost::system::error_code error_code, std::size_t bytes_transferred) -> void {\n\t\tif (!error_code) {\n\t\t\tif (packet_size != bytes_transferred) { cout << \"Client No. [ \" << m_id << \" ] async_write_some packet bytes was NOT SAME !!\\n\"; }\n\t\t\tdelete[] sendBuf;\n\t\t}\n\t});\n}\n\nvoid player_session::m_process_packet(const unsigned int& id, Packet buf[])\n{\n\t\/\/ packet[0] = packet size\t\t> 0° ڸ , Ŷ ũⰡ ߸ Ѵ.\n\t\/\/ packet[1] = type\t\t\t\t> 1° ڸ Ŷ Ŷ Ӽ ִ ̴.\n\t\/\/ packet[...] = data\t\t\t> 2° ʹ Ӽ ´ ó ش.\n\n\t\/\/ buf[1] ° Ӽ з ڿ, ο 2° ͸ óϱ Ѵ.\n\n\t{\n\t\tswitch (buf[1])\n\t\t{\n\t\tcase TEST:\n\t\t\t\/\/ Ŷ ״ ش.\n\t\t\tcout << \"Client No. [ \" << m_id << \" ] TEST Packet Recived !!\\n\";\n\t\t\tprintf(\"buf[0] = %d, buf[1] = %d, buf[2] = %d\\n\\n\", buf[0], buf[1], buf[2]);\n\t\t\tg_clients[id]->send_packet(buf);\n\t\t\tbreak;\n\n\t\tcase KEYINPUT:\n\t\t\tg_clients[id]->m_player_data.pos = reinterpret_cast(&buf[2])->pos;\n\n\t\t\t\/\/ ʿ ֵ ̵ ѷ\n\t\t\tfor (auto players : g_clients)\n\t\t\t{\n\t\t\t\tif (DISCONNECTED == players->m_connect_state) { continue; }\n\t\t\t\tif (id == players->m_id) { continue; }\n\n\t\t\t\tplayers->send_packet(buf);\n\t\t\t}\n\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"\/*\n *\n * Copyright (C) 2000 Frans Kaashoek (kaashoek@lcs.mit.edu)\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\n * USA\n *\n *\/\n\n#include \"chord.h\"\n#include \"dhash.h\"\n#include \"parseopt.h\"\n\nEXITFN (cleanup);\n\n#define MAX_VNODES 1024\n\nptr chordnode;\nstatic str p2psocket;\nint do_cache;\nstr db_name;\ndhash *dh[MAX_VNODES + 1];\nint ndhash = 0;\nint nreplica;\n\nvoid stats ();\nvoid print ();\n\nvoid\nclient_accept (int fd)\n{\n if (fd < 0)\n fatal (\"EOF\\n\");\n ref x = axprt_stream::alloc (fd);\n dhashclient *c = New dhashclient (x, nreplica, chordnode);\n if (do_cache) c->set_caching (1);\n else c->set_caching (0);\n}\n\nstatic void\nclient_accept_socket (int lfd)\n{\n sockaddr_un sun;\n bzero (&sun, sizeof (sun));\n socklen_t sunlen = sizeof (sun);\n int fd = accept (lfd, reinterpret_cast (&sun), &sunlen);\n if (fd >= 0)\n client_accept (fd);\n}\n\nstatic void\nclient_listening_cb (int fd, int status)\n{\n if (status)\n close (fd);\n else if (listen (fd, 5) < 0) {\n warn (\"not listening for sfskey: listen: %m\\n\");\n close (fd);\n }\n else {\n fdcb (fd, selread, wrap (client_accept_socket, fd));\n }\n}\n\nstatic void\ncleanup ()\n{\n unlink (p2psocket);\n}\n\nstatic void\nstartclntd()\n{\n sockaddr_un sun;\n if (p2psocket.len () >= sizeof (sun.sun_path)) {\n warn (\"not listening on socket: path too long: %s\\n\", p2psocket.cstr ());\n return;\n }\n int clntfd = socket (AF_UNIX, SOCK_STREAM, 0);\n if (clntfd < 0) {\n warn (\"not listening on socket: socket: %m\\n\");\n return;\n }\n make_async (clntfd);\n\n bzero (&sun, sizeof (sun));\n sun.sun_family = AF_UNIX;\n strcpy (sun.sun_path, p2psocket);\n\n#if 0\n pid_t pid = afork ();\n if (pid == -1) {\n warn (\"not listening on socket: fork: %m\\n\");\n return;\n }\n else if (!pid) {\n#endif\n umask (077);\n if (bind (clntfd, (sockaddr *) &sun, sizeof (sun)) < 0) {\n if (errno == EADDRINUSE)\n\tunlink (sun.sun_path);\n if (bind (clntfd, (sockaddr *) &sun, sizeof (sun)) < 0) {\n\twarn (\"not listening on socket: %s: %m\\n\", sun.sun_path);\n\terr_flush ();\n\t_exit (1);\n }\n }\n#if 0\n err_flush ();\n _exit (0);\n }\n chldcb (pid, wrap (start_listening_cb, clntfd));\n#endif\n client_listening_cb (clntfd, 0);\n}\n\nstatic void\nnewvnode_cb (int nreplica, int n, vnode *my)\n{\n str db_name_prime = strbuf () << db_name << \"-\" << n;\n if (ndhash == MAX_VNODES) fatal << \"Too many virtual nodes (1024)\\n\";\n dh[ndhash++] = New dhash (db_name_prime, my, nreplica);\n if (n > 0) chordnode->newvnode (wrap (newvnode_cb, nreplica, n-1));\n}\n\nstatic void\ninitID (str s, chordID *ID)\n{\n chordID n (s);\n chordID b (1);\n b = b << NBIT;\n b = b - 1;\n *ID = n & b;\n}\n\nstatic void\nparseconfigfile (str cf, int nvnode, int set_rpcdelay)\n{ \n parseargs pa (cf);\n bool errors = false;\n int line;\n vec av;\n int myport;\n str myhost;\n str wellknownhost;\n int wellknownport;\n bool myid = false;\n chordID myID;\n chordID wellknownID;\n int ss = 10000;\n int cs = 1000;\n myport = 0;\n int max_connections = 400;\n int max_loccache = 250;\n\n while (pa.getline (&av, &line)) {\n if (!strcasecmp (av[0], \"#\")) {\n } else if (!strcasecmp (av[0], \"myport\")) {\n if (av.size () != 2 || !convertint (av[1], &myport)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: myport \\n\";\n }\n } else if (!strcasecmp (av[0], \"myname\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: myname \\n\";\n }\n myhost = av[1];\n } else if (!strcasecmp (av[0], \"wellknownport\")) {\n if (av.size () != 2 || !convertint (av[1], &wellknownport)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownport \\n\";\n }\n } else if (!strcasecmp (av[0], \"myID\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: myID \\n\";\n } else {\n\tinitID (av[1], &myID);\n\tmyid = true;\n }\n } else if (!strcasecmp (av[0], \"wellknownID\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownID \\n\";\n } else {\n\tinitID (av[1], &wellknownID);\n }\n } else if (!strcasecmp (av[0], \"wellknownport\")) {\n if (av.size () != 2 || !convertint (av[1], &wellknownport)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownport \\n\";\n }\n } else if (!strcasecmp (av[0], \"nreplica\")) {\n if (av.size () != 2 || !convertint (av[1], &nreplica)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: nreplica \\n\";\n }\n } else if (!strcasecmp (av[0], \"wellknownhost\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownhost \\n\";\n }\n else\n wellknownhost = av[1];\n } else if (!strcasecmp (av[0], \"storesize\")) {\n if (av.size () != 2 || !convertint (av[1], &ss)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: storesize \\n\";\n }\n } else if (!strcasecmp (av[0], \"cachesize\")) {\n if (av.size () != 2 || !convertint (av[1], &cs)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: cachesize \\n\";\n }\n } else if (!strcasecmp (av[0], \"maxopenconnections\")) {\n if (av.size () != 2 || !convertint (av[1], &max_connections)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: maxopenconnections \\n\";\n }\n } else if (!strcasecmp (av[0], \"maxlocationcache\")) {\n if (av.size () != 2 || !convertint (av[1], &max_loccache)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: maxlocationcache \\n\";\n }\n }\n }\n if (errors) {\n fatal (\"errors in config file\\n\");\n }\n if (!myhost) {\n myhost = myname ();\n }\n chordnode = New refcounted (wellknownhost, wellknownport, \n\t\t\t\t wellknownID, myport, myhost, set_rpcdelay,\n\t\t\t\t max_loccache, max_connections);\n if (myid) chordnode->newvnode (myID, wrap (newvnode_cb, nreplica, nvnode-1));\n else chordnode->newvnode (wrap (newvnode_cb, nreplica, nvnode-1));\n sigcb(SIGUSR1, wrap (&stats));\n sigcb(SIGUSR2, wrap (&print));\n}\n\nvoid\nstats () \n{\n chordnode->stats ();\n for (int i = 0 ; i < ndhash; i++)\n dh[i]->print_stats ();\n}\n\nvoid\nprint ()\n{\n chordnode->print ();\n}\nstatic void\nusage ()\n{\n warnx << \"Usage: \" << progname \n\t<< \"-d -S -v -c -f \\n\"; \n exit (1);\n}\n\nint\nmain (int argc, char **argv)\n{\n int vnode = 1;\n setprogname (argv[0]);\n sfsconst_init ();\n random_init ();\n int ch;\n do_cache = 0;\n int set_name = 0;\n int set_rpcdelay = 0;\n\n while ((ch = getopt (argc, argv, \"d:S:v:f:c\")) != -1)\n switch (ch) {\n case 'S':\n p2psocket = optarg;\n break;\n case 'v':\n vnode = atoi (optarg);\n break;\n case 'r':\n set_rpcdelay = atoi(optarg);\n break;\n case 'f':\n if (!set_name) fatal(\"must specify db name\\n\");\n parseconfigfile (optarg, vnode, set_rpcdelay);\n break;\n case 'c':\n do_cache = 1;\n break;\n case 'd':\n db_name = optarg;\n set_name = 1;\n break;\n default:\n usage ();\n break;\n }\n\n if (!chordnode) \n fatal (\"Specify config file\\n\");\n if (p2psocket) \n startclntd();\n amain ();\n}\n\n\n\nstupid--scale location table with number of virtual nodes\/*\n *\n * Copyright (C) 2000 Frans Kaashoek (kaashoek@lcs.mit.edu)\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\n * USA\n *\n *\/\n\n#include \"chord.h\"\n#include \"dhash.h\"\n#include \"parseopt.h\"\n\nEXITFN (cleanup);\n\n#define MAX_VNODES 1024\n\nptr chordnode;\nstatic str p2psocket;\nint do_cache;\nstr db_name;\ndhash *dh[MAX_VNODES + 1];\nint ndhash = 0;\nint nreplica;\n\nvoid stats ();\nvoid print ();\n\nvoid\nclient_accept (int fd)\n{\n if (fd < 0)\n fatal (\"EOF\\n\");\n ref x = axprt_stream::alloc (fd);\n dhashclient *c = New dhashclient (x, nreplica, chordnode);\n if (do_cache) c->set_caching (1);\n else c->set_caching (0);\n}\n\nstatic void\nclient_accept_socket (int lfd)\n{\n sockaddr_un sun;\n bzero (&sun, sizeof (sun));\n socklen_t sunlen = sizeof (sun);\n int fd = accept (lfd, reinterpret_cast (&sun), &sunlen);\n if (fd >= 0)\n client_accept (fd);\n}\n\nstatic void\nclient_listening_cb (int fd, int status)\n{\n if (status)\n close (fd);\n else if (listen (fd, 5) < 0) {\n warn (\"not listening for sfskey: listen: %m\\n\");\n close (fd);\n }\n else {\n fdcb (fd, selread, wrap (client_accept_socket, fd));\n }\n}\n\nstatic void\ncleanup ()\n{\n unlink (p2psocket);\n}\n\nstatic void\nstartclntd()\n{\n sockaddr_un sun;\n if (p2psocket.len () >= sizeof (sun.sun_path)) {\n warn (\"not listening on socket: path too long: %s\\n\", p2psocket.cstr ());\n return;\n }\n int clntfd = socket (AF_UNIX, SOCK_STREAM, 0);\n if (clntfd < 0) {\n warn (\"not listening on socket: socket: %m\\n\");\n return;\n }\n make_async (clntfd);\n\n bzero (&sun, sizeof (sun));\n sun.sun_family = AF_UNIX;\n strcpy (sun.sun_path, p2psocket);\n\n#if 0\n pid_t pid = afork ();\n if (pid == -1) {\n warn (\"not listening on socket: fork: %m\\n\");\n return;\n }\n else if (!pid) {\n#endif\n umask (077);\n if (bind (clntfd, (sockaddr *) &sun, sizeof (sun)) < 0) {\n if (errno == EADDRINUSE)\n\tunlink (sun.sun_path);\n if (bind (clntfd, (sockaddr *) &sun, sizeof (sun)) < 0) {\n\twarn (\"not listening on socket: %s: %m\\n\", sun.sun_path);\n\terr_flush ();\n\t_exit (1);\n }\n }\n#if 0\n err_flush ();\n _exit (0);\n }\n chldcb (pid, wrap (start_listening_cb, clntfd));\n#endif\n client_listening_cb (clntfd, 0);\n}\n\nstatic void\nnewvnode_cb (int nreplica, int n, vnode *my)\n{\n str db_name_prime = strbuf () << db_name << \"-\" << n;\n if (ndhash == MAX_VNODES) fatal << \"Too many virtual nodes (1024)\\n\";\n dh[ndhash++] = New dhash (db_name_prime, my, nreplica);\n if (n > 0) chordnode->newvnode (wrap (newvnode_cb, nreplica, n-1));\n}\n\nstatic void\ninitID (str s, chordID *ID)\n{\n chordID n (s);\n chordID b (1);\n b = b << NBIT;\n b = b - 1;\n *ID = n & b;\n}\n\nstatic void\nparseconfigfile (str cf, int nvnode, int set_rpcdelay)\n{ \n parseargs pa (cf);\n bool errors = false;\n int line;\n vec av;\n int myport;\n str myhost;\n str wellknownhost;\n int wellknownport;\n bool myid = false;\n chordID myID;\n chordID wellknownID;\n int ss = 10000;\n int cs = 1000;\n myport = 0;\n int max_connections = 400;\n int max_loccache = 100;\n\n while (pa.getline (&av, &line)) {\n if (!strcasecmp (av[0], \"#\")) {\n } else if (!strcasecmp (av[0], \"myport\")) {\n if (av.size () != 2 || !convertint (av[1], &myport)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: myport \\n\";\n }\n } else if (!strcasecmp (av[0], \"myname\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: myname \\n\";\n }\n myhost = av[1];\n } else if (!strcasecmp (av[0], \"wellknownport\")) {\n if (av.size () != 2 || !convertint (av[1], &wellknownport)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownport \\n\";\n }\n } else if (!strcasecmp (av[0], \"myID\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: myID \\n\";\n } else {\n\tinitID (av[1], &myID);\n\tmyid = true;\n }\n } else if (!strcasecmp (av[0], \"wellknownID\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownID \\n\";\n } else {\n\tinitID (av[1], &wellknownID);\n }\n } else if (!strcasecmp (av[0], \"wellknownport\")) {\n if (av.size () != 2 || !convertint (av[1], &wellknownport)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownport \\n\";\n }\n } else if (!strcasecmp (av[0], \"nreplica\")) {\n if (av.size () != 2 || !convertint (av[1], &nreplica)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: nreplica \\n\";\n }\n } else if (!strcasecmp (av[0], \"wellknownhost\")) {\n if (av.size () != 2) {\n errors = true;\n warn << cf << \":\" << line << \": usage: wellknownhost \\n\";\n }\n else\n wellknownhost = av[1];\n } else if (!strcasecmp (av[0], \"storesize\")) {\n if (av.size () != 2 || !convertint (av[1], &ss)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: storesize \\n\";\n }\n } else if (!strcasecmp (av[0], \"cachesize\")) {\n if (av.size () != 2 || !convertint (av[1], &cs)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: cachesize \\n\";\n }\n } else if (!strcasecmp (av[0], \"maxopenconnections\")) {\n if (av.size () != 2 || !convertint (av[1], &max_connections)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: maxopenconnections \\n\";\n }\n } else if (!strcasecmp (av[0], \"maxlocationcache\")) {\n if (av.size () != 2 || !convertint (av[1], &max_loccache)) {\n errors = true;\n warn << cf << \":\" << line << \": usage: maxlocationcache \\n\";\n }\n }\n }\n if (errors) {\n fatal (\"errors in config file\\n\");\n }\n if (!myhost) {\n myhost = myname ();\n }\n max_loccache = max_loccache * nvnode;\n chordnode = New refcounted (wellknownhost, wellknownport, \n\t\t\t\t wellknownID, myport, myhost, set_rpcdelay,\n\t\t\t\t max_loccache, max_connections);\n if (myid) chordnode->newvnode (myID, wrap (newvnode_cb, nreplica, nvnode-1));\n else chordnode->newvnode (wrap (newvnode_cb, nreplica, nvnode-1));\n sigcb(SIGUSR1, wrap (&stats));\n sigcb(SIGUSR2, wrap (&print));\n}\n\nvoid\nstats () \n{\n chordnode->stats ();\n for (int i = 0 ; i < ndhash; i++)\n dh[i]->print_stats ();\n}\n\nvoid\nprint ()\n{\n chordnode->print ();\n}\nstatic void\nusage ()\n{\n warnx << \"Usage: \" << progname \n\t<< \"-d -S -v -c -f \\n\"; \n exit (1);\n}\n\nint\nmain (int argc, char **argv)\n{\n int vnode = 1;\n setprogname (argv[0]);\n sfsconst_init ();\n random_init ();\n int ch;\n do_cache = 0;\n int set_name = 0;\n int set_rpcdelay = 0;\n\n while ((ch = getopt (argc, argv, \"d:S:v:f:c\")) != -1)\n switch (ch) {\n case 'S':\n p2psocket = optarg;\n break;\n case 'v':\n vnode = atoi (optarg);\n break;\n case 'r':\n set_rpcdelay = atoi(optarg);\n break;\n case 'f':\n if (!set_name) fatal(\"must specify db name\\n\");\n parseconfigfile (optarg, vnode, set_rpcdelay);\n break;\n case 'c':\n do_cache = 1;\n break;\n case 'd':\n db_name = optarg;\n set_name = 1;\n break;\n default:\n usage ();\n break;\n }\n\n if (!chordnode) \n fatal (\"Specify config file\\n\");\n if (p2psocket) \n startclntd();\n amain ();\n}\n\n\n\n<|endoftext|>"} {"text":"\n\/**\n * @file \/home\/ryan\/programming\/atl\/test\/lists.cpp\n * @author Ryan Domigan \n * Created on Feb 14, 2015\n *\/\n\n#include \"..\/atl.hpp\"\n#include \"..\/helpers.hpp\"\n\n#include \"..\/debug.hpp\"\n\n#include \n#include \n\n#include \n\n\nusing namespace atl;\nusing namespace std;\n\nstruct ListTest : public ::testing::Test\n{\n Atl atl;\n\n \/\/ Assert that two simple lists (nested lists, Symbols, and\n \/\/ Fixnums) are equivalent.\n template\n void assert_equiv(Range0 const& aa, Range1 const& bb)\n {\n auto aitr = aa.begin(), bitr = bb.begin();\n for(;\n (aitr != aa.end()) && (bitr != bb.end());\n ++aitr, ++bitr)\n {\n ASSERT_EQ(((*aitr)._tag),\n ((*bitr)._tag));\n switch((*aitr)._tag)\n {\n case tag::value:\n ASSERT_EQ((unwrap(*aitr)),\n (unwrap(*bitr)));\n break;\n case tag::value:\n assert_equiv((unwrap(*aitr)),\n (unwrap(*bitr)));\n break;\n default:\n ASSERT_EQ((*aitr),\n (*bitr));\n break;\n }\n }\n ASSERT_EQ((aitr == aa.end()),\n (bitr == bb.end()));\n }\n\n bool _assert_not_equiv(Ast const& aa, Ast const& bb)\n {\n auto aitr = aa.begin(), bitr = bb.begin();\n for(;\n (aitr != aa.end()) || (bitr != bb.end());\n ++aitr, ++bitr)\n {\n if((*aitr)._tag != (*bitr)._tag)\n return true;\n\n switch((*aitr)._tag)\n {\n case tag::value:\n if(unwrap(*aitr) != unwrap(*bitr))\n return true;\n break;\n case tag::value:\n if(_assert_not_equiv((unwrap(*aitr)),\n (unwrap(*bitr))))\n return true;\n break;\n default:\n if((*aitr).value != (*bitr).value)\n return true;\n break;\n }\n }\n return (aitr != aa.end()) && (bitr != bb.end());\n }\n\n void assert_not_equiv(Ast const& aa, Ast const& bb)\n { ASSERT_TRUE(_assert_not_equiv(aa, bb)); }\n};\n\n\nTEST_F(ListTest, test_equiv_ast)\n{\n \/\/ Test manually constructed asts and my test harness's equiv\n \/\/ function.\n auto seq = atl.gc.dynamic_seq();\n auto car = seq->push_seq();\n\n seq->push_back(wrap(1));\n seq->push_back(wrap(2));\n car->end_at(seq->end());\n\n auto seq3 = atl.gc.dynamic_seq();\n car = seq3->push_seq();\n\n seq3->push_back(wrap(1));\n seq3->push_back(wrap(2));\n car->end_at(seq3->end());\n\n auto seq2 = atl.gc.dynamic_seq();\n car = seq2->push_seq();\n\n seq2->push_back(wrap(1));\n seq2->push_back(wrap(2));\n seq2->push_back(wrap(3));\n car->end_at(seq2->end());\n\n\n assert_not_equiv((unwrap(*seq->begin())),\n (unwrap(*seq2->begin())));\n\n assert_equiv((unwrap(*seq->begin())),\n (unwrap(*seq3->begin())));\n}\n\nTEST_F(ListTest, test_quote)\n{\n \/\/ Constructing a list from function calls is complicated by the\n \/\/ need to tag the list memebers. Make sure quoting works first.\n {\n auto rval = atl.string_(\"'(1 2 (a b))\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 2 (a b))\"))));\n }\n\n {\n auto rval = atl.string_(\"'(1)\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1)\"))));\n }\n}\n\n\nTEST_F(ListTest, test_indexing)\n{\n {\n auto rval = atl.string_(\"(nth '(1 2 3) 0)\");\n ASSERT_EQ((unwrap(*unwrap(rval).value).value),\n 1);\n }\n\n {\n auto rval = atl.string_(\"(nth '(1 2 3) 1)\");\n ASSERT_EQ((unwrap(*unwrap(rval).value).value),\n 2);\n }\n}\n\n\nTEST_F(ListTest, test_slice)\n{\n auto result = atl.string_(\"(slice '(1 2 3 4) 2)\");\n\n assert_equiv((unwrap(result)),\n (unwrap(atl.parse.string_(\"(3 4)\"))));\n}\n\n\nTEST_F(ListTest, test_make_ast)\n{\n\tusing namespace make_ast;\n\n\t{\n\t\tauto ast = make(lift(1), lift(2), lift(3))\n\t\t\t(*atl.env.gc.dynamic_seq());\n\n\t\tassert_equiv((*ast),\n\t\t unwrap(atl.parse.string_(\"(1 2 3)\")));\n\t}\n\n\t{\n\t\tauto ast = make(lift(1),\n\t\t make(lift(2), lift(3)),\n\t\t lift(4))\n\t\t\t(*atl.env.gc.dynamic_seq());\n\n\t\tassert_equiv((*ast),\n\t\t unwrap(atl.parse.string_(\"(1 (2 3) 4)\")));\n\t}\n}\n\nTEST_F(ListTest, test_list)\n{\n {\n auto rval = atl.string_(\"(Ast 1 2 3)\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 2 3)\"))));\n }\n\n {\n auto rval = atl.string_(\"(Ast)\");\n assert_equiv((unwrap(rval)),\n (*make_ast::make()(*atl.env.gc.dynamic_seq())));\n }\n\n {\n auto rval = atl.string_(\"(Ast 1 (Ast 2 3))\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 (2 3))\"))));\n }\n\n {\n auto rval = atl.string_(\"(Ast 1 (Ast 2 3) 4)\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 (2 3) 4)\"))));\n }\n}\n\nTEST_F(ListTest, test_cons)\n{\n auto result = atl.string_(\"(cons 0 '(1))\");\n cout << printer::any(result) << endl;\n}\n\nTest embedded Asts with quote and nth\n\/**\n * @file \/home\/ryan\/programming\/atl\/test\/lists.cpp\n * @author Ryan Domigan \n * Created on Feb 14, 2015\n *\/\n\n#include \"..\/atl.hpp\"\n#include \"..\/helpers.hpp\"\n\n#include \"..\/debug.hpp\"\n\n#include \n#include \n\n#include \n\n\nusing namespace atl;\nusing namespace std;\n\nstruct ListTest : public ::testing::Test\n{\n Atl atl;\n\n \/\/ Assert that two simple lists (nested lists, Symbols, and\n \/\/ Fixnums) are equivalent.\n template\n void assert_equiv(Range0 const& aa, Range1 const& bb)\n {\n auto aitr = aa.begin(), bitr = bb.begin();\n for(;\n (aitr != aa.end()) && (bitr != bb.end());\n ++aitr, ++bitr)\n {\n ASSERT_EQ(((*aitr)._tag),\n ((*bitr)._tag));\n switch((*aitr)._tag)\n {\n case tag::value:\n ASSERT_EQ((unwrap(*aitr)),\n (unwrap(*bitr)));\n break;\n case tag::value:\n assert_equiv((unwrap(*aitr)),\n (unwrap(*bitr)));\n break;\n default:\n ASSERT_EQ((*aitr),\n (*bitr));\n break;\n }\n }\n ASSERT_EQ((aitr == aa.end()),\n (bitr == bb.end()));\n }\n\n bool _assert_not_equiv(Ast const& aa, Ast const& bb)\n {\n auto aitr = aa.begin(), bitr = bb.begin();\n for(;\n (aitr != aa.end()) || (bitr != bb.end());\n ++aitr, ++bitr)\n {\n if((*aitr)._tag != (*bitr)._tag)\n return true;\n\n switch((*aitr)._tag)\n {\n case tag::value:\n if(unwrap(*aitr) != unwrap(*bitr))\n return true;\n break;\n case tag::value:\n if(_assert_not_equiv((unwrap(*aitr)),\n (unwrap(*bitr))))\n return true;\n break;\n default:\n if((*aitr).value != (*bitr).value)\n return true;\n break;\n }\n }\n return (aitr != aa.end()) && (bitr != bb.end());\n }\n\n void assert_not_equiv(Ast const& aa, Ast const& bb)\n { ASSERT_TRUE(_assert_not_equiv(aa, bb)); }\n};\n\n\nTEST_F(ListTest, test_equiv_ast)\n{\n \/\/ Test manually constructed asts and my test harness's equiv\n \/\/ function.\n auto seq = atl.gc.dynamic_seq();\n auto car = seq->push_seq();\n\n seq->push_back(wrap(1));\n seq->push_back(wrap(2));\n car->end_at(seq->end());\n\n auto seq3 = atl.gc.dynamic_seq();\n car = seq3->push_seq();\n\n seq3->push_back(wrap(1));\n seq3->push_back(wrap(2));\n car->end_at(seq3->end());\n\n auto seq2 = atl.gc.dynamic_seq();\n car = seq2->push_seq();\n\n seq2->push_back(wrap(1));\n seq2->push_back(wrap(2));\n seq2->push_back(wrap(3));\n car->end_at(seq2->end());\n\n\n assert_not_equiv((unwrap(*seq->begin())),\n (unwrap(*seq2->begin())));\n\n assert_equiv((unwrap(*seq->begin())),\n (unwrap(*seq3->begin())));\n}\n\nTEST_F(ListTest, test_quote)\n{\n \/\/ Constructing a list from function calls is complicated by the\n \/\/ need to tag the list memebers. Make sure quoting works first.\n {\n auto rval = atl.string_(\"'(1 2 (a b))\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 2 (a b))\"))));\n }\n\n {\n auto rval = atl.string_(\"'(1)\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1)\"))));\n }\n}\n\n\/\/ Check that I can quote an embedded Ast\nTEST_F(ListTest, test_quote_embedded)\n{\n\tusing namespace make_ast;\n\tArena arena;\n\n\tauto inner = make\n\t\t(lift(1), lift(2), lift(3))\n\t\t(*arena.dynamic_seq());\n\n\tauto expr = make\n\t\t(lift(),\n\t\t lift(*inner))\n\t\t(*arena.dynamic_seq());\n\n\tassert_equiv(*expr,\n\t unwrap(atl.parse.string_(\"'(1 2 3)\")));\n}\n\n\nTEST_F(ListTest, test_indexing)\n{\n {\n auto rval = atl.string_(\"(nth '(1 2 3) 0)\");\n ASSERT_EQ((unwrap(*unwrap(rval).value).value),\n 1);\n }\n\n {\n auto rval = atl.string_(\"(nth '(1 2 3) 1)\");\n ASSERT_EQ((unwrap(*unwrap(rval).value).value),\n 2);\n }\n}\n\n\/\/ Check that I can get the index of an embedded Ast\nTEST_F(ListTest, test_index_embedded)\n{\n\tusing namespace make_ast;\n\tArena arena;\n\n\tauto inner = make\n\t\t(lift(),\n\t\t make(lift(1), lift(2), lift(3)))\n\t\t(*arena.dynamic_seq());\n\n\tauto expr = make\n\t\t(lift(arena.amake(\"nth\")),\n\t\t lift(*inner),\n\t\t lift(1))\n\t\t(*arena.dynamic_seq());\n\n\tauto rval = atl.eval(wrap(*expr));\n\tASSERT_EQ(unwrap(*unwrap(rval).value).value,\n\t 2);\n}\n\nTEST_F(ListTest, test_slice)\n{\n\tauto result = atl.string_(\"(slice '(1 2 3 4) 2)\");\n\n assert_equiv((unwrap(result)),\n (unwrap(atl.parse.string_(\"(3 4)\"))));\n}\n\n\nTEST_F(ListTest, test_make_ast)\n{\n\tusing namespace make_ast;\n\n\t{\n\t\tauto ast = make(lift(1), lift(2), lift(3))\n\t\t\t(*atl.env.gc.dynamic_seq());\n\n\t\tassert_equiv((*ast),\n\t\t unwrap(atl.parse.string_(\"(1 2 3)\")));\n\t}\n\n\t{\n\t\tauto ast = make(lift(1),\n\t\t make(lift(2), lift(3)),\n\t\t lift(4))\n\t\t\t(*atl.env.gc.dynamic_seq());\n\n\t\tassert_equiv((*ast),\n\t\t unwrap(atl.parse.string_(\"(1 (2 3) 4)\")));\n\t}\n}\n\nTEST_F(ListTest, test_list)\n{\n {\n auto rval = atl.string_(\"(Ast 1 2 3)\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 2 3)\"))));\n }\n\n {\n auto rval = atl.string_(\"(Ast)\");\n assert_equiv((unwrap(rval)),\n (*make_ast::make()(*atl.env.gc.dynamic_seq())));\n }\n\n {\n auto rval = atl.string_(\"(Ast 1 (Ast 2 3))\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 (2 3))\"))));\n }\n\n {\n auto rval = atl.string_(\"(Ast 1 (Ast 2 3) 4)\");\n assert_equiv((unwrap(rval)),\n (unwrap(atl.parse.string_(\"(1 (2 3) 4)\"))));\n }\n}\n\nTEST_F(ListTest, test_cons)\n{\n auto result = atl.string_(\"(cons 0 '(1))\");\n cout << printer::any(result) << endl;\n}\n\n<|endoftext|>"} {"text":"Fix a typo pointed out by wtc after I checked in.<|endoftext|>"} {"text":"\/\/===- ReduceArguments.cpp - Specialized Delta Pass -----------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a function which calls the Generic Delta pass in order\n\/\/ to reduce uninteresting Arguments from defined functions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ReduceBasicBlocks.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Value.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n\nusing namespace llvm;\n\n\/\/\/ Replaces BB Terminator with one that only contains Chunk BBs\nstatic void replaceBranchTerminator(BasicBlock &BB,\n std::set BBsToKeep) {\n auto Term = BB.getTerminator();\n std::vector ChunkSucessors;\n for (auto Succ : successors(&BB))\n if (BBsToKeep.count(Succ))\n ChunkSucessors.push_back(Succ);\n\n \/\/ BB only references Chunk BBs\n if (ChunkSucessors.size() == Term->getNumSuccessors())\n return;\n\n Term->eraseFromParent();\n\n if (ChunkSucessors.empty()) {\n ReturnInst::Create(BB.getContext(), nullptr, &BB);\n return;\n }\n\n if (isa(Term))\n BranchInst::Create(ChunkSucessors[0], &BB);\n\n if (auto IndBI = dyn_cast(Term)) {\n auto NewIndBI =\n IndirectBrInst::Create(IndBI->getAddress(), ChunkSucessors.size(), &BB);\n for (auto Dest : ChunkSucessors)\n NewIndBI->addDestination(Dest);\n }\n}\n\n\/\/\/ Removes uninteresting BBs from switch, if the default case ends up being\n\/\/\/ uninteresting, the switch is replaced with a void return (since it has to be\n\/\/\/ replace with something)\nstatic void removeUninterestingBBsFromSwitch(SwitchInst &SwInst,\n std::set BBsToKeep) {\n if (!BBsToKeep.count(SwInst.getDefaultDest())) {\n ReturnInst::Create(SwInst.getContext(), nullptr, SwInst.getParent());\n SwInst.eraseFromParent();\n } else\n for (int I = 0, E = SwInst.getNumCases(); I != E; ++I) {\n auto Case = SwInst.case_begin() + I;\n if (!BBsToKeep.count(Case->getCaseSuccessor())) {\n SwInst.removeCase(Case);\n --I;\n --E;\n }\n }\n}\n\n\/\/\/ Removes out-of-chunk arguments from functions, and modifies their calls\n\/\/\/ accordingly. It also removes allocations of out-of-chunk arguments.\n\/\/\/ @returns the Module stripped of out-of-chunk functions\nstatic void extractBasicBlocksFromModule(std::vector ChunksToKeep,\n Module *Program) {\n int I = 0, BBCount = 0;\n std::set BBsToKeep;\n\n for (auto &F : *Program)\n for (auto &BB : F)\n if (I < (int)ChunksToKeep.size()) {\n if (ChunksToKeep[I].contains(++BBCount))\n BBsToKeep.insert(&BB);\n if (ChunksToKeep[I].end == BBCount)\n ++I;\n }\n\n std::vector BBsToDelete;\n for (auto &F : *Program)\n for (auto &BB : F) {\n if (!BBsToKeep.count(&BB)) {\n BBsToDelete.push_back(&BB);\n \/\/ Remove out-of-chunk BB from successor phi nodes\n for (auto *Succ : successors(&BB))\n Succ->removePredecessor(&BB);\n }\n }\n\n \/\/ Replace terminators that reference out-of-chunk BBs\n for (auto &F : *Program)\n for (auto &BB : F) {\n if (auto *SwInst = dyn_cast(BB.getTerminator()))\n removeUninterestingBBsFromSwitch(*SwInst, BBsToKeep);\n else\n replaceBranchTerminator(BB, BBsToKeep);\n }\n\n \/\/ Replace out-of-chunk switch uses\n for (auto &BB : BBsToDelete) {\n \/\/ Instructions might be referenced in other BBs\n for (auto &I : *BB)\n I.replaceAllUsesWith(UndefValue::get(I.getType()));\n BB->eraseFromParent();\n }\n}\n\n\/\/\/ Counts the amount of basic blocks and prints their name & respective index\nstatic int countBasicBlocks(Module *Program) {\n \/\/ TODO: Silence index with --quiet flag\n outs() << \"----------------------------\\n\";\n int BBCount = 0;\n for (auto &F : *Program)\n for (auto &BB : F) {\n if (BB.hasName())\n outs() << \"\\t\" << ++BBCount << \": \" << BB.getName() << \"\\n\";\n else\n outs() << \"\\t\" << ++BBCount << \": Unnamed\\n\";\n }\n\n return BBCount;\n}\n\nvoid llvm::reduceBasicBlocksDeltaPass(TestRunner &Test) {\n outs() << \"*** Reducing Basic Blocks...\\n\";\n int BBCount = countBasicBlocks(Test.getProgram());\n runDeltaPass(Test, BBCount, extractBasicBlocksFromModule);\n}\nllvm-reduce: Remove inaccurate doxy comment about a return that isn't returned\/\/===- ReduceArguments.cpp - Specialized Delta Pass -----------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a function which calls the Generic Delta pass in order\n\/\/ to reduce uninteresting Arguments from defined functions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ReduceBasicBlocks.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Instruction.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Value.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n\nusing namespace llvm;\n\n\/\/\/ Replaces BB Terminator with one that only contains Chunk BBs\nstatic void replaceBranchTerminator(BasicBlock &BB,\n std::set BBsToKeep) {\n auto Term = BB.getTerminator();\n std::vector ChunkSucessors;\n for (auto Succ : successors(&BB))\n if (BBsToKeep.count(Succ))\n ChunkSucessors.push_back(Succ);\n\n \/\/ BB only references Chunk BBs\n if (ChunkSucessors.size() == Term->getNumSuccessors())\n return;\n\n Term->eraseFromParent();\n\n if (ChunkSucessors.empty()) {\n ReturnInst::Create(BB.getContext(), nullptr, &BB);\n return;\n }\n\n if (isa(Term))\n BranchInst::Create(ChunkSucessors[0], &BB);\n\n if (auto IndBI = dyn_cast(Term)) {\n auto NewIndBI =\n IndirectBrInst::Create(IndBI->getAddress(), ChunkSucessors.size(), &BB);\n for (auto Dest : ChunkSucessors)\n NewIndBI->addDestination(Dest);\n }\n}\n\n\/\/\/ Removes uninteresting BBs from switch, if the default case ends up being\n\/\/\/ uninteresting, the switch is replaced with a void return (since it has to be\n\/\/\/ replace with something)\nstatic void removeUninterestingBBsFromSwitch(SwitchInst &SwInst,\n std::set BBsToKeep) {\n if (!BBsToKeep.count(SwInst.getDefaultDest())) {\n ReturnInst::Create(SwInst.getContext(), nullptr, SwInst.getParent());\n SwInst.eraseFromParent();\n } else\n for (int I = 0, E = SwInst.getNumCases(); I != E; ++I) {\n auto Case = SwInst.case_begin() + I;\n if (!BBsToKeep.count(Case->getCaseSuccessor())) {\n SwInst.removeCase(Case);\n --I;\n --E;\n }\n }\n}\n\n\/\/\/ Removes out-of-chunk arguments from functions, and modifies their calls\n\/\/\/ accordingly. It also removes allocations of out-of-chunk arguments.\nstatic void extractBasicBlocksFromModule(std::vector ChunksToKeep,\n Module *Program) {\n int I = 0, BBCount = 0;\n std::set BBsToKeep;\n\n for (auto &F : *Program)\n for (auto &BB : F)\n if (I < (int)ChunksToKeep.size()) {\n if (ChunksToKeep[I].contains(++BBCount))\n BBsToKeep.insert(&BB);\n if (ChunksToKeep[I].end == BBCount)\n ++I;\n }\n\n std::vector BBsToDelete;\n for (auto &F : *Program)\n for (auto &BB : F) {\n if (!BBsToKeep.count(&BB)) {\n BBsToDelete.push_back(&BB);\n \/\/ Remove out-of-chunk BB from successor phi nodes\n for (auto *Succ : successors(&BB))\n Succ->removePredecessor(&BB);\n }\n }\n\n \/\/ Replace terminators that reference out-of-chunk BBs\n for (auto &F : *Program)\n for (auto &BB : F) {\n if (auto *SwInst = dyn_cast(BB.getTerminator()))\n removeUninterestingBBsFromSwitch(*SwInst, BBsToKeep);\n else\n replaceBranchTerminator(BB, BBsToKeep);\n }\n\n \/\/ Replace out-of-chunk switch uses\n for (auto &BB : BBsToDelete) {\n \/\/ Instructions might be referenced in other BBs\n for (auto &I : *BB)\n I.replaceAllUsesWith(UndefValue::get(I.getType()));\n BB->eraseFromParent();\n }\n}\n\n\/\/\/ Counts the amount of basic blocks and prints their name & respective index\nstatic int countBasicBlocks(Module *Program) {\n \/\/ TODO: Silence index with --quiet flag\n outs() << \"----------------------------\\n\";\n int BBCount = 0;\n for (auto &F : *Program)\n for (auto &BB : F) {\n if (BB.hasName())\n outs() << \"\\t\" << ++BBCount << \": \" << BB.getName() << \"\\n\";\n else\n outs() << \"\\t\" << ++BBCount << \": Unnamed\\n\";\n }\n\n return BBCount;\n}\n\nvoid llvm::reduceBasicBlocksDeltaPass(TestRunner &Test) {\n outs() << \"*** Reducing Basic Blocks...\\n\";\n int BBCount = countBasicBlocks(Test.getProgram());\n runDeltaPass(Test, BBCount, extractBasicBlocksFromModule);\n}\n<|endoftext|>"} {"text":"#include \"util\/testing.h\"\n\n#include \n#include \n#include \n\nnamespace cert_trans {\nnamespace test {\n\nvoid InitTesting(const char* name, int* argc, char*** argv,\n bool remove_flags) {\n \/\/ Change the defaults. Can be overridden on command line.\n \/\/ Log to stderr instead of log files.\n FLAGS_logtostderr = true;\n \/\/ Only log fatal messages by default.\n FLAGS_minloglevel = 3;\n ::testing::InitGoogleTest(argc, *argv);\n google::ParseCommandLineFlags(argc, argv, remove_flags);\n google::InitGoogleLogging(name);\n}\n\n} \/\/ namespace test\n} \/\/ namespace cert_trans\nCall evthread_use_pthreads() in all tests.#include \"util\/testing.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace cert_trans {\nnamespace test {\n\nvoid InitTesting(const char* name, int* argc, char*** argv,\n bool remove_flags) {\n \/\/ Change the defaults. Can be overridden on command line.\n \/\/ Log to stderr instead of log files.\n FLAGS_logtostderr = true;\n \/\/ Only log fatal messages by default.\n FLAGS_minloglevel = 3;\n ::testing::InitGoogleTest(argc, *argv);\n google::ParseCommandLineFlags(argc, argv, remove_flags);\n google::InitGoogleLogging(name);\n evthread_use_pthreads();\n}\n\n} \/\/ namespace test\n} \/\/ namespace cert_trans\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"paddle\/fluid\/framework\/tensor.h\"\n#include \n#include \n#include \"paddle\/fluid\/platform\/float16.h\"\n\nnamespace framework = paddle::framework;\nnamespace platform = paddle::platform;\n\nTEST(Tensor, Dims) {\n framework::Tensor tt;\n tt.Resize({2, 3, 4});\n framework::DDim dims = tt.dims();\n ASSERT_EQ(arity(dims), 3);\n for (int i = 0; i < 3; ++i) {\n EXPECT_EQ(i + 2, dims[i]);\n }\n}\n\nTEST(Tensor, DataAssert) {\n framework::Tensor src_tensor;\n\n bool caught = false;\n try {\n src_tensor.data();\n } catch (platform::EnforceNotMet err) {\n caught = true;\n std::string msg =\n \"holder_ should not be null\\nTensor holds no memory. Call \"\n \"Tensor::mutable_data first.\";\n const char* what = err.what();\n for (size_t i = 0; i < msg.length(); ++i) {\n ASSERT_EQ(what[i], msg[i]);\n }\n }\n ASSERT_TRUE(caught);\n}\n\nTEST(Tensor, MutableData) {\n {\n framework::Tensor src_tensor;\n float* p1 = nullptr;\n float* p2 = nullptr;\n \/\/ initialization\n p1 = src_tensor.mutable_data(framework::make_ddim({1, 2, 3}),\n platform::CPUPlace());\n EXPECT_NE(p1, nullptr);\n \/\/ set src_tensor a new dim with large size\n \/\/ momery is supposed to be re-allocated\n p2 = src_tensor.mutable_data(framework::make_ddim({3, 4}),\n platform::CPUPlace());\n EXPECT_NE(p2, nullptr);\n EXPECT_NE(p1, p2);\n \/\/ set src_tensor a new dim with same size\n \/\/ momery block is supposed to be unchanged\n p1 = src_tensor.mutable_data(framework::make_ddim({2, 2, 3}),\n platform::CPUPlace());\n EXPECT_EQ(p1, p2);\n \/\/ set src_tensor a new dim with smaller size\n \/\/ momery block is supposed to be unchanged\n p2 = src_tensor.mutable_data(framework::make_ddim({2, 2}),\n platform::CPUPlace());\n EXPECT_EQ(p1, p2);\n }\n\n#ifdef PADDLE_WITH_CUDA\n {\n framework::Tensor src_tensor;\n float* p1 = nullptr;\n float* p2 = nullptr;\n \/\/ initialization\n p1 = src_tensor.mutable_data(framework::make_ddim({1, 2, 3}),\n platform::CUDAPlace());\n EXPECT_NE(p1, nullptr);\n \/\/ set src_tensor a new dim with large size\n \/\/ momery is supposed to be re-allocated\n p2 = src_tensor.mutable_data(framework::make_ddim({3, 4}),\n platform::CUDAPlace());\n EXPECT_NE(p2, nullptr);\n EXPECT_NE(p1, p2);\n \/\/ set src_tensor a new dim with same size\n \/\/ momery block is supposed to be unchanged\n p1 = src_tensor.mutable_data(framework::make_ddim({2, 2, 3}),\n platform::CUDAPlace());\n EXPECT_EQ(p1, p2);\n \/\/ set src_tensor a new dim with smaller size\n \/\/ momery block is supposed to be unchanged\n p2 = src_tensor.mutable_data(framework::make_ddim({2, 2}),\n platform::CUDAPlace());\n EXPECT_EQ(p1, p2);\n }\n#endif\n}\n\nTEST(Tensor, ShareDataWith) {\n {\n framework::Tensor src_tensor;\n framework::Tensor dst_tensor;\n \/\/ Try to share data form uninitialized tensor\n bool caught = false;\n try {\n dst_tensor.ShareDataWith(src_tensor);\n } catch (paddle::platform::EnforceNotMet err) {\n caught = true;\n std::string msg =\n \"holder_ should not be null\\nTensor holds no memory. Call \"\n \"Tensor::mutable_data first.\";\n const char* what = err.what();\n for (size_t i = 0; i < msg.length(); ++i) {\n ASSERT_EQ(what[i], msg[i]);\n }\n }\n ASSERT_TRUE(caught);\n\n src_tensor.mutable_data(framework::make_ddim({2, 3, 4}),\n platform::CPUPlace());\n dst_tensor.ShareDataWith(src_tensor);\n ASSERT_EQ(src_tensor.data(), dst_tensor.data());\n }\n\n#ifdef PADDLE_WITH_CUDA\n {\n framework::Tensor src_tensor;\n framework::Tensor dst_tensor;\n src_tensor.mutable_data(framework::make_ddim({2, 3, 4}),\n platform::CUDAPlace());\n dst_tensor.ShareDataWith(src_tensor);\n ASSERT_EQ(src_tensor.data(), dst_tensor.data());\n }\n#endif\n}\n\nTEST(Tensor, Slice) {\n {\n framework::Tensor src_tensor;\n src_tensor.mutable_data(framework::make_ddim({5, 3, 4}),\n platform::CPUPlace());\n framework::Tensor slice_tensor = src_tensor.Slice(1, 3);\n framework::DDim slice_dims = slice_tensor.dims();\n ASSERT_EQ(arity(slice_dims), 3);\n EXPECT_EQ(slice_dims[0], 2);\n EXPECT_EQ(slice_dims[1], 3);\n EXPECT_EQ(slice_dims[2], 4);\n\n uintptr_t src_data_address =\n reinterpret_cast(src_tensor.data());\n uintptr_t src_mutable_data_address = reinterpret_cast(\n src_tensor.mutable_data(src_tensor.dims(), platform::CPUPlace()));\n uintptr_t slice_data_address =\n reinterpret_cast(slice_tensor.data());\n uintptr_t slice_mutable_data_address =\n reinterpret_cast(slice_tensor.mutable_data(\n slice_tensor.dims(), platform::CPUPlace()));\n EXPECT_EQ(src_data_address, src_mutable_data_address);\n EXPECT_EQ(slice_data_address, slice_mutable_data_address);\n EXPECT_EQ(src_data_address + 3 * 4 * 1 * sizeof(int), slice_data_address);\n }\n\n#ifdef PADDLE_WITH_CUDA\n {\n framework::Tensor src_tensor;\n src_tensor.mutable_data(framework::make_ddim({6, 9}),\n platform::CUDAPlace());\n framework::Tensor slice_tensor = src_tensor.Slice(2, 6);\n framework::DDim slice_dims = slice_tensor.dims();\n ASSERT_EQ(arity(slice_dims), 2);\n EXPECT_EQ(slice_dims[0], 4);\n EXPECT_EQ(slice_dims[1], 9);\n\n uintptr_t src_data_address =\n reinterpret_cast(src_tensor.data());\n uintptr_t src_mutable_data_address =\n reinterpret_cast(src_tensor.mutable_data(\n src_tensor.dims(), platform::CUDAPlace()));\n uintptr_t slice_data_address =\n reinterpret_cast(slice_tensor.data());\n uintptr_t slice_mutable_data_address =\n reinterpret_cast(slice_tensor.mutable_data(\n slice_tensor.dims(), platform::CUDAPlace()));\n EXPECT_EQ(src_data_address, src_mutable_data_address);\n EXPECT_EQ(slice_data_address, slice_mutable_data_address);\n EXPECT_EQ(src_data_address + 9 * 2 * sizeof(double), slice_data_address);\n }\n#endif\n}\n\nTEST(Tensor, ReshapeToMatrix) {\n framework::Tensor src;\n int* src_ptr = src.mutable_data({2, 3, 4, 9}, platform::CPUPlace());\n for (int i = 0; i < 2 * 3 * 4 * 9; ++i) {\n src_ptr[i] = i;\n }\n framework::Tensor res = framework::ReshapeToMatrix(src, 2);\n ASSERT_EQ(res.dims()[0], 2 * 3);\n ASSERT_EQ(res.dims()[1], 4 * 9);\n}\n\nTEST(Tensor, Layout) {\n framework::Tensor src;\n ASSERT_EQ(src.layout(), framework::DataLayout::kNCHW);\n src.set_layout(framework::DataLayout::kAnyLayout);\n ASSERT_EQ(src.layout(), framework::DataLayout::kAnyLayout);\n}\n\nTEST(Tensor, FP16) {\n using platform::float16;\n framework::Tensor src;\n float16* src_ptr = src.mutable_data({2, 3}, platform::CPUPlace());\n for (int i = 0; i < 2 * 3; ++i) {\n src_ptr[i] = static_cast(i);\n }\n EXPECT_EQ(src.memory_size(), 2 * 3 * sizeof(float16));\n \/\/ EXPECT a human readable error message\n \/\/ src.data();\n \/\/ Tensor holds the wrong type, it holds N6paddle8platform7float16E at\n \/\/ [\/paddle\/Paddle\/paddle\/fluid\/framework\/tensor_impl.h:43]\n}\nadd a small test to verify tensor type\/\/ Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"paddle\/fluid\/framework\/tensor.h\"\n#include \n#include \n#include \"paddle\/fluid\/platform\/float16.h\"\n\nnamespace framework = paddle::framework;\nnamespace platform = paddle::platform;\n\nTEST(Tensor, Dims) {\n framework::Tensor tt;\n tt.Resize({2, 3, 4});\n framework::DDim dims = tt.dims();\n ASSERT_EQ(arity(dims), 3);\n for (int i = 0; i < 3; ++i) {\n EXPECT_EQ(i + 2, dims[i]);\n }\n}\n\nTEST(Tensor, DataAssert) {\n framework::Tensor src_tensor;\n\n bool caught = false;\n try {\n src_tensor.data();\n } catch (platform::EnforceNotMet err) {\n caught = true;\n std::string msg =\n \"holder_ should not be null\\nTensor holds no memory. Call \"\n \"Tensor::mutable_data first.\";\n const char* what = err.what();\n for (size_t i = 0; i < msg.length(); ++i) {\n ASSERT_EQ(what[i], msg[i]);\n }\n }\n ASSERT_TRUE(caught);\n}\n\nTEST(Tensor, MutableData) {\n {\n framework::Tensor src_tensor;\n float* p1 = nullptr;\n float* p2 = nullptr;\n \/\/ initialization\n p1 = src_tensor.mutable_data(framework::make_ddim({1, 2, 3}),\n platform::CPUPlace());\n EXPECT_NE(p1, nullptr);\n \/\/ set src_tensor a new dim with large size\n \/\/ momery is supposed to be re-allocated\n p2 = src_tensor.mutable_data(framework::make_ddim({3, 4}),\n platform::CPUPlace());\n EXPECT_NE(p2, nullptr);\n EXPECT_NE(p1, p2);\n \/\/ set src_tensor a new dim with same size\n \/\/ momery block is supposed to be unchanged\n p1 = src_tensor.mutable_data(framework::make_ddim({2, 2, 3}),\n platform::CPUPlace());\n EXPECT_EQ(p1, p2);\n \/\/ set src_tensor a new dim with smaller size\n \/\/ momery block is supposed to be unchanged\n p2 = src_tensor.mutable_data(framework::make_ddim({2, 2}),\n platform::CPUPlace());\n EXPECT_EQ(p1, p2);\n }\n \/\/ Not sure if it's desired, but currently, Tensor type can be changed.\n {\n framework::Tensor src_tensor;\n int8_t* p1 = src_tensor.mutable_data(framework::make_ddim({1}),\n platform::CPUPlace());\n EXPECT_NE(p1, nullptr);\n *p1 = 1;\n\n uint8_t* p2 = src_tensor.mutable_data(framework::make_ddim({1}),\n platform::CPUPlace());\n EXPECT_NE(p2, nullptr);\n EXPECT_EQ(static_cast(p2[0]), 1);\n }\n\n#ifdef PADDLE_WITH_CUDA\n {\n framework::Tensor src_tensor;\n float* p1 = nullptr;\n float* p2 = nullptr;\n \/\/ initialization\n p1 = src_tensor.mutable_data(framework::make_ddim({1, 2, 3}),\n platform::CUDAPlace());\n EXPECT_NE(p1, nullptr);\n \/\/ set src_tensor a new dim with large size\n \/\/ momery is supposed to be re-allocated\n p2 = src_tensor.mutable_data(framework::make_ddim({3, 4}),\n platform::CUDAPlace());\n EXPECT_NE(p2, nullptr);\n EXPECT_NE(p1, p2);\n \/\/ set src_tensor a new dim with same size\n \/\/ momery block is supposed to be unchanged\n p1 = src_tensor.mutable_data(framework::make_ddim({2, 2, 3}),\n platform::CUDAPlace());\n EXPECT_EQ(p1, p2);\n \/\/ set src_tensor a new dim with smaller size\n \/\/ momery block is supposed to be unchanged\n p2 = src_tensor.mutable_data(framework::make_ddim({2, 2}),\n platform::CUDAPlace());\n EXPECT_EQ(p1, p2);\n }\n#endif\n}\n\nTEST(Tensor, ShareDataWith) {\n {\n framework::Tensor src_tensor;\n framework::Tensor dst_tensor;\n \/\/ Try to share data form uninitialized tensor\n bool caught = false;\n try {\n dst_tensor.ShareDataWith(src_tensor);\n } catch (paddle::platform::EnforceNotMet err) {\n caught = true;\n std::string msg =\n \"holder_ should not be null\\nTensor holds no memory. Call \"\n \"Tensor::mutable_data first.\";\n const char* what = err.what();\n for (size_t i = 0; i < msg.length(); ++i) {\n ASSERT_EQ(what[i], msg[i]);\n }\n }\n ASSERT_TRUE(caught);\n\n src_tensor.mutable_data(framework::make_ddim({2, 3, 4}),\n platform::CPUPlace());\n dst_tensor.ShareDataWith(src_tensor);\n ASSERT_EQ(src_tensor.data(), dst_tensor.data());\n }\n\n#ifdef PADDLE_WITH_CUDA\n {\n framework::Tensor src_tensor;\n framework::Tensor dst_tensor;\n src_tensor.mutable_data(framework::make_ddim({2, 3, 4}),\n platform::CUDAPlace());\n dst_tensor.ShareDataWith(src_tensor);\n ASSERT_EQ(src_tensor.data(), dst_tensor.data());\n }\n#endif\n}\n\nTEST(Tensor, Slice) {\n {\n framework::Tensor src_tensor;\n src_tensor.mutable_data(framework::make_ddim({5, 3, 4}),\n platform::CPUPlace());\n framework::Tensor slice_tensor = src_tensor.Slice(1, 3);\n framework::DDim slice_dims = slice_tensor.dims();\n ASSERT_EQ(arity(slice_dims), 3);\n EXPECT_EQ(slice_dims[0], 2);\n EXPECT_EQ(slice_dims[1], 3);\n EXPECT_EQ(slice_dims[2], 4);\n\n uintptr_t src_data_address =\n reinterpret_cast(src_tensor.data());\n uintptr_t src_mutable_data_address = reinterpret_cast(\n src_tensor.mutable_data(src_tensor.dims(), platform::CPUPlace()));\n uintptr_t slice_data_address =\n reinterpret_cast(slice_tensor.data());\n uintptr_t slice_mutable_data_address =\n reinterpret_cast(slice_tensor.mutable_data(\n slice_tensor.dims(), platform::CPUPlace()));\n EXPECT_EQ(src_data_address, src_mutable_data_address);\n EXPECT_EQ(slice_data_address, slice_mutable_data_address);\n EXPECT_EQ(src_data_address + 3 * 4 * 1 * sizeof(int), slice_data_address);\n }\n\n#ifdef PADDLE_WITH_CUDA\n {\n framework::Tensor src_tensor;\n src_tensor.mutable_data(framework::make_ddim({6, 9}),\n platform::CUDAPlace());\n framework::Tensor slice_tensor = src_tensor.Slice(2, 6);\n framework::DDim slice_dims = slice_tensor.dims();\n ASSERT_EQ(arity(slice_dims), 2);\n EXPECT_EQ(slice_dims[0], 4);\n EXPECT_EQ(slice_dims[1], 9);\n\n uintptr_t src_data_address =\n reinterpret_cast(src_tensor.data());\n uintptr_t src_mutable_data_address =\n reinterpret_cast(src_tensor.mutable_data(\n src_tensor.dims(), platform::CUDAPlace()));\n uintptr_t slice_data_address =\n reinterpret_cast(slice_tensor.data());\n uintptr_t slice_mutable_data_address =\n reinterpret_cast(slice_tensor.mutable_data(\n slice_tensor.dims(), platform::CUDAPlace()));\n EXPECT_EQ(src_data_address, src_mutable_data_address);\n EXPECT_EQ(slice_data_address, slice_mutable_data_address);\n EXPECT_EQ(src_data_address + 9 * 2 * sizeof(double), slice_data_address);\n }\n#endif\n}\n\nTEST(Tensor, ReshapeToMatrix) {\n framework::Tensor src;\n int* src_ptr = src.mutable_data({2, 3, 4, 9}, platform::CPUPlace());\n for (int i = 0; i < 2 * 3 * 4 * 9; ++i) {\n src_ptr[i] = i;\n }\n framework::Tensor res = framework::ReshapeToMatrix(src, 2);\n ASSERT_EQ(res.dims()[0], 2 * 3);\n ASSERT_EQ(res.dims()[1], 4 * 9);\n}\n\nTEST(Tensor, Layout) {\n framework::Tensor src;\n ASSERT_EQ(src.layout(), framework::DataLayout::kNCHW);\n src.set_layout(framework::DataLayout::kAnyLayout);\n ASSERT_EQ(src.layout(), framework::DataLayout::kAnyLayout);\n}\n\nTEST(Tensor, FP16) {\n using platform::float16;\n framework::Tensor src;\n float16* src_ptr = src.mutable_data({2, 3}, platform::CPUPlace());\n for (int i = 0; i < 2 * 3; ++i) {\n src_ptr[i] = static_cast(i);\n }\n EXPECT_EQ(src.memory_size(), 2 * 3 * sizeof(float16));\n \/\/ EXPECT a human readable error message\n \/\/ src.data();\n \/\/ Tensor holds the wrong type, it holds N6paddle8platform7float16E at\n \/\/ [\/paddle\/Paddle\/paddle\/fluid\/framework\/tensor_impl.h:43]\n}\n<|endoftext|>"} {"text":"#include \n#ifndef HAVE_GETOPT\n #include \n#else\n #include \n#endif\n#include \n#include \n\nint\nmain(int argc, char *argv[]) {\n if (argc < 3) {\n cerr << \"Usage: multify -[x,c|v] ...\" << endl;\n return 0;\n }\n\n bool verbose = true;\n bool extract = false;\n\n extern char *optarg;\n extern int optind;\n int flag = getopt(argc, argv, \"xcvr:\");\n Filename rel_path;\n while (flag != EOF) {\n switch (flag) {\n case 'x':\n\textract = true;\n break;\n case 'c':\n break;\n case 'v':\n\tverbose = true;\n \tbreak;\n case 'r':\n\trel_path = optarg;\n\tbreak;\n default:\n\tcerr << \"Unhandled switch: \" << flag << endl;\n\tbreak;\n } \n flag = getopt(argc, argv, \"xcvr:\");\n }\n argc -= (optind - 1);\n argv += (optind - 1);\n\n if (argc <= 1) {\n cerr << \"Usage: multify -[x,c|v] ...\" << endl;\n return 0;\n }\n\n Filename dest_file = argv[1];\n dest_file.set_binary();\n\n if (verbose == true) {\n if (extract == true)\n cerr << \"Extracting from: \" << dest_file << endl;\n else\n cerr << \"Appending to: \" << dest_file << endl;\n }\n\n Multifile mfile;\n\n if (extract == false) {\n for (int i = 2; i < argc; i++) {\n Filename in_file = argv[i];\n in_file.set_binary();\n mfile.add(in_file);\n }\n\n if (mfile.write(dest_file) == false)\n cerr << \"Failed to write: \" << dest_file << endl;\n } else {\n mfile.read(dest_file);\n mfile.extract_all(rel_path);\n }\n\n return 1;\n}\n*** empty log message ***#include \n#ifndef HAVE_GETOPT\n #include \n#else\n #include \n#endif\n#include \n#include \n\nint\nmain(int argc, char *argv[]) {\n if (argc < 3) {\n cerr << \"Usage: multify -[x,c|vr] ...\" << endl;\n return 0;\n }\n\n bool verbose = true;\n bool extract = false;\n\n extern char *optarg;\n extern int optind;\n int flag = getopt(argc, argv, \"xcvr:\");\n Filename rel_path;\n while (flag != EOF) {\n switch (flag) {\n case 'x':\n\textract = true;\n break;\n case 'c':\n break;\n case 'v':\n\tverbose = true;\n \tbreak;\n case 'r':\n\trel_path = optarg;\n\tbreak;\n default:\n\tcerr << \"Unhandled switch: \" << flag << endl;\n\tbreak;\n } \n flag = getopt(argc, argv, \"xcvr:\");\n }\n argc -= (optind - 1);\n argv += (optind - 1);\n\n if (argc <= 1) {\n cerr << \"Usage: multify -[x,c|v] ...\" << endl;\n return 0;\n }\n\n Filename dest_file = argv[1];\n dest_file.set_binary();\n\n if (verbose == true) {\n if (extract == true)\n cerr << \"Extracting from: \" << dest_file << endl;\n else\n cerr << \"Appending to: \" << dest_file << endl;\n }\n\n Multifile mfile;\n\n if (extract == false) {\n for (int i = 2; i < argc; i++) {\n Filename in_file = argv[i];\n in_file.set_binary();\n mfile.add(in_file);\n }\n\n if (mfile.write(dest_file) == false)\n cerr << \"Failed to write: \" << dest_file << endl;\n } else {\n mfile.read(dest_file);\n mfile.extract_all(rel_path);\n }\n\n return 1;\n}\n<|endoftext|>"} {"text":"\/\/ Filename: windowsRegistry.cxx\n\/\/ Created by: drose (06Aug01)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/www.panda3d.org\/license.txt .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d@yahoogroups.com .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"windowsRegistry.h\"\n#include \"config_express.h\"\n\n#ifdef WIN32_VC\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::set_string_value\n\/\/ Access: Published, Static\n\/\/ Description: Sets the registry key to the indicated value as a\n\/\/ string. The supplied string value is automatically\n\/\/ converted from whatever encoding is set by\n\/\/ TextEncoder::set_default_encoding() and written as a\n\/\/ Unicode string. The registry key must already exist\n\/\/ prior to calling this function.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\nset_string_value(const string &key, const string &name, const string &value) {\n TextEncoder encoder;\n wstring wvalue = encoder.decode_text(value);\n\n bool okflag = true;\n\n \/\/ Now convert the string to Windows' idea of the correct wide-char\n \/\/ encoding, so we can store it in the registry. This might well be\n \/\/ the same string we just decoded from, but it might not.\n\n \/\/ Windows likes to have a null character trailing the string (even\n \/\/ though we also pass a length).\n wvalue += (wchar_t)0;\n int mb_result_len =\n WideCharToMultiByte(CP_ACP, 0,\n wvalue.data(), wvalue.length(),\n NULL, 0,\n NULL, NULL);\n if (mb_result_len == 0) {\n express_cat.error()\n << \"Unable to convert '\" << value\n << \"' from Unicode to MultiByte form.\\n\";\n return false;\n }\n\n char *mb_result = (char *)alloca(mb_result_len);\n WideCharToMultiByte(CP_ACP, 0,\n wvalue.data(), wvalue.length(),\n mb_result, mb_result_len,\n NULL, NULL);\n\n if (express_cat.is_debug()) {\n express_cat.debug()\n << \"Converted '\" << value << \"' to '\" << mb_result\n << \"' for storing in registry.\\n\";\n }\n\n return do_set(key, name, REG_SZ, mb_result, mb_result_len);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::set_int_value\n\/\/ Access: Published, Static\n\/\/ Description: Sets the registry key to the indicated value as an\n\/\/ integer. The registry key must already exist prior\n\/\/ to calling this function.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\nset_int_value(const string &key, const string &name, int value) {\n DWORD dw = value;\n return do_set(key, name, REG_DWORD, &dw, sizeof(dw));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::get_key_type\n\/\/ Access: Published, Static\n\/\/ Description: Returns the type of the indicated key, or T_none if\n\/\/ the key is not known or is some unsupported type.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nWindowsRegistry::Type WindowsRegistry::\nget_key_type(const string &key, const string &name) {\n int data_type;\n string data;\n if (!do_get(key, name, data_type, data)) {\n return T_none;\n }\n\n switch (data_type) {\n case REG_SZ:\n return T_string;\n\n case REG_DWORD:\n return T_int;\n\n default:\n return T_none;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::get_string_value\n\/\/ Access: Published, Static\n\/\/ Description: Returns the value associated with the indicated\n\/\/ registry key, assuming it is a string value. The\n\/\/ string value is automatically encoded using\n\/\/ TextEncoder::get_default_encoding(). If the key is\n\/\/ not defined or is not a string type value,\n\/\/ default_value is returned instead.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring WindowsRegistry::\nget_string_value(const string &key, const string &name,\n const string &default_value) {\n int data_type;\n string data;\n if (!do_get(key, name, data_type, data)) {\n return default_value;\n }\n\n if (data_type != REG_SZ) {\n express_cat.warning()\n << \"Registry key \" << key << \" does not contain a string value.\\n\";\n return default_value;\n }\n\n \/\/ Now we have to decode the MultiByte string to Unicode, and re-encode\n \/\/ it according to our own encoding.\n\n if (data.empty()) {\n return data;\n }\n\n int wide_result_len =\n MultiByteToWideChar(CP_ACP, 0,\n data.data(), data.length(),\n NULL, 0);\n if (wide_result_len == 0) {\n express_cat.error()\n << \"Unable to convert '\" << data \n << \"' from MultiByte to Unicode form.\\n\";\n return data;\n }\n \n wchar_t *wide_result = (wchar_t *)alloca(wide_result_len * sizeof(wchar_t));\n MultiByteToWideChar(CP_ACP, 0,\n data.data(), data.length(),\n wide_result, wide_result_len);\n\n wstring wdata(wide_result, wide_result_len);\n\n TextEncoder encoder;\n string result = encoder.encode_wtext(wdata);\n\n if (express_cat.is_debug()) {\n express_cat.debug()\n << \"Converted '\" << data << \"' from registry to '\" << result << \"'\\n\";\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::get_int_value\n\/\/ Access: Published, Static\n\/\/ Description: Returns the value associated with the indicated\n\/\/ registry key, assuming it is an integer value. If\n\/\/ the key is not defined or is not an integer type\n\/\/ value, default_value is returned instead.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint WindowsRegistry::\nget_int_value(const string &key, const string &name, int default_value) {\n int data_type;\n string data;\n if (!do_get(key, name, data_type, data)) {\n return default_value;\n }\n\n if (data_type != REG_DWORD) {\n express_cat.warning()\n << \"Registry key \" << key << \" does not contain an integer value.\\n\";\n return default_value;\n }\n \n \/\/ Now we have a DWORD encoded in a string.\n nassertr(data.length() == sizeof(DWORD), default_value);\n DWORD dw = *(DWORD *)data.data();\n return dw;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::do_set\n\/\/ Access: Private, Static\n\/\/ Description: The internal function to actually make all of the\n\/\/ appropriate windows calls to set the registry value.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\ndo_set(const string &key, const string &name,\n int data_type, const void *data, int data_length) {\n HKEY hkey;\n LONG error;\n\n error =\n RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_SET_VALUE, &hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.error()\n << \"Unable to open registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n return false;\n }\n\n bool okflag = true;\n\n error =\n RegSetValueEx(hkey, name.c_str(), 0, data_type, \n (CONST BYTE *)data, data_length);\n if (error != ERROR_SUCCESS) {\n express_cat.error()\n << \"Unable to set registry key \" << key << \" name \" << name \n << \": \" << format_message(error) << \"\\n\";\n okflag = false;\n }\n\n error = RegCloseKey(hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.warning()\n << \"Unable to close opened registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n }\n\n return okflag;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::do_get\n\/\/ Access: Private, Static\n\/\/ Description: The internal function to actually make all of the\n\/\/ appropriate windows calls to retrieve the registry\n\/\/ value.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\ndo_get(const string &key, const string &name, int &data_type, string &data) {\n HKEY hkey;\n LONG error;\n\n error =\n RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_QUERY_VALUE, &hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.debug()\n << \"Unable to open registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n return false;\n }\n\n bool okflag = true;\n\n \/\/ We start with a 1K buffer; presumably that will be big enough\n \/\/ most of the time.\n static const size_t init_buffer_size = 1024;\n char init_buffer[init_buffer_size];\n DWORD buffer_size = init_buffer_size;\n DWORD dw_data_type;\n\n error =\n RegQueryValueEx(hkey, name.c_str(), 0, &dw_data_type, \n (BYTE *)init_buffer, &buffer_size);\n if (error == ERROR_SUCCESS) {\n data_type = dw_data_type;\n if (data_type == REG_SZ || \n data_type == REG_MULTI_SZ || \n data_type == REG_EXPAND_SZ) {\n \/\/ Eliminate the trailing null character.\n buffer_size--;\n }\n data = string(init_buffer, buffer_size);\n\n } else if (error == ERROR_MORE_DATA) {\n \/\/ Huh, 1K wasn't big enough. Ok, get a bigger buffer.\n\n \/\/ If we were querying HKEY_PERFORMANCE_DATA, we'd have to keep\n \/\/ guessing bigger and bigger until we got it. Since we're\n \/\/ querying static data for now, we can just use the size Windows\n \/\/ tells us.\n char *new_buffer = new char[buffer_size];\n error =\n RegQueryValueEx(hkey, name.c_str(), 0, &dw_data_type, \n (BYTE *)new_buffer, &buffer_size);\n if (error == ERROR_SUCCESS) {\n data_type = dw_data_type;\n if (data_type == REG_SZ || \n data_type == REG_MULTI_SZ || \n data_type == REG_EXPAND_SZ) {\n \/\/ Eliminate the trailing null character.\n buffer_size--;\n }\n data = string(new_buffer, buffer_size);\n }\n delete new_buffer;\n }\n\n if (error != ERROR_SUCCESS) {\n express_cat.info()\n << \"Unable to get registry value \" << name \n << \": \" << format_message(error) << \"\\n\";\n okflag = false;\n }\n\n error = RegCloseKey(hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.warning()\n << \"Unable to close opened registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n }\n\n return okflag;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::format_message\n\/\/ Access: Private, Static\n\/\/ Description: Returns the Windows error message associated with the\n\/\/ given error code.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring WindowsRegistry::\nformat_message(int error_code) {\n LPTSTR buffer;\n DWORD length = \n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, error_code, 0, &buffer, 0, NULL);\n if (length == 0) {\n return \"Unknown error message\";\n }\n\n \/\/ Strip off \\n's and \\r's trailing the string.\n while (length > 0 && \n (buffer[length - 1] == '\\r' || buffer[length - 1] == '\\n')) {\n length--;\n }\n\n string result((const char *)buffer, length);\n LocalFree(buffer);\n return result;\n}\n\n#endif \/\/ WIN32_VC\ntrim extra newlines from windows error message\/\/ Filename: windowsRegistry.cxx\n\/\/ Created by: drose (06Aug01)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/www.panda3d.org\/license.txt .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d@yahoogroups.com .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"windowsRegistry.h\"\n#include \"config_express.h\"\n\n#ifdef WIN32_VC\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::set_string_value\n\/\/ Access: Published, Static\n\/\/ Description: Sets the registry key to the indicated value as a\n\/\/ string. The supplied string value is automatically\n\/\/ converted from whatever encoding is set by\n\/\/ TextEncoder::set_default_encoding() and written as a\n\/\/ Unicode string. The registry key must already exist\n\/\/ prior to calling this function.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\nset_string_value(const string &key, const string &name, const string &value) {\n TextEncoder encoder;\n wstring wvalue = encoder.decode_text(value);\n\n bool okflag = true;\n\n \/\/ Now convert the string to Windows' idea of the correct wide-char\n \/\/ encoding, so we can store it in the registry. This might well be\n \/\/ the same string we just decoded from, but it might not.\n\n \/\/ Windows likes to have a null character trailing the string (even\n \/\/ though we also pass a length).\n wvalue += (wchar_t)0;\n int mb_result_len =\n WideCharToMultiByte(CP_ACP, 0,\n wvalue.data(), wvalue.length(),\n NULL, 0,\n NULL, NULL);\n if (mb_result_len == 0) {\n express_cat.error()\n << \"Unable to convert '\" << value\n << \"' from Unicode to MultiByte form.\\n\";\n return false;\n }\n\n char *mb_result = (char *)alloca(mb_result_len);\n WideCharToMultiByte(CP_ACP, 0,\n wvalue.data(), wvalue.length(),\n mb_result, mb_result_len,\n NULL, NULL);\n\n if (express_cat.is_debug()) {\n express_cat.debug()\n << \"Converted '\" << value << \"' to '\" << mb_result\n << \"' for storing in registry.\\n\";\n }\n\n return do_set(key, name, REG_SZ, mb_result, mb_result_len);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::set_int_value\n\/\/ Access: Published, Static\n\/\/ Description: Sets the registry key to the indicated value as an\n\/\/ integer. The registry key must already exist prior\n\/\/ to calling this function.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\nset_int_value(const string &key, const string &name, int value) {\n DWORD dw = value;\n return do_set(key, name, REG_DWORD, &dw, sizeof(dw));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::get_key_type\n\/\/ Access: Published, Static\n\/\/ Description: Returns the type of the indicated key, or T_none if\n\/\/ the key is not known or is some unsupported type.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nWindowsRegistry::Type WindowsRegistry::\nget_key_type(const string &key, const string &name) {\n int data_type;\n string data;\n if (!do_get(key, name, data_type, data)) {\n return T_none;\n }\n\n switch (data_type) {\n case REG_SZ:\n return T_string;\n\n case REG_DWORD:\n return T_int;\n\n default:\n return T_none;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::get_string_value\n\/\/ Access: Published, Static\n\/\/ Description: Returns the value associated with the indicated\n\/\/ registry key, assuming it is a string value. The\n\/\/ string value is automatically encoded using\n\/\/ TextEncoder::get_default_encoding(). If the key is\n\/\/ not defined or is not a string type value,\n\/\/ default_value is returned instead.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring WindowsRegistry::\nget_string_value(const string &key, const string &name,\n const string &default_value) {\n int data_type;\n string data;\n if (!do_get(key, name, data_type, data)) {\n return default_value;\n }\n\n if (data_type != REG_SZ) {\n express_cat.warning()\n << \"Registry key \" << key << \" does not contain a string value.\\n\";\n return default_value;\n }\n\n \/\/ Now we have to decode the MultiByte string to Unicode, and re-encode\n \/\/ it according to our own encoding.\n\n if (data.empty()) {\n return data;\n }\n\n int wide_result_len =\n MultiByteToWideChar(CP_ACP, 0,\n data.data(), data.length(),\n NULL, 0);\n if (wide_result_len == 0) {\n express_cat.error()\n << \"Unable to convert '\" << data \n << \"' from MultiByte to Unicode form.\\n\";\n return data;\n }\n \n wchar_t *wide_result = (wchar_t *)alloca(wide_result_len * sizeof(wchar_t));\n MultiByteToWideChar(CP_ACP, 0,\n data.data(), data.length(),\n wide_result, wide_result_len);\n\n wstring wdata(wide_result, wide_result_len);\n\n TextEncoder encoder;\n string result = encoder.encode_wtext(wdata);\n\n if (express_cat.is_debug()) {\n express_cat.debug()\n << \"Converted '\" << data << \"' from registry to '\" << result << \"'\\n\";\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::get_int_value\n\/\/ Access: Published, Static\n\/\/ Description: Returns the value associated with the indicated\n\/\/ registry key, assuming it is an integer value. If\n\/\/ the key is not defined or is not an integer type\n\/\/ value, default_value is returned instead.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint WindowsRegistry::\nget_int_value(const string &key, const string &name, int default_value) {\n int data_type;\n string data;\n if (!do_get(key, name, data_type, data)) {\n return default_value;\n }\n\n if (data_type != REG_DWORD) {\n express_cat.warning()\n << \"Registry key \" << key << \" does not contain an integer value.\\n\";\n return default_value;\n }\n \n \/\/ Now we have a DWORD encoded in a string.\n nassertr(data.length() == sizeof(DWORD), default_value);\n DWORD dw = *(DWORD *)data.data();\n return dw;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::do_set\n\/\/ Access: Private, Static\n\/\/ Description: The internal function to actually make all of the\n\/\/ appropriate windows calls to set the registry value.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\ndo_set(const string &key, const string &name,\n int data_type, const void *data, int data_length) {\n HKEY hkey;\n LONG error;\n\n error =\n RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_SET_VALUE, &hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.error()\n << \"Unable to open registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n return false;\n }\n\n bool okflag = true;\n\n error =\n RegSetValueEx(hkey, name.c_str(), 0, data_type, \n (CONST BYTE *)data, data_length);\n if (error != ERROR_SUCCESS) {\n express_cat.error()\n << \"Unable to set registry key \" << key << \" name \" << name \n << \": \" << format_message(error) << \"\\n\";\n okflag = false;\n }\n\n error = RegCloseKey(hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.warning()\n << \"Unable to close opened registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n }\n\n return okflag;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::do_get\n\/\/ Access: Private, Static\n\/\/ Description: The internal function to actually make all of the\n\/\/ appropriate windows calls to retrieve the registry\n\/\/ value.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool WindowsRegistry::\ndo_get(const string &key, const string &name, int &data_type, string &data) {\n HKEY hkey;\n LONG error;\n\n error =\n RegOpenKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, KEY_QUERY_VALUE, &hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.debug()\n << \"Unable to open registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n return false;\n }\n\n bool okflag = true;\n\n \/\/ We start with a 1K buffer; presumably that will be big enough\n \/\/ most of the time.\n static const size_t init_buffer_size = 1024;\n char init_buffer[init_buffer_size];\n DWORD buffer_size = init_buffer_size;\n DWORD dw_data_type;\n\n error =\n RegQueryValueEx(hkey, name.c_str(), 0, &dw_data_type, \n (BYTE *)init_buffer, &buffer_size);\n if (error == ERROR_SUCCESS) {\n data_type = dw_data_type;\n if (data_type == REG_SZ || \n data_type == REG_MULTI_SZ || \n data_type == REG_EXPAND_SZ) {\n \/\/ Eliminate the trailing null character.\n buffer_size--;\n }\n data = string(init_buffer, buffer_size);\n\n } else if (error == ERROR_MORE_DATA) {\n \/\/ Huh, 1K wasn't big enough. Ok, get a bigger buffer.\n\n \/\/ If we were querying HKEY_PERFORMANCE_DATA, we'd have to keep\n \/\/ guessing bigger and bigger until we got it. Since we're\n \/\/ querying static data for now, we can just use the size Windows\n \/\/ tells us.\n char *new_buffer = new char[buffer_size];\n error =\n RegQueryValueEx(hkey, name.c_str(), 0, &dw_data_type, \n (BYTE *)new_buffer, &buffer_size);\n if (error == ERROR_SUCCESS) {\n data_type = dw_data_type;\n if (data_type == REG_SZ || \n data_type == REG_MULTI_SZ || \n data_type == REG_EXPAND_SZ) {\n \/\/ Eliminate the trailing null character.\n buffer_size--;\n }\n data = string(new_buffer, buffer_size);\n }\n delete new_buffer;\n }\n\n if (error != ERROR_SUCCESS) {\n express_cat.info()\n << \"Unable to get registry value \" << name \n << \": \" << format_message(error) << \"\\n\";\n okflag = false;\n }\n\n error = RegCloseKey(hkey);\n if (error != ERROR_SUCCESS) {\n express_cat.warning()\n << \"Unable to close opened registry key \" << key\n << \": \" << format_message(error) << \"\\n\";\n }\n\n return okflag;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: WindowsRegistry::format_message\n\/\/ Access: Private, Static\n\/\/ Description: Returns the Windows error message associated with the\n\/\/ given error code.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring WindowsRegistry::\nformat_message(int error_code) {\n PVOID buffer;\n DWORD length = \n FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL, error_code, 0, (LPTSTR)&buffer, 0, NULL);\n if (length == 0) {\n return \"Unknown error message\";\n }\n\n const char *text = (const char *)buffer;\n\n \/\/ Strip off \\n's and \\r's trailing the string.\n while (length > 0 && \n (text[length - 1] == '\\r' || text[length - 1] == '\\n')) {\n length--;\n }\n\n string result((const char *)text, length);\n LocalFree(buffer);\n return result;\n}\n\n#endif \/\/ WIN32_VC\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace vespalib;\n\nTEST(VisitRangeExample, set_intersection) {\n std::vector first({1,3,7});\n std::vector second({2,3,8});\n std::vector result;\n vespalib::visit_ranges(overload{[](visit_ranges_either, int) {},\n [&result](visit_ranges_both, int x, int) { result.push_back(x); }},\n first.begin(), first.end(), second.begin(), second.end());\n EXPECT_EQ(result, std::vector({3}));\n}\n\nTEST(VisitRangeExample, set_subtraction) {\n std::vector first({1,3,7});\n std::vector second({2,3,8});\n std::vector result;\n vespalib::visit_ranges(overload{[&result](visit_ranges_first, int a) { result.push_back(a); },\n [](visit_ranges_second, int) {},\n [](visit_ranges_both, int, int) {}},\n first.begin(), first.end(), second.begin(), second.end());\n EXPECT_EQ(result, std::vector({1,7}));\n}\n\nTEST(VisitRangesTest, empty_ranges_can_be_visited) {\n std::vector a;\n std::vector b;\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int) {\n c.push_back(42);\n },\n [&c](visit_ranges_both, int, int) {\n c.push_back(42);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({}));\n}\n\nTEST(VisitRangesTest, simple_merge_can_be_implemented) {\n std::vector a({1,3,7});\n std::vector b({2,3,8});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_both, int x, int y) {\n c.push_back(x);\n c.push_back(y);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({1,2,3,3,7,8}));\n}\n\nTEST(VisitRangesTest, simple_union_can_be_implemented) {\n std::vector a({1,3,7});\n std::vector b({2,3,8});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_both, int x, int) {\n c.push_back(x);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({1,2,3,7,8}));\n}\n\nTEST(VisitRangesTest, asymmetric_merge_can_be_implemented) {\n std::vector a({1,3,7});\n std::vector b({2,3,8});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_first, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_second, int) {},\n [&c](visit_ranges_both, int x, int y) {\n c.push_back(x * y);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({1,9,7}));\n}\n\nTEST(VisitRangesTest, comparator_can_be_specified) {\n std::vector a({7,3,1});\n std::vector b({8,3,2});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_both, int x, int y) {\n c.push_back(x);\n c.push_back(y);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end(), std::greater<>());\n EXPECT_EQ(c, std::vector({8,7,3,3,2,1}));\n}\n\nGTEST_MAIN_RUN_ALL_TESTS()\nRemove unused lambda capture.\/\/ Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace vespalib;\n\nTEST(VisitRangeExample, set_intersection) {\n std::vector first({1,3,7});\n std::vector second({2,3,8});\n std::vector result;\n vespalib::visit_ranges(overload{[](visit_ranges_either, int) {},\n [&result](visit_ranges_both, int x, int) { result.push_back(x); }},\n first.begin(), first.end(), second.begin(), second.end());\n EXPECT_EQ(result, std::vector({3}));\n}\n\nTEST(VisitRangeExample, set_subtraction) {\n std::vector first({1,3,7});\n std::vector second({2,3,8});\n std::vector result;\n vespalib::visit_ranges(overload{[&result](visit_ranges_first, int a) { result.push_back(a); },\n [](visit_ranges_second, int) {},\n [](visit_ranges_both, int, int) {}},\n first.begin(), first.end(), second.begin(), second.end());\n EXPECT_EQ(result, std::vector({1,7}));\n}\n\nTEST(VisitRangesTest, empty_ranges_can_be_visited) {\n std::vector a;\n std::vector b;\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int) {\n c.push_back(42);\n },\n [&c](visit_ranges_both, int, int) {\n c.push_back(42);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({}));\n}\n\nTEST(VisitRangesTest, simple_merge_can_be_implemented) {\n std::vector a({1,3,7});\n std::vector b({2,3,8});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_both, int x, int y) {\n c.push_back(x);\n c.push_back(y);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({1,2,3,3,7,8}));\n}\n\nTEST(VisitRangesTest, simple_union_can_be_implemented) {\n std::vector a({1,3,7});\n std::vector b({2,3,8});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_both, int x, int) {\n c.push_back(x);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({1,2,3,7,8}));\n}\n\nTEST(VisitRangesTest, asymmetric_merge_can_be_implemented) {\n std::vector a({1,3,7});\n std::vector b({2,3,8});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_first, int x) {\n c.push_back(x);\n },\n [](visit_ranges_second, int) {},\n [&c](visit_ranges_both, int x, int y) {\n c.push_back(x * y);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end());\n EXPECT_EQ(c, std::vector({1,9,7}));\n}\n\nTEST(VisitRangesTest, comparator_can_be_specified) {\n std::vector a({7,3,1});\n std::vector b({8,3,2});\n std::vector c;\n auto visitor = overload\n {\n [&c](visit_ranges_either, int x) {\n c.push_back(x);\n },\n [&c](visit_ranges_both, int x, int y) {\n c.push_back(x);\n c.push_back(y);\n }\n };\n vespalib::visit_ranges(visitor, a.begin(), a.end(), b.begin(), b.end(), std::greater<>());\n EXPECT_EQ(c, std::vector({8,7,3,3,2,1}));\n}\n\nGTEST_MAIN_RUN_ALL_TESTS()\n<|endoftext|>"} {"text":"remove debug assert that is not 100% correct and can fail in some models<|endoftext|>"} {"text":"updates to render correctly<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"modules\/serviceworkers\/InspectorServiceWorkerCacheAgent.h\"\n\n#include \"core\/InspectorBackendDispatcher.h\"\n#include \"core\/InspectorTypeBuilder.h\"\n#include \"modules\/serviceworkers\/ServiceWorkerGlobalScope.h\"\n#include \"modules\/serviceworkers\/ServiceWorkerGlobalScopeClient.h\"\n#include \"platform\/JSONValues.h\"\n#include \"platform\/heap\/Handle.h\"\n#include \"public\/platform\/WebServiceWorkerCache.h\"\n#include \"public\/platform\/WebServiceWorkerCacheError.h\"\n#include \"public\/platform\/WebServiceWorkerCacheStorage.h\"\n#include \"public\/platform\/WebServiceWorkerRequest.h\"\n#include \"public\/platform\/WebServiceWorkerResponse.h\"\n#include \"public\/platform\/WebString.h\"\n#include \"public\/platform\/WebURL.h\"\n#include \"public\/platform\/WebVector.h\"\n#include \"wtf\/Noncopyable.h\"\n#include \"wtf\/OwnPtr.h\"\n#include \"wtf\/PassRefPtr.h\"\n#include \"wtf\/RefCounted.h\"\n#include \"wtf\/RefPtr.h\"\n#include \"wtf\/Vector.h\"\n#include \"wtf\/text\/StringBuilder.h\"\n\n#include \n\nusing blink::TypeBuilder::Array;\nusing blink::TypeBuilder::ServiceWorkerCache::DataEntry;\n\ntypedef blink::InspectorBackendDispatcher::ServiceWorkerCacheCommandHandler::DeleteCacheCallback DeleteCacheCallback;\ntypedef blink::InspectorBackendDispatcher::ServiceWorkerCacheCommandHandler::RequestCacheNamesCallback RequestCacheNamesCallback;\ntypedef blink::InspectorBackendDispatcher::ServiceWorkerCacheCommandHandler::RequestEntriesCallback RequestEntriesCallback;\ntypedef blink::InspectorBackendDispatcher::CallbackBase RequestCallback;\n\nnamespace blink {\n\nnamespace {\n\nWebServiceWorkerCacheStorage* assertCacheStorage(ErrorString* errorString, ServiceWorkerGlobalScope* globalScope)\n{\n ServiceWorkerGlobalScopeClient* client = ServiceWorkerGlobalScopeClient::from(globalScope);\n if (!client) {\n *errorString = \"Could not find service worker global scope.\";\n return nullptr;\n }\n WebServiceWorkerCacheStorage* cache = client->cacheStorage();\n if (!cache) {\n *errorString = \"Cache not available on service worker global client.\";\n return nullptr;\n }\n return cache;\n}\n\nCString serviceWorkerCacheErrorString(WebServiceWorkerCacheError* error)\n{\n switch (*error) {\n case WebServiceWorkerCacheErrorNotImplemented:\n return CString(\"not implemented.\");\n break;\n case WebServiceWorkerCacheErrorNotFound:\n return CString(\"not found.\");\n break;\n case WebServiceWorkerCacheErrorExists:\n return CString(\"cache already exists.\");\n break;\n default:\n return CString(\"unknown error.\");\n break;\n }\n}\n\nclass RequestCacheNames\n : public WebServiceWorkerCacheStorage::CacheStorageKeysCallbacks {\n WTF_MAKE_NONCOPYABLE(RequestCacheNames);\n\npublic:\n RequestCacheNames(PassRefPtr callback)\n : m_callback(callback)\n {\n }\n\n virtual ~RequestCacheNames() { }\n\n void onSuccess(WebVector* caches)\n {\n RefPtr> array = TypeBuilder::Array::create();\n for (size_t i = 0; i < caches->size(); i++) {\n array->addItem(String((*caches)[i]));\n }\n m_callback->sendSuccess(array);\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting cache names: %s\", serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n RefPtr m_callback;\n};\n\nstruct DataRequestParams {\n String cacheName;\n int skipCount;\n int pageSize;\n};\n\nstruct RequestResponse {\n RequestResponse() { }\n RequestResponse(const String& request, const String& response)\n : request(request)\n , response(response)\n {\n }\n String request;\n String response;\n};\n\nclass ResponsesAccumulator : public RefCounted {\n WTF_MAKE_NONCOPYABLE(ResponsesAccumulator);\n\npublic:\n ResponsesAccumulator(int numResponses, const DataRequestParams& params, PassRefPtr callback)\n : m_params(params)\n , m_numResponsesLeft(numResponses)\n , m_responses(static_cast(numResponses))\n , m_callback(callback)\n {\n }\n\n void addRequestResponsePair(const WebServiceWorkerRequest& request, const WebServiceWorkerResponse& response)\n {\n ASSERT(m_numResponsesLeft > 0);\n RequestResponse& requestResponse = m_responses.at(m_responses.size() - m_numResponsesLeft);\n requestResponse.request = request.url().string();\n requestResponse.response = response.statusText();\n\n if (--m_numResponsesLeft != 0)\n return;\n\n std::sort(m_responses.begin(), m_responses.end(),\n [](const RequestResponse& a, const RequestResponse& b)\n {\n return WTF::codePointCompareLessThan(a.request, b.request);\n });\n if (m_params.skipCount > 0)\n m_responses.remove(0, m_params.skipCount);\n bool hasMore = false;\n if (static_cast(m_params.pageSize) < m_responses.size()) {\n m_responses.remove(m_params.pageSize, m_responses.size() - m_params.pageSize);\n hasMore = true;\n }\n RefPtr> array = TypeBuilder::Array::create();\n for (const auto& requestResponse : m_responses) {\n RefPtr entry = DataEntry::create()\n .setRequest(JSONString::create(requestResponse.request)->toJSONString())\n .setResponse(JSONString::create(requestResponse.response)->toJSONString());\n array->addItem(entry);\n }\n m_callback->sendSuccess(array, hasMore);\n }\n\nprivate:\n DataRequestParams m_params;\n int m_numResponsesLeft;\n Vector m_responses;\n RefPtr m_callback;\n};\n\nclass GetCacheResponsesForRequestData : public WebServiceWorkerCache::CacheMatchCallbacks {\n WTF_MAKE_NONCOPYABLE(GetCacheResponsesForRequestData);\n\npublic:\n GetCacheResponsesForRequestData(\n const DataRequestParams& params, const WebServiceWorkerRequest& request,\n PassRefPtr accum, PassRefPtr callback)\n : m_params(params)\n , m_request(request)\n , m_accumulator(accum)\n , m_callback(callback)\n {\n }\n virtual ~GetCacheResponsesForRequestData() { }\n\n void onSuccess(WebServiceWorkerResponse* response)\n {\n m_accumulator->addRequestResponsePair(m_request, *response);\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting responses for cache %s: %s\", m_params.cacheName.utf8().data(), serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n DataRequestParams m_params;\n WebServiceWorkerRequest m_request;\n RefPtr m_accumulator;\n RefPtr m_callback;\n};\n\nclass GetCacheKeysForRequestData : public WebServiceWorkerCache::CacheWithRequestsCallbacks {\n WTF_MAKE_NONCOPYABLE(GetCacheKeysForRequestData);\n\npublic:\n GetCacheKeysForRequestData(const DataRequestParams& params, PassOwnPtr cache, PassRefPtr callback)\n : m_params(params)\n , m_cache(cache)\n , m_callback(callback)\n {\n }\n virtual ~GetCacheKeysForRequestData() { }\n\n void onSuccess(WebVector* requests)\n {\n RefPtr accumulator = adoptRef(new ResponsesAccumulator(requests->size(), m_params, m_callback));\n\n for (size_t i = 0; i < requests->size(); i++) {\n const auto& request = (*requests)[i];\n auto* cacheRequest = new GetCacheResponsesForRequestData(m_params, request, accumulator, m_callback);\n m_cache->dispatchMatch(cacheRequest, request, WebServiceWorkerCache::QueryParams());\n }\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting requests for cache %s: %s\", m_params.cacheName.utf8().data(), serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n DataRequestParams m_params;\n OwnPtr m_cache;\n RefPtr m_callback;\n};\n\nclass GetCacheForRequestData\n : public WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks {\n WTF_MAKE_NONCOPYABLE(GetCacheForRequestData);\n\npublic:\n GetCacheForRequestData(const DataRequestParams& params, PassRefPtr callback)\n : m_params(params)\n , m_callback(callback)\n {\n }\n virtual ~GetCacheForRequestData() { }\n\n void onSuccess(WebServiceWorkerCache* cache)\n {\n auto* cacheRequest = new GetCacheKeysForRequestData(m_params, adoptPtr(cache), m_callback);\n cache->dispatchKeys(cacheRequest, nullptr, WebServiceWorkerCache::QueryParams());\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting cache %s: %s\", m_params.cacheName.utf8().data(), serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n DataRequestParams m_params;\n RefPtr m_callback;\n};\n\nclass DeleteCache : public WebServiceWorkerCacheStorage::CacheStorageCallbacks {\n WTF_MAKE_NONCOPYABLE(DeleteCache);\n\npublic:\n DeleteCache(PassRefPtr callback)\n : m_callback(callback)\n {\n }\n virtual ~DeleteCache() { }\n\n void onSuccess()\n {\n m_callback->sendSuccess();\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting cache names: %s\", serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n RefPtr m_callback;\n};\n\n} \/\/ namespace\n\nInspectorServiceWorkerCacheAgent::InspectorServiceWorkerCacheAgent(ServiceWorkerGlobalScope* scope)\n : InspectorBaseAgent(\"ServiceWorkerCache\")\n , m_globalScope(scope)\n{\n}\n\nInspectorServiceWorkerCacheAgent::~InspectorServiceWorkerCacheAgent() { }\n\nvoid InspectorServiceWorkerCacheAgent::trace(Visitor* visitor)\n{\n InspectorBaseAgent::trace(visitor);\n}\n\nvoid InspectorServiceWorkerCacheAgent::clearFrontend() { }\nvoid InspectorServiceWorkerCacheAgent::restore() { }\n\nvoid InspectorServiceWorkerCacheAgent::requestCacheNames(ErrorString* errorString, PassRefPtrWillBeRawPtr callback)\n{\n WebServiceWorkerCacheStorage* cache = assertCacheStorage(errorString, m_globalScope);\n if (!cache) {\n callback->sendFailure(*errorString);\n return;\n }\n cache->dispatchKeys(new RequestCacheNames(callback));\n}\n\n\nvoid InspectorServiceWorkerCacheAgent::requestEntries(ErrorString* errorString, const String& cacheName, int skipCount, int pageSize, PassRefPtrWillBeRawPtr callback)\n{\n WebServiceWorkerCacheStorage* cache = assertCacheStorage(errorString, m_globalScope);\n if (!cache) {\n callback->sendFailure(*errorString);\n return;\n }\n DataRequestParams params;\n params.cacheName = cacheName;\n params.pageSize = pageSize;\n params.skipCount = skipCount;\n cache->dispatchOpen(new GetCacheForRequestData(params, callback), WebString(cacheName));\n}\n\nvoid InspectorServiceWorkerCacheAgent::deleteCache(ErrorString* errorString, const String& cacheName, PassRefPtrWillBeRawPtr callback)\n{\n WebServiceWorkerCacheStorage* cache = assertCacheStorage(errorString, m_globalScope);\n if (!cache) {\n callback->sendFailure(*errorString);\n return;\n }\n cache->dispatchDelete(new DeleteCache(callback), WebString(cacheName));\n}\n\n} \/\/ namespace blink\nOilpan: fix build after r186900.\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"modules\/serviceworkers\/InspectorServiceWorkerCacheAgent.h\"\n\n#include \"core\/InspectorBackendDispatcher.h\"\n#include \"core\/InspectorTypeBuilder.h\"\n#include \"modules\/serviceworkers\/ServiceWorkerGlobalScope.h\"\n#include \"modules\/serviceworkers\/ServiceWorkerGlobalScopeClient.h\"\n#include \"platform\/JSONValues.h\"\n#include \"platform\/heap\/Handle.h\"\n#include \"public\/platform\/WebServiceWorkerCache.h\"\n#include \"public\/platform\/WebServiceWorkerCacheError.h\"\n#include \"public\/platform\/WebServiceWorkerCacheStorage.h\"\n#include \"public\/platform\/WebServiceWorkerRequest.h\"\n#include \"public\/platform\/WebServiceWorkerResponse.h\"\n#include \"public\/platform\/WebString.h\"\n#include \"public\/platform\/WebURL.h\"\n#include \"public\/platform\/WebVector.h\"\n#include \"wtf\/Noncopyable.h\"\n#include \"wtf\/OwnPtr.h\"\n#include \"wtf\/PassRefPtr.h\"\n#include \"wtf\/RefCounted.h\"\n#include \"wtf\/RefPtr.h\"\n#include \"wtf\/Vector.h\"\n#include \"wtf\/text\/StringBuilder.h\"\n\n#include \n\nusing blink::TypeBuilder::Array;\nusing blink::TypeBuilder::ServiceWorkerCache::DataEntry;\n\ntypedef blink::InspectorBackendDispatcher::ServiceWorkerCacheCommandHandler::DeleteCacheCallback DeleteCacheCallback;\ntypedef blink::InspectorBackendDispatcher::ServiceWorkerCacheCommandHandler::RequestCacheNamesCallback RequestCacheNamesCallback;\ntypedef blink::InspectorBackendDispatcher::ServiceWorkerCacheCommandHandler::RequestEntriesCallback RequestEntriesCallback;\ntypedef blink::InspectorBackendDispatcher::CallbackBase RequestCallback;\n\nnamespace blink {\n\nnamespace {\n\nWebServiceWorkerCacheStorage* assertCacheStorage(ErrorString* errorString, ServiceWorkerGlobalScope* globalScope)\n{\n ServiceWorkerGlobalScopeClient* client = ServiceWorkerGlobalScopeClient::from(globalScope);\n if (!client) {\n *errorString = \"Could not find service worker global scope.\";\n return nullptr;\n }\n WebServiceWorkerCacheStorage* cache = client->cacheStorage();\n if (!cache) {\n *errorString = \"Cache not available on service worker global client.\";\n return nullptr;\n }\n return cache;\n}\n\nCString serviceWorkerCacheErrorString(WebServiceWorkerCacheError* error)\n{\n switch (*error) {\n case WebServiceWorkerCacheErrorNotImplemented:\n return CString(\"not implemented.\");\n break;\n case WebServiceWorkerCacheErrorNotFound:\n return CString(\"not found.\");\n break;\n case WebServiceWorkerCacheErrorExists:\n return CString(\"cache already exists.\");\n break;\n default:\n return CString(\"unknown error.\");\n break;\n }\n}\n\nclass RequestCacheNames\n : public WebServiceWorkerCacheStorage::CacheStorageKeysCallbacks {\n WTF_MAKE_NONCOPYABLE(RequestCacheNames);\n\npublic:\n RequestCacheNames(PassRefPtrWillBeRawPtr callback)\n : m_callback(callback)\n {\n }\n\n virtual ~RequestCacheNames() { }\n\n void onSuccess(WebVector* caches)\n {\n RefPtr> array = TypeBuilder::Array::create();\n for (size_t i = 0; i < caches->size(); i++) {\n array->addItem(String((*caches)[i]));\n }\n m_callback->sendSuccess(array);\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting cache names: %s\", serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n RefPtrWillBePersistent m_callback;\n};\n\nstruct DataRequestParams {\n String cacheName;\n int skipCount;\n int pageSize;\n};\n\nstruct RequestResponse {\n RequestResponse() { }\n RequestResponse(const String& request, const String& response)\n : request(request)\n , response(response)\n {\n }\n String request;\n String response;\n};\n\nclass ResponsesAccumulator : public RefCounted {\n WTF_MAKE_NONCOPYABLE(ResponsesAccumulator);\n\npublic:\n ResponsesAccumulator(int numResponses, const DataRequestParams& params, PassRefPtrWillBeRawPtr callback)\n : m_params(params)\n , m_numResponsesLeft(numResponses)\n , m_responses(static_cast(numResponses))\n , m_callback(callback)\n {\n }\n\n void addRequestResponsePair(const WebServiceWorkerRequest& request, const WebServiceWorkerResponse& response)\n {\n ASSERT(m_numResponsesLeft > 0);\n RequestResponse& requestResponse = m_responses.at(m_responses.size() - m_numResponsesLeft);\n requestResponse.request = request.url().string();\n requestResponse.response = response.statusText();\n\n if (--m_numResponsesLeft != 0)\n return;\n\n std::sort(m_responses.begin(), m_responses.end(),\n [](const RequestResponse& a, const RequestResponse& b)\n {\n return WTF::codePointCompareLessThan(a.request, b.request);\n });\n if (m_params.skipCount > 0)\n m_responses.remove(0, m_params.skipCount);\n bool hasMore = false;\n if (static_cast(m_params.pageSize) < m_responses.size()) {\n m_responses.remove(m_params.pageSize, m_responses.size() - m_params.pageSize);\n hasMore = true;\n }\n RefPtr> array = TypeBuilder::Array::create();\n for (const auto& requestResponse : m_responses) {\n RefPtr entry = DataEntry::create()\n .setRequest(JSONString::create(requestResponse.request)->toJSONString())\n .setResponse(JSONString::create(requestResponse.response)->toJSONString());\n array->addItem(entry);\n }\n m_callback->sendSuccess(array, hasMore);\n }\n\nprivate:\n DataRequestParams m_params;\n int m_numResponsesLeft;\n Vector m_responses;\n RefPtrWillBePersistent m_callback;\n};\n\nclass GetCacheResponsesForRequestData : public WebServiceWorkerCache::CacheMatchCallbacks {\n WTF_MAKE_NONCOPYABLE(GetCacheResponsesForRequestData);\n\npublic:\n GetCacheResponsesForRequestData(\n const DataRequestParams& params, const WebServiceWorkerRequest& request,\n PassRefPtr accum, PassRefPtrWillBeRawPtr callback)\n : m_params(params)\n , m_request(request)\n , m_accumulator(accum)\n , m_callback(callback)\n {\n }\n virtual ~GetCacheResponsesForRequestData() { }\n\n void onSuccess(WebServiceWorkerResponse* response)\n {\n m_accumulator->addRequestResponsePair(m_request, *response);\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting responses for cache %s: %s\", m_params.cacheName.utf8().data(), serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n DataRequestParams m_params;\n WebServiceWorkerRequest m_request;\n RefPtr m_accumulator;\n RefPtrWillBePersistent m_callback;\n};\n\nclass GetCacheKeysForRequestData : public WebServiceWorkerCache::CacheWithRequestsCallbacks {\n WTF_MAKE_NONCOPYABLE(GetCacheKeysForRequestData);\n\npublic:\n GetCacheKeysForRequestData(const DataRequestParams& params, PassOwnPtr cache, PassRefPtrWillBeRawPtr callback)\n : m_params(params)\n , m_cache(cache)\n , m_callback(callback)\n {\n }\n virtual ~GetCacheKeysForRequestData() { }\n\n void onSuccess(WebVector* requests)\n {\n RefPtr accumulator = adoptRef(new ResponsesAccumulator(requests->size(), m_params, m_callback));\n\n for (size_t i = 0; i < requests->size(); i++) {\n const auto& request = (*requests)[i];\n auto* cacheRequest = new GetCacheResponsesForRequestData(m_params, request, accumulator, m_callback);\n m_cache->dispatchMatch(cacheRequest, request, WebServiceWorkerCache::QueryParams());\n }\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting requests for cache %s: %s\", m_params.cacheName.utf8().data(), serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n DataRequestParams m_params;\n OwnPtr m_cache;\n RefPtrWillBePersistent m_callback;\n};\n\nclass GetCacheForRequestData\n : public WebServiceWorkerCacheStorage::CacheStorageWithCacheCallbacks {\n WTF_MAKE_NONCOPYABLE(GetCacheForRequestData);\n\npublic:\n GetCacheForRequestData(const DataRequestParams& params, PassRefPtrWillBeRawPtr callback)\n : m_params(params)\n , m_callback(callback)\n {\n }\n virtual ~GetCacheForRequestData() { }\n\n void onSuccess(WebServiceWorkerCache* cache)\n {\n auto* cacheRequest = new GetCacheKeysForRequestData(m_params, adoptPtr(cache), m_callback);\n cache->dispatchKeys(cacheRequest, nullptr, WebServiceWorkerCache::QueryParams());\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting cache %s: %s\", m_params.cacheName.utf8().data(), serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n DataRequestParams m_params;\n RefPtrWillBePersistent m_callback;\n};\n\nclass DeleteCache : public WebServiceWorkerCacheStorage::CacheStorageCallbacks {\n WTF_MAKE_NONCOPYABLE(DeleteCache);\n\npublic:\n DeleteCache(PassRefPtrWillBeRawPtr callback)\n : m_callback(callback)\n {\n }\n virtual ~DeleteCache() { }\n\n void onSuccess()\n {\n m_callback->sendSuccess();\n }\n\n void onError(WebServiceWorkerCacheError* error)\n {\n m_callback->sendFailure(String::format(\"Error requesting cache names: %s\", serviceWorkerCacheErrorString(error).data()));\n }\n\nprivate:\n RefPtrWillBePersistent m_callback;\n};\n\n} \/\/ namespace\n\nInspectorServiceWorkerCacheAgent::InspectorServiceWorkerCacheAgent(ServiceWorkerGlobalScope* scope)\n : InspectorBaseAgent(\"ServiceWorkerCache\")\n , m_globalScope(scope)\n{\n}\n\nInspectorServiceWorkerCacheAgent::~InspectorServiceWorkerCacheAgent() { }\n\nvoid InspectorServiceWorkerCacheAgent::trace(Visitor* visitor)\n{\n InspectorBaseAgent::trace(visitor);\n}\n\nvoid InspectorServiceWorkerCacheAgent::clearFrontend() { }\nvoid InspectorServiceWorkerCacheAgent::restore() { }\n\nvoid InspectorServiceWorkerCacheAgent::requestCacheNames(ErrorString* errorString, PassRefPtrWillBeRawPtr callback)\n{\n WebServiceWorkerCacheStorage* cache = assertCacheStorage(errorString, m_globalScope);\n if (!cache) {\n callback->sendFailure(*errorString);\n return;\n }\n cache->dispatchKeys(new RequestCacheNames(callback));\n}\n\n\nvoid InspectorServiceWorkerCacheAgent::requestEntries(ErrorString* errorString, const String& cacheName, int skipCount, int pageSize, PassRefPtrWillBeRawPtr callback)\n{\n WebServiceWorkerCacheStorage* cache = assertCacheStorage(errorString, m_globalScope);\n if (!cache) {\n callback->sendFailure(*errorString);\n return;\n }\n DataRequestParams params;\n params.cacheName = cacheName;\n params.pageSize = pageSize;\n params.skipCount = skipCount;\n cache->dispatchOpen(new GetCacheForRequestData(params, callback), WebString(cacheName));\n}\n\nvoid InspectorServiceWorkerCacheAgent::deleteCache(ErrorString* errorString, const String& cacheName, PassRefPtrWillBeRawPtr callback)\n{\n WebServiceWorkerCacheStorage* cache = assertCacheStorage(errorString, m_globalScope);\n if (!cache) {\n callback->sendFailure(*errorString);\n return;\n }\n cache->dispatchDelete(new DeleteCache(callback), WebString(cacheName));\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"X87: EmitCreateIteratorResult loads map from function's context<|endoftext|>"} {"text":"\/*\n Copyright (C) 2000 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n \n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csgeom\/math3d.h\"\n#include \"csutil\/parser.h\"\n#include \"csutil\/scanstr.h\"\n#include \"csutil\/cscolor.h\"\n#include \"ballldr.h\"\n#include \"imesh\/imeshobj.h\"\n#include \"iengine\/imeshobj.h\"\n#include \"iengine\/iengine.h\"\n#include \"isys\/isystem.h\"\n#include \"imesh\/imball.h\"\n#include \"ivideo\/igraph3d.h\"\n#include \"qint.h\"\n#include \"iutil\/istrvec.h\"\n#include \"csutil\/util.h\"\n#include \"iobject\/iobject.h\"\n#include \"iengine\/imater.h\"\n#include \"csengine\/material.h\"\n#include \"iengine\/imovable.h\"\n\nCS_TOKEN_DEF_START\n CS_TOKEN_DEF (ADD)\n CS_TOKEN_DEF (ALPHA)\n CS_TOKEN_DEF (COPY)\n CS_TOKEN_DEF (KEYCOLOR)\n CS_TOKEN_DEF (MULTIPLY2)\n CS_TOKEN_DEF (MULTIPLY)\n CS_TOKEN_DEF (TRANSPARENT)\n\n CS_TOKEN_DEF (NUMRIM)\n CS_TOKEN_DEF (MATERIAL)\n CS_TOKEN_DEF (FACTORY)\n CS_TOKEN_DEF (MIXMODE)\n CS_TOKEN_DEF (RADIUS)\n CS_TOKEN_DEF (SHIFT)\nCS_TOKEN_DEF_END\n\nIMPLEMENT_IBASE (csBallFactoryLoader)\n IMPLEMENTS_INTERFACE (iLoaderPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_IBASE (csBallFactorySaver)\n IMPLEMENTS_INTERFACE (iSaverPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_IBASE (csBallLoader)\n IMPLEMENTS_INTERFACE (iLoaderPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_IBASE (csBallSaver)\n IMPLEMENTS_INTERFACE (iSaverPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_FACTORY (csBallFactoryLoader)\nIMPLEMENT_FACTORY (csBallFactorySaver)\nIMPLEMENT_FACTORY (csBallLoader)\nIMPLEMENT_FACTORY (csBallSaver)\n\nEXPORT_CLASS_TABLE (ballldr)\n EXPORT_CLASS (csBallFactoryLoader, \"crystalspace.mesh.loader.factory.ball\",\n \"Crystal Space Ball Factory Loader\")\n EXPORT_CLASS (csBallFactorySaver, \"crystalspace.mesh.saver.factory.ball\",\n \"Crystal Space Ball Factory Saver\")\n EXPORT_CLASS (csBallLoader, \"crystalspace.mesh.loader.ball\",\n \"Crystal Space Ball Mesh Loader\")\n EXPORT_CLASS (csBallSaver, \"crystalspace.mesh.saver.ball\",\n \"Crystal Space Ball Mesh Saver\")\nEXPORT_CLASS_TABLE_END\n\ncsBallFactoryLoader::csBallFactoryLoader (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallFactoryLoader::~csBallFactoryLoader ()\n{\n}\n\nbool csBallFactoryLoader::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\niBase* csBallFactoryLoader::Parse (const char* \/*string*\/, iEngine* \/*engine*\/)\n{\n iMeshObjectType* type = QUERY_PLUGIN_CLASS (sys, \"crystalspace.mesh.object.ball\", \"MeshObj\", iMeshObjectType);\n if (!type)\n {\n type = LOAD_PLUGIN (sys, \"crystalspace.mesh.object.ball\", \"MeshObj\", iMeshObjectType);\n printf (\"Load TYPE plugin crystalspace.mesh.object.ball\\n\");\n }\n iMeshObjectFactory* fact = type->NewFactory ();\n type->DecRef ();\n return fact;\n}\n\n\/\/---------------------------------------------------------------------------\n\ncsBallFactorySaver::csBallFactorySaver (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallFactorySaver::~csBallFactorySaver ()\n{\n}\n\nbool csBallFactorySaver::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\n#define MAXLINE 100 \/* max number of chars per line... *\/\n\nvoid csBallFactorySaver::WriteDown (iBase* obj, iStrVector *str,\n iEngine* \/*engine*\/)\n{\n iFactory *fact = QUERY_INTERFACE (this, iFactory);\n char buf[MAXLINE];\n char name[MAXLINE];\n csFindReplace(name, fact->QueryDescription (), \"Saver\", \"Loader\", MAXLINE);\n sprintf(buf, \"MESHOBJ '%s' (\\n\", name);\n str->Push(strnew(buf));\n csFindReplace(name, fact->QueryClassID (), \"saver\", \"loader\", MAXLINE);\n sprintf(buf, \" PLUGIN ('%s')\\n\", name);\n str->Push(strnew(buf));\n str->Push(strnew(\" PARAMS ()\\n\"));\n str->Push(strnew(\")\\n\"));\n fact->DecRef();\n}\n\n\/\/---------------------------------------------------------------------------\n\ncsBallLoader::csBallLoader (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallLoader::~csBallLoader ()\n{\n}\n\nbool csBallLoader::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\nstatic UInt ParseMixmode (char* buf)\n{\n CS_TOKEN_TABLE_START (modes)\n CS_TOKEN_TABLE (COPY)\n CS_TOKEN_TABLE (MULTIPLY2)\n CS_TOKEN_TABLE (MULTIPLY)\n CS_TOKEN_TABLE (ADD)\n CS_TOKEN_TABLE (ALPHA)\n CS_TOKEN_TABLE (TRANSPARENT)\n CS_TOKEN_TABLE (KEYCOLOR)\n CS_TOKEN_TABLE_END\n\n char* name;\n long cmd;\n char* params;\n\n UInt Mixmode = 0;\n\n while ((cmd = csGetObject (&buf, modes, &name, ¶ms)) > 0)\n {\n if (!params)\n {\n printf (\"Expected parameters instead of '%s'!\\n\", buf);\n return 0;\n }\n switch (cmd)\n {\n case CS_TOKEN_COPY: Mixmode |= CS_FX_COPY; break;\n case CS_TOKEN_MULTIPLY: Mixmode |= CS_FX_MULTIPLY; break;\n case CS_TOKEN_MULTIPLY2: Mixmode |= CS_FX_MULTIPLY2; break;\n case CS_TOKEN_ADD: Mixmode |= CS_FX_ADD; break;\n case CS_TOKEN_ALPHA:\n\tMixmode &= ~CS_FX_MASK_ALPHA;\n\tfloat alpha;\n\tint ialpha;\n ScanStr (params, \"%f\", &alpha);\n\tialpha = QInt (alpha * 255.99);\n\tMixmode |= CS_FX_SETALPHA(ialpha);\n\tbreak;\n case CS_TOKEN_TRANSPARENT: Mixmode |= CS_FX_TRANSPARENT; break;\n case CS_TOKEN_KEYCOLOR: Mixmode |= CS_FX_KEYCOLOR; break;\n }\n }\n if (cmd == CS_PARSERR_TOKENNOTFOUND)\n {\n printf (\"Token '%s' not found while parsing the modes!\\n\", csGetLastOffender ());\n return 0;\n }\n return Mixmode;\n}\n\niBase* csBallLoader::Parse (const char* string, iEngine* engine)\n{\n CS_TOKEN_TABLE_START (commands)\n CS_TOKEN_TABLE (MATERIAL)\n CS_TOKEN_TABLE (FACTORY)\n CS_TOKEN_TABLE (NUMRIM)\n CS_TOKEN_TABLE (RADIUS)\n CS_TOKEN_TABLE (SHIFT)\n CS_TOKEN_TABLE (MIXMODE)\n CS_TOKEN_TABLE_END\n\n char* name;\n long cmd;\n char* params;\n char str[255];\n\n iMeshObject* mesh = NULL;\n iBallState* ballstate = NULL;\n\n char* buf = (char*)string;\n while ((cmd = csGetObject (&buf, commands, &name, ¶ms)) > 0)\n {\n if (!params)\n {\n \/\/ @@@ Error handling!\n if (ballstate) ballstate->DecRef ();\n return NULL;\n }\n switch (cmd)\n {\n case CS_TOKEN_RADIUS:\n\t{\n\t float x, y, z;\n\t ScanStr (params, \"%f,%f,%f\", &x, &y, &z);\n\t ballstate->SetRadius (x, y, z);\n\t}\n\tbreak;\n case CS_TOKEN_SHIFT:\n\t{\n\t float x, y, z;\n\t ScanStr (params, \"%f,%f,%f\", &x, &y, &z);\n\t ballstate->SetShift (x, y, z);\n\t}\n\tbreak;\n case CS_TOKEN_NUMRIM:\n\t{\n\t int f;\n\t ScanStr (params, \"%d\", &f);\n\t ballstate->SetRimVertices (f);\n\t}\n\tbreak;\n case CS_TOKEN_FACTORY:\n\t{\n ScanStr (params, \"%s\", str);\n\t iMeshFactoryWrapper* fact = engine->FindMeshFactory (str);\n\t if (!fact)\n\t {\n\t \/\/ @@@ Error handling!\n\t return NULL;\n\t }\n\t mesh = fact->GetMeshObjectFactory ()->NewInstance ();\n ballstate = QUERY_INTERFACE (mesh, iBallState);\n\t}\n\tbreak;\n case CS_TOKEN_MATERIAL:\n\t{\n ScanStr (params, \"%s\", str);\n iMaterialWrapper* mat = engine->FindMaterial (str);\n\t if (!mat)\n\t {\n \/\/ @@@ Error handling!\n mesh->DecRef ();\n return NULL;\n\t }\n\t ballstate->SetMaterialWrapper (mat);\n\t}\n\tbreak;\n case CS_TOKEN_MIXMODE:\n ballstate->SetMixMode (ParseMixmode (params));\n\tbreak;\n }\n }\n\n if (ballstate) ballstate->DecRef ();\n return mesh;\n}\n\n\/\/---------------------------------------------------------------------------\n\n\ncsBallSaver::csBallSaver (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallSaver::~csBallSaver ()\n{\n}\n\nbool csBallSaver::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\nstatic void WriteMixmode(iStrVector *str, UInt mixmode)\n{\n str->Push(strnew(\" MIXMODE (\"));\n if(mixmode&CS_FX_COPY) str->Push(strnew(\" COPY ()\"));\n if(mixmode&CS_FX_ADD) str->Push(strnew(\" ADD ()\"));\n if(mixmode&CS_FX_MULTIPLY) str->Push(strnew(\" MULTIPLY ()\"));\n if(mixmode&CS_FX_MULTIPLY2) str->Push(strnew(\" MULTIPLY2 ()\"));\n if(mixmode&CS_FX_KEYCOLOR) str->Push(strnew(\" KEYCOLOR ()\"));\n if(mixmode&CS_FX_TRANSPARENT) str->Push(strnew(\" TRANSPARENT ()\"));\n if(mixmode&CS_FX_ALPHA) {\n char buf[MAXLINE];\n sprintf(buf, \"ALPHA (%g)\", float(mixmode&CS_FX_MASK_ALPHA)\/255.);\n str->Push(strnew(buf));\n }\n str->Push(strnew(\")\"));\n}\n\nvoid csBallSaver::WriteDown (iBase* obj, iStrVector *str,\n iEngine* \/*engine*\/)\n{\n iFactory *fact = QUERY_INTERFACE (this, iFactory);\n iMeshObject *mesh = QUERY_INTERFACE(obj, iMeshObject);\n if(!mesh)\n {\n printf(\"Error: non-mesh given to %s.\\n\", \n fact->QueryDescription () );\n fact->DecRef();\n return;\n }\n iBallState *state = QUERY_INTERFACE(obj, iBallState);\n if(!state)\n {\n printf(\"Error: invalid mesh given to %s.\\n\", \n fact->QueryDescription () );\n fact->DecRef();\n mesh->DecRef();\n return;\n }\n\n char buf[MAXLINE];\n char name[MAXLINE];\n csFindReplace(name, fact->QueryDescription (), \"Saver\", \"Loader\", MAXLINE);\n sprintf(buf, \"FACTORY ('%s')\\n\", name);\n str->Push(strnew(buf));\n if(state->GetMixMode() != CS_FX_COPY)\n {\n WriteMixmode(str, state->GetMixMode());\n }\n\n \/\/ Mesh information\n float x=0, y=0, z=0;\n state->GetRadius(x, y, z);\n sprintf(buf, \"RADIUS (%g, %g, %g)\\n\", x, y, z);\n str->Push(strnew(buf));\n sprintf(buf, \"SHIFT (%g, %g, %g)\\n\", state->GetShift ().x, \n state->GetShift ().y, state->GetShift ().z);\n str->Push(strnew(buf));\n sprintf(buf, \"NUMRIM (%d)\\n\", state->GetRimVertices());\n str->Push(strnew(buf));\n sprintf(buf, \"MATERIAL (%s)\\n\", state->GetMaterialWrapper()->\n GetPrivateObject()->GetName());\n str->Push(strnew(buf));\n\n fact->DecRef();\n mesh->DecRef();\n state->DecRef();\n\n}\n\n\/\/---------------------------------------------------------------------------\nFixes ball factory saver. Now it does nothing, which is correct.\/*\n Copyright (C) 2000 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n \n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csgeom\/math3d.h\"\n#include \"csutil\/parser.h\"\n#include \"csutil\/scanstr.h\"\n#include \"csutil\/cscolor.h\"\n#include \"ballldr.h\"\n#include \"imesh\/imeshobj.h\"\n#include \"iengine\/imeshobj.h\"\n#include \"iengine\/iengine.h\"\n#include \"isys\/isystem.h\"\n#include \"imesh\/imball.h\"\n#include \"ivideo\/igraph3d.h\"\n#include \"qint.h\"\n#include \"iutil\/istrvec.h\"\n#include \"csutil\/util.h\"\n#include \"iobject\/iobject.h\"\n#include \"iengine\/imater.h\"\n#include \"csengine\/material.h\"\n#include \"iengine\/imovable.h\"\n\nCS_TOKEN_DEF_START\n CS_TOKEN_DEF (ADD)\n CS_TOKEN_DEF (ALPHA)\n CS_TOKEN_DEF (COPY)\n CS_TOKEN_DEF (KEYCOLOR)\n CS_TOKEN_DEF (MULTIPLY2)\n CS_TOKEN_DEF (MULTIPLY)\n CS_TOKEN_DEF (TRANSPARENT)\n\n CS_TOKEN_DEF (NUMRIM)\n CS_TOKEN_DEF (MATERIAL)\n CS_TOKEN_DEF (FACTORY)\n CS_TOKEN_DEF (MIXMODE)\n CS_TOKEN_DEF (RADIUS)\n CS_TOKEN_DEF (SHIFT)\nCS_TOKEN_DEF_END\n\nIMPLEMENT_IBASE (csBallFactoryLoader)\n IMPLEMENTS_INTERFACE (iLoaderPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_IBASE (csBallFactorySaver)\n IMPLEMENTS_INTERFACE (iSaverPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_IBASE (csBallLoader)\n IMPLEMENTS_INTERFACE (iLoaderPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_IBASE (csBallSaver)\n IMPLEMENTS_INTERFACE (iSaverPlugIn)\n IMPLEMENTS_INTERFACE (iPlugIn)\nIMPLEMENT_IBASE_END\n\nIMPLEMENT_FACTORY (csBallFactoryLoader)\nIMPLEMENT_FACTORY (csBallFactorySaver)\nIMPLEMENT_FACTORY (csBallLoader)\nIMPLEMENT_FACTORY (csBallSaver)\n\nEXPORT_CLASS_TABLE (ballldr)\n EXPORT_CLASS (csBallFactoryLoader, \"crystalspace.mesh.loader.factory.ball\",\n \"Crystal Space Ball Factory Loader\")\n EXPORT_CLASS (csBallFactorySaver, \"crystalspace.mesh.saver.factory.ball\",\n \"Crystal Space Ball Factory Saver\")\n EXPORT_CLASS (csBallLoader, \"crystalspace.mesh.loader.ball\",\n \"Crystal Space Ball Mesh Loader\")\n EXPORT_CLASS (csBallSaver, \"crystalspace.mesh.saver.ball\",\n \"Crystal Space Ball Mesh Saver\")\nEXPORT_CLASS_TABLE_END\n\ncsBallFactoryLoader::csBallFactoryLoader (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallFactoryLoader::~csBallFactoryLoader ()\n{\n}\n\nbool csBallFactoryLoader::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\niBase* csBallFactoryLoader::Parse (const char* \/*string*\/, iEngine* \/*engine*\/)\n{\n iMeshObjectType* type = QUERY_PLUGIN_CLASS (sys, \"crystalspace.mesh.object.ball\", \"MeshObj\", iMeshObjectType);\n if (!type)\n {\n type = LOAD_PLUGIN (sys, \"crystalspace.mesh.object.ball\", \"MeshObj\", iMeshObjectType);\n printf (\"Load TYPE plugin crystalspace.mesh.object.ball\\n\");\n }\n iMeshObjectFactory* fact = type->NewFactory ();\n type->DecRef ();\n return fact;\n}\n\n\/\/---------------------------------------------------------------------------\n\ncsBallFactorySaver::csBallFactorySaver (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallFactorySaver::~csBallFactorySaver ()\n{\n}\n\nbool csBallFactorySaver::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\n#define MAXLINE 100 \/* max number of chars per line... *\/\n\nvoid csBallFactorySaver::WriteDown (iBase* \/*obj*\/, iStrVector * \/*str*\/,\n iEngine* \/*engine*\/)\n{\n \/\/ no params\n}\n\n\/\/---------------------------------------------------------------------------\n\ncsBallLoader::csBallLoader (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallLoader::~csBallLoader ()\n{\n}\n\nbool csBallLoader::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\nstatic UInt ParseMixmode (char* buf)\n{\n CS_TOKEN_TABLE_START (modes)\n CS_TOKEN_TABLE (COPY)\n CS_TOKEN_TABLE (MULTIPLY2)\n CS_TOKEN_TABLE (MULTIPLY)\n CS_TOKEN_TABLE (ADD)\n CS_TOKEN_TABLE (ALPHA)\n CS_TOKEN_TABLE (TRANSPARENT)\n CS_TOKEN_TABLE (KEYCOLOR)\n CS_TOKEN_TABLE_END\n\n char* name;\n long cmd;\n char* params;\n\n UInt Mixmode = 0;\n\n while ((cmd = csGetObject (&buf, modes, &name, ¶ms)) > 0)\n {\n if (!params)\n {\n printf (\"Expected parameters instead of '%s'!\\n\", buf);\n return 0;\n }\n switch (cmd)\n {\n case CS_TOKEN_COPY: Mixmode |= CS_FX_COPY; break;\n case CS_TOKEN_MULTIPLY: Mixmode |= CS_FX_MULTIPLY; break;\n case CS_TOKEN_MULTIPLY2: Mixmode |= CS_FX_MULTIPLY2; break;\n case CS_TOKEN_ADD: Mixmode |= CS_FX_ADD; break;\n case CS_TOKEN_ALPHA:\n\tMixmode &= ~CS_FX_MASK_ALPHA;\n\tfloat alpha;\n\tint ialpha;\n ScanStr (params, \"%f\", &alpha);\n\tialpha = QInt (alpha * 255.99);\n\tMixmode |= CS_FX_SETALPHA(ialpha);\n\tbreak;\n case CS_TOKEN_TRANSPARENT: Mixmode |= CS_FX_TRANSPARENT; break;\n case CS_TOKEN_KEYCOLOR: Mixmode |= CS_FX_KEYCOLOR; break;\n }\n }\n if (cmd == CS_PARSERR_TOKENNOTFOUND)\n {\n printf (\"Token '%s' not found while parsing the modes!\\n\", csGetLastOffender ());\n return 0;\n }\n return Mixmode;\n}\n\niBase* csBallLoader::Parse (const char* string, iEngine* engine)\n{\n CS_TOKEN_TABLE_START (commands)\n CS_TOKEN_TABLE (MATERIAL)\n CS_TOKEN_TABLE (FACTORY)\n CS_TOKEN_TABLE (NUMRIM)\n CS_TOKEN_TABLE (RADIUS)\n CS_TOKEN_TABLE (SHIFT)\n CS_TOKEN_TABLE (MIXMODE)\n CS_TOKEN_TABLE_END\n\n char* name;\n long cmd;\n char* params;\n char str[255];\n\n iMeshObject* mesh = NULL;\n iBallState* ballstate = NULL;\n\n char* buf = (char*)string;\n while ((cmd = csGetObject (&buf, commands, &name, ¶ms)) > 0)\n {\n if (!params)\n {\n \/\/ @@@ Error handling!\n if (ballstate) ballstate->DecRef ();\n return NULL;\n }\n switch (cmd)\n {\n case CS_TOKEN_RADIUS:\n\t{\n\t float x, y, z;\n\t ScanStr (params, \"%f,%f,%f\", &x, &y, &z);\n\t ballstate->SetRadius (x, y, z);\n\t}\n\tbreak;\n case CS_TOKEN_SHIFT:\n\t{\n\t float x, y, z;\n\t ScanStr (params, \"%f,%f,%f\", &x, &y, &z);\n\t ballstate->SetShift (x, y, z);\n\t}\n\tbreak;\n case CS_TOKEN_NUMRIM:\n\t{\n\t int f;\n\t ScanStr (params, \"%d\", &f);\n\t ballstate->SetRimVertices (f);\n\t}\n\tbreak;\n case CS_TOKEN_FACTORY:\n\t{\n ScanStr (params, \"%s\", str);\n\t iMeshFactoryWrapper* fact = engine->FindMeshFactory (str);\n\t if (!fact)\n\t {\n\t \/\/ @@@ Error handling!\n\t return NULL;\n\t }\n\t mesh = fact->GetMeshObjectFactory ()->NewInstance ();\n ballstate = QUERY_INTERFACE (mesh, iBallState);\n\t}\n\tbreak;\n case CS_TOKEN_MATERIAL:\n\t{\n ScanStr (params, \"%s\", str);\n iMaterialWrapper* mat = engine->FindMaterial (str);\n\t if (!mat)\n\t {\n \/\/ @@@ Error handling!\n mesh->DecRef ();\n return NULL;\n\t }\n\t ballstate->SetMaterialWrapper (mat);\n\t}\n\tbreak;\n case CS_TOKEN_MIXMODE:\n ballstate->SetMixMode (ParseMixmode (params));\n\tbreak;\n }\n }\n\n if (ballstate) ballstate->DecRef ();\n return mesh;\n}\n\n\/\/---------------------------------------------------------------------------\n\n\ncsBallSaver::csBallSaver (iBase* pParent)\n{\n CONSTRUCT_IBASE (pParent);\n}\n\ncsBallSaver::~csBallSaver ()\n{\n}\n\nbool csBallSaver::Initialize (iSystem* system)\n{\n sys = system;\n return true;\n}\n\nstatic void WriteMixmode(iStrVector *str, UInt mixmode)\n{\n str->Push(strnew(\" MIXMODE (\"));\n if(mixmode&CS_FX_COPY) str->Push(strnew(\" COPY ()\"));\n if(mixmode&CS_FX_ADD) str->Push(strnew(\" ADD ()\"));\n if(mixmode&CS_FX_MULTIPLY) str->Push(strnew(\" MULTIPLY ()\"));\n if(mixmode&CS_FX_MULTIPLY2) str->Push(strnew(\" MULTIPLY2 ()\"));\n if(mixmode&CS_FX_KEYCOLOR) str->Push(strnew(\" KEYCOLOR ()\"));\n if(mixmode&CS_FX_TRANSPARENT) str->Push(strnew(\" TRANSPARENT ()\"));\n if(mixmode&CS_FX_ALPHA) {\n char buf[MAXLINE];\n sprintf(buf, \"ALPHA (%g)\", float(mixmode&CS_FX_MASK_ALPHA)\/255.);\n str->Push(strnew(buf));\n }\n str->Push(strnew(\")\"));\n}\n\nvoid csBallSaver::WriteDown (iBase* obj, iStrVector *str,\n iEngine* \/*engine*\/)\n{\n iFactory *fact = QUERY_INTERFACE (this, iFactory);\n iMeshObject *mesh = QUERY_INTERFACE(obj, iMeshObject);\n if(!mesh)\n {\n printf(\"Error: non-mesh given to %s.\\n\", \n fact->QueryDescription () );\n fact->DecRef();\n return;\n }\n iBallState *state = QUERY_INTERFACE(obj, iBallState);\n if(!state)\n {\n printf(\"Error: invalid mesh given to %s.\\n\", \n fact->QueryDescription () );\n fact->DecRef();\n mesh->DecRef();\n return;\n }\n\n char buf[MAXLINE];\n char name[MAXLINE];\n csFindReplace(name, fact->QueryDescription (), \"Saver\", \"Loader\", MAXLINE);\n sprintf(buf, \"FACTORY ('%s')\\n\", name);\n str->Push(strnew(buf));\n if(state->GetMixMode() != CS_FX_COPY)\n {\n WriteMixmode(str, state->GetMixMode());\n }\n\n \/\/ Mesh information\n float x=0, y=0, z=0;\n state->GetRadius(x, y, z);\n sprintf(buf, \"RADIUS (%g, %g, %g)\\n\", x, y, z);\n str->Push(strnew(buf));\n sprintf(buf, \"SHIFT (%g, %g, %g)\\n\", state->GetShift ().x, \n state->GetShift ().y, state->GetShift ().z);\n str->Push(strnew(buf));\n sprintf(buf, \"NUMRIM (%d)\\n\", state->GetRimVertices());\n str->Push(strnew(buf));\n sprintf(buf, \"MATERIAL (%s)\\n\", state->GetMaterialWrapper()->\n GetPrivateObject()->GetName());\n str->Push(strnew(buf));\n\n fact->DecRef();\n mesh->DecRef();\n state->DecRef();\n\n}\n\n\/\/---------------------------------------------------------------------------\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#if SILICIUM_COMPILER_HAS_USING\nnamespace Si\n{\n\tnamespace m2\n\t{\n\t\tusing std::size_t;\n\t\tusing std::move;\n\n\t\tstruct empty_t\n\t\t{\n\t\t};\n\n\t\tstatic BOOST_CONSTEXPR_OR_CONST empty_t empty;\n\n\t\tstruct out_of_memory\n\t\t{\n\t\t};\n\n\t\tstruct piece_of_memory\n\t\t{\n\t\t\tvoid *begin;\n\n\t\t\tpiece_of_memory()\n\t\t\t : begin(nullptr)\n\t\t\t{\n\t\t\t}\n\n\t\t\texplicit piece_of_memory(void *begin)\n\t\t\t : begin(begin)\n\t\t\t{\n\t\t\t}\n\t\t};\n\n\t\tstruct standard_allocator\n\t\t{\n\t\t\tvariant allocate(size_t size)\n\t\t\t{\n\t\t\t\tvoid *memory = std::malloc(size);\n\t\t\t\tif (memory)\n\t\t\t\t{\n\t\t\t\t\treturn piece_of_memory{memory};\n\t\t\t\t}\n\t\t\t\treturn out_of_memory();\n\t\t\t}\n\n\t\t\tvariant reallocate(piece_of_memory existing_allocation, size_t new_size)\n\t\t\t{\n\t\t\t\tvoid *new_allocation = std::realloc(existing_allocation.begin, new_size);\n\t\t\t\tif (new_allocation)\n\t\t\t\t{\n\t\t\t\t\treturn piece_of_memory{new_allocation};\n\t\t\t\t}\n\t\t\t\treturn out_of_memory();\n\t\t\t}\n\n\t\t\tvoid deallocate(piece_of_memory existing_allocation)\n\t\t\t{\n\t\t\t\tstd::free(existing_allocation.begin);\n\t\t\t}\n\t\t};\n\n\t\tenum class resize_result\n\t\t{\n\t\t\tsuccess,\n\t\t\tout_of_memory\n\t\t};\n\n\t\ttemplate \n\t\tstruct dynamic_storage : private Allocator\n\t\t{\n\t\t\ttypedef T element_type;\n\t\t\ttypedef Length length_type;\n\n\t\t\tdynamic_storage(empty_t, Allocator allocator = Allocator())\n\t\t\t : Allocator(move(allocator))\n\t\t\t , m_begin()\n\t\t\t , m_length(length_type::template literal<0>())\n\t\t\t{\n\t\t\t}\n\n\t\t\t~dynamic_storage()\n\t\t\t{\n\t\t\t\tAllocator::deallocate(m_begin);\n\t\t\t}\n\n\t\t\tlength_type length() const\n\t\t\t{\n\t\t\t\treturn m_length;\n\t\t\t}\n\n\t\t\tresize_result resize(length_type new_length)\n\t\t\t{\n\t\t\t\t\/\/ TODO: handle overflow\n\t\t\t\tsize_t const size_in_bytes = new_length.value() * sizeof(element_type);\n\t\t\t\treturn visit(Allocator::reallocate(m_begin, size_in_bytes),\n\t\t\t\t [this, new_length](piece_of_memory const reallocated)\n\t\t\t\t {\n\t\t\t\t\t m_begin = reallocated;\n\t\t\t\t\t m_length = new_length;\n\t\t\t\t\t return resize_result::success;\n\t\t\t\t\t },\n\t\t\t\t [](out_of_memory)\n\t\t\t\t {\n\t\t\t\t\t return resize_result::out_of_memory;\n\t\t\t\t\t });\n\t\t\t}\n\n\t\t\tT &data() const\n\t\t\t{\n\t\t\t\treturn *begin();\n\t\t\t}\n\n\t\t\tdynamic_storage(dynamic_storage &&other) BOOST_NOEXCEPT : Allocator(move(other)),\n\t\t\t m_begin(other.m_begin),\n\t\t\t m_length(other.m_length)\n\t\t\t{\n\t\t\t\tother.m_begin = piece_of_memory();\n\t\t\t\tother.m_length = length_type::template literal<0>();\n\t\t\t}\n\n\t\t\tdynamic_storage &operator=(dynamic_storage &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tusing std::swap;\n\t\t\t\tswap(static_cast(*this), static_cast(other));\n\t\t\t\tswap(m_begin, other.m_begin);\n\t\t\t\tswap(m_length, other.m_length);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSILICIUM_DISABLE_COPY(dynamic_storage)\n\n\t\tprivate:\n\t\t\tpiece_of_memory m_begin;\n\t\t\tlength_type m_length;\n\n\t\t\tT *begin() const\n\t\t\t{\n\t\t\t\treturn static_cast(m_begin.begin);\n\t\t\t}\n\t\t};\n\n\t\tenum class emplace_back_result\n\t\t{\n\t\t\tsuccess,\n\t\t\tout_of_memory,\n\t\t\tfull\n\t\t};\n\n\t\ttemplate \n\t\tstruct basic_vector\n\t\t{\n\t\t\ttypedef typename DynamicStorage::element_type element_type;\n\t\t\ttypedef typename DynamicStorage::length_type length_type;\n\n\t\t\tbasic_vector(empty_t, DynamicStorage storage)\n\t\t\t : m_storage(move(storage))\n\t\t\t , m_used(length_type::template literal<0>())\n\t\t\t{\n\t\t\t}\n\n\t\t\tlength_type capacity() const\n\t\t\t{\n\t\t\t\treturn m_storage.length();\n\t\t\t}\n\n\t\t\tlength_type length() const\n\t\t\t{\n\t\t\t\treturn m_used;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\templace_back_result emplace_back(Args &&... args)\n\t\t\t{\n\t\t\t\toverflow_or const maybe_new_size =\n\t\t\t\t checked_add(capacity().value(), 1);\n\t\t\t\tif (maybe_new_size.is_overflow())\n\t\t\t\t{\n\t\t\t\t\treturn emplace_back_result::full;\n\t\t\t\t}\n\t\t\t\tlength_type const new_size = *length_type::create(*maybe_new_size.value());\n\t\t\t\tif (m_storage.length() < new_size)\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: exponential growth\n\t\t\t\t\tswitch (m_storage.resize(new_size))\n\t\t\t\t\t{\n\t\t\t\t\tcase resize_result::success:\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase resize_result::out_of_memory:\n\t\t\t\t\t\treturn emplace_back_result::out_of_memory;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnew (&m_storage.data()) element_type{std::forward(args)...};\n\t\t\t\tm_used = new_size;\n\t\t\t\treturn emplace_back_result::success;\n\t\t\t}\n\n\t\t\tbasic_vector(basic_vector &&other) BOOST_NOEXCEPT : m_storage(move(other.m_storage)), m_used(other.m_used)\n\t\t\t{\n\t\t\t\t\/\/ TODO: solve more generically\n\t\t\t\tother.m_used = length_type::template literal<0>();\n\t\t\t}\n\n\t\t\tbasic_vector &operator=(basic_vector &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tm_storage = move(other.m_storage);\n\t\t\t\tm_used = other.m_used;\n\t\t\t\t\/\/ TODO: solve more generically\n\t\t\t\tother.m_used = length_type::template literal<0>();\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSILICIUM_DISABLE_COPY(basic_vector)\n\n\t\tprivate:\n\t\t\tDynamicStorage m_storage;\n\t\t\tlength_type m_used;\n\t\t};\n\n\t\ttemplate \n\t\tusing vector = basic_vector>;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(move2_vector_emplace_back)\n{\n\tSi::m2::vector> v{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tBOOST_REQUIRE_EQUAL(0u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(0u, v.capacity().value());\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));\n\tBOOST_REQUIRE_EQUAL(1u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(1u, v.capacity().value());\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(13u));\n\tBOOST_REQUIRE_EQUAL(2u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(2u, v.capacity().value());\n}\n\nBOOST_AUTO_TEST_CASE(move2_vector_move_construct)\n{\n\tSi::m2::vector> v{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));\n\tSi::m2::vector> w{std::move(v)};\n\tBOOST_REQUIRE_EQUAL(0u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(1u, w.length().value());\n}\n\nBOOST_AUTO_TEST_CASE(move2_vector_move_assign)\n{\n\tSi::m2::vector> v{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));\n\tSi::m2::vector> w{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tw = std::move(v);\n\tBOOST_REQUIRE_EQUAL(0u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(1u, w.length().value());\n}\n#endif\nimplement ~basic_vector#include \n#include \n#include \n#include \n#include \n\n#if SILICIUM_COMPILER_HAS_USING\nnamespace Si\n{\n\tnamespace m2\n\t{\n\t\tusing std::size_t;\n\t\tusing std::move;\n\n\t\tstruct empty_t\n\t\t{\n\t\t};\n\n\t\tstatic BOOST_CONSTEXPR_OR_CONST empty_t empty;\n\n\t\tstruct out_of_memory\n\t\t{\n\t\t};\n\n\t\tstruct piece_of_memory\n\t\t{\n\t\t\tvoid *begin;\n\n\t\t\tpiece_of_memory()\n\t\t\t : begin(nullptr)\n\t\t\t{\n\t\t\t}\n\n\t\t\texplicit piece_of_memory(void *begin)\n\t\t\t : begin(begin)\n\t\t\t{\n\t\t\t}\n\t\t};\n\n\t\tstruct standard_allocator\n\t\t{\n\t\t\tvariant allocate(size_t size)\n\t\t\t{\n\t\t\t\tvoid *memory = std::malloc(size);\n\t\t\t\tif (memory)\n\t\t\t\t{\n\t\t\t\t\treturn piece_of_memory{memory};\n\t\t\t\t}\n\t\t\t\treturn out_of_memory();\n\t\t\t}\n\n\t\t\tvariant reallocate(piece_of_memory existing_allocation, size_t new_size)\n\t\t\t{\n\t\t\t\tvoid *new_allocation = std::realloc(existing_allocation.begin, new_size);\n\t\t\t\tif (new_allocation)\n\t\t\t\t{\n\t\t\t\t\treturn piece_of_memory{new_allocation};\n\t\t\t\t}\n\t\t\t\treturn out_of_memory();\n\t\t\t}\n\n\t\t\tvoid deallocate(piece_of_memory existing_allocation)\n\t\t\t{\n\t\t\t\tstd::free(existing_allocation.begin);\n\t\t\t}\n\t\t};\n\n\t\tenum class resize_result\n\t\t{\n\t\t\tsuccess,\n\t\t\tout_of_memory\n\t\t};\n\n\t\ttemplate \n\t\tstruct dynamic_storage : private Allocator\n\t\t{\n\t\t\ttypedef T element_type;\n\t\t\ttypedef Length length_type;\n\n\t\t\tdynamic_storage(empty_t, Allocator allocator = Allocator())\n\t\t\t : Allocator(move(allocator))\n\t\t\t , m_begin()\n\t\t\t , m_length(length_type::template literal<0>())\n\t\t\t{\n\t\t\t}\n\n\t\t\t~dynamic_storage()\n\t\t\t{\n\t\t\t\tAllocator::deallocate(m_begin);\n\t\t\t}\n\n\t\t\tlength_type length() const\n\t\t\t{\n\t\t\t\treturn m_length;\n\t\t\t}\n\n\t\t\tresize_result resize(length_type new_length)\n\t\t\t{\n\t\t\t\t\/\/ TODO: handle overflow\n\t\t\t\tsize_t const size_in_bytes = new_length.value() * sizeof(element_type);\n\t\t\t\treturn visit(Allocator::reallocate(m_begin, size_in_bytes),\n\t\t\t\t [this, new_length](piece_of_memory const reallocated)\n\t\t\t\t {\n\t\t\t\t\t m_begin = reallocated;\n\t\t\t\t\t m_length = new_length;\n\t\t\t\t\t return resize_result::success;\n\t\t\t\t\t },\n\t\t\t\t [](out_of_memory)\n\t\t\t\t {\n\t\t\t\t\t return resize_result::out_of_memory;\n\t\t\t\t\t });\n\t\t\t}\n\n\t\t\tT &data() const\n\t\t\t{\n\t\t\t\treturn *begin();\n\t\t\t}\n\n\t\t\tdynamic_storage(dynamic_storage &&other) BOOST_NOEXCEPT : Allocator(move(other)),\n\t\t\t m_begin(other.m_begin),\n\t\t\t m_length(other.m_length)\n\t\t\t{\n\t\t\t\tother.m_begin = piece_of_memory();\n\t\t\t\tother.m_length = length_type::template literal<0>();\n\t\t\t}\n\n\t\t\tdynamic_storage &operator=(dynamic_storage &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tusing std::swap;\n\t\t\t\tswap(static_cast(*this), static_cast(other));\n\t\t\t\tswap(m_begin, other.m_begin);\n\t\t\t\tswap(m_length, other.m_length);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSILICIUM_DISABLE_COPY(dynamic_storage)\n\n\t\tprivate:\n\t\t\tpiece_of_memory m_begin;\n\t\t\tlength_type m_length;\n\n\t\t\tT *begin() const\n\t\t\t{\n\t\t\t\treturn static_cast(m_begin.begin);\n\t\t\t}\n\t\t};\n\n\t\tenum class emplace_back_result\n\t\t{\n\t\t\tsuccess,\n\t\t\tout_of_memory,\n\t\t\tfull\n\t\t};\n\n\t\ttemplate \n\t\tstruct basic_vector\n\t\t{\n\t\t\ttypedef typename DynamicStorage::element_type element_type;\n\t\t\ttypedef typename DynamicStorage::length_type length_type;\n\n\t\t\tbasic_vector(empty_t, DynamicStorage storage)\n\t\t\t : m_storage(move(storage))\n\t\t\t , m_used(length_type::template literal<0>())\n\t\t\t{\n\t\t\t}\n\n\t\t\t~basic_vector() BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tfor (typename length_type::value_type i = 0; i < length().value(); ++i)\n\t\t\t\t{\n\t\t\t\t\t(&m_storage.data())[length().value() - 1 - i].~element_type();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlength_type capacity() const BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\treturn m_storage.length();\n\t\t\t}\n\n\t\t\tlength_type length() const BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\treturn m_used;\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\templace_back_result emplace_back(Args &&... args)\n\t\t\t{\n\t\t\t\toverflow_or const maybe_new_size =\n\t\t\t\t checked_add(capacity().value(), 1);\n\t\t\t\tif (maybe_new_size.is_overflow())\n\t\t\t\t{\n\t\t\t\t\treturn emplace_back_result::full;\n\t\t\t\t}\n\t\t\t\tlength_type const new_size = *length_type::create(*maybe_new_size.value());\n\t\t\t\tif (m_storage.length() < new_size)\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: exponential growth\n\t\t\t\t\tswitch (m_storage.resize(new_size))\n\t\t\t\t\t{\n\t\t\t\t\tcase resize_result::success:\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase resize_result::out_of_memory:\n\t\t\t\t\t\treturn emplace_back_result::out_of_memory;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnew (&m_storage.data()) element_type{std::forward(args)...};\n\t\t\t\tm_used = new_size;\n\t\t\t\treturn emplace_back_result::success;\n\t\t\t}\n\n\t\t\tbasic_vector(basic_vector &&other) BOOST_NOEXCEPT : m_storage(move(other.m_storage)), m_used(other.m_used)\n\t\t\t{\n\t\t\t\t\/\/ TODO: solve more generically\n\t\t\t\tother.m_used = length_type::template literal<0>();\n\t\t\t}\n\n\t\t\tbasic_vector &operator=(basic_vector &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tm_storage = move(other.m_storage);\n\t\t\t\tm_used = other.m_used;\n\t\t\t\t\/\/ TODO: solve more generically\n\t\t\t\tother.m_used = length_type::template literal<0>();\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tSILICIUM_DISABLE_COPY(basic_vector)\n\n\t\tprivate:\n\t\t\tDynamicStorage m_storage;\n\t\t\tlength_type m_used;\n\t\t};\n\n\t\ttemplate \n\t\tusing vector = basic_vector>;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(move2_vector_emplace_back)\n{\n\tSi::m2::vector> v{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tBOOST_REQUIRE_EQUAL(0u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(0u, v.capacity().value());\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));\n\tBOOST_REQUIRE_EQUAL(1u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(1u, v.capacity().value());\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(13u));\n\tBOOST_REQUIRE_EQUAL(2u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(2u, v.capacity().value());\n}\n\nBOOST_AUTO_TEST_CASE(move2_vector_move_construct)\n{\n\tSi::m2::vector> v{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));\n\tSi::m2::vector> w{std::move(v)};\n\tBOOST_REQUIRE_EQUAL(0u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(1u, w.length().value());\n}\n\nBOOST_AUTO_TEST_CASE(move2_vector_move_assign)\n{\n\tSi::m2::vector> v{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tBOOST_REQUIRE(Si::m2::emplace_back_result::success == v.emplace_back(12u));\n\tSi::m2::vector> w{\n\t Si::m2::empty,\n\t Si::m2::dynamic_storage, Si::m2::standard_allocator>{\n\t Si::m2::empty}};\n\tw = std::move(v);\n\tBOOST_REQUIRE_EQUAL(0u, v.length().value());\n\tBOOST_REQUIRE_EQUAL(1u, w.length().value());\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\ntemplate void matrixRedux(const MatrixType& m)\n{\n typedef typename MatrixType::Index Index;\n typedef typename MatrixType::Scalar Scalar;\n typedef typename MatrixType::RealScalar RealScalar;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols);\n\n \/\/ The entries of m1 are uniformly distributed in [0,1], so m1.prod() is very small. This may lead to test\n \/\/ failures if we underflow into denormals. Thus, we scale so that entires are close to 1.\n MatrixType m1_for_prod = MatrixType::Ones(rows, cols) + RealScalar(0.2) * m1;\n\n VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows, cols).sum(), Scalar(1));\n VERIFY_IS_APPROX(MatrixType::Ones(rows, cols).sum(), Scalar(float(rows*cols))); \/\/ the float() here to shut up excessive MSVC warning about int->complex conversion being lossy\n Scalar s(0), p(1), minc(numext::real(m1.coeff(0))), maxc(numext::real(m1.coeff(0)));\n for(int j = 0; j < cols; j++)\n for(int i = 0; i < rows; i++)\n {\n s += m1(i,j);\n p *= m1_for_prod(i,j);\n minc = (std::min)(numext::real(minc), numext::real(m1(i,j)));\n maxc = (std::max)(numext::real(maxc), numext::real(m1(i,j)));\n }\n const Scalar mean = s\/Scalar(RealScalar(rows*cols));\n\n VERIFY_IS_APPROX(m1.sum(), s);\n VERIFY_IS_APPROX(m1.mean(), mean);\n VERIFY_IS_APPROX(m1_for_prod.prod(), p);\n VERIFY_IS_APPROX(m1.real().minCoeff(), numext::real(minc));\n VERIFY_IS_APPROX(m1.real().maxCoeff(), numext::real(maxc));\n\n \/\/ test slice vectorization assuming assign is ok\n Index r0 = internal::random(0,rows-1);\n Index c0 = internal::random(0,cols-1);\n Index r1 = internal::random(r0+1,rows)-r0;\n Index c1 = internal::random(c0+1,cols)-c0;\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).sum(), m1.block(r0,c0,r1,c1).eval().sum());\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).mean(), m1.block(r0,c0,r1,c1).eval().mean());\n VERIFY_IS_APPROX(m1_for_prod.block(r0,c0,r1,c1).prod(), m1_for_prod.block(r0,c0,r1,c1).eval().prod());\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).real().minCoeff(), m1.block(r0,c0,r1,c1).real().eval().minCoeff());\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).real().maxCoeff(), m1.block(r0,c0,r1,c1).real().eval().maxCoeff());\n \n \/\/ test empty objects\n VERIFY_IS_APPROX(m1.block(r0,c0,0,0).sum(), Scalar(0));\n VERIFY_IS_APPROX(m1.block(r0,c0,0,0).prod(), Scalar(1));\n}\n\ntemplate void vectorRedux(const VectorType& w)\n{\n using std::abs;\n typedef typename VectorType::Index Index;\n typedef typename VectorType::Scalar Scalar;\n typedef typename NumTraits::Real RealScalar;\n Index size = w.size();\n\n VectorType v = VectorType::Random(size);\n VectorType v_for_prod = VectorType::Ones(size) + Scalar(0.2) * v; \/\/ see comment above declaration of m1_for_prod\n\n for(int i = 1; i < size; i++)\n {\n Scalar s(0), p(1);\n RealScalar minc(numext::real(v.coeff(0))), maxc(numext::real(v.coeff(0)));\n for(int j = 0; j < i; j++)\n {\n s += v[j];\n p *= v_for_prod[j];\n minc = (std::min)(minc, numext::real(v[j]));\n maxc = (std::max)(maxc, numext::real(v[j]));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(s - v.head(i).sum()), Scalar(1));\n VERIFY_IS_APPROX(p, v_for_prod.head(i).prod());\n VERIFY_IS_APPROX(minc, v.real().head(i).minCoeff());\n VERIFY_IS_APPROX(maxc, v.real().head(i).maxCoeff());\n }\n\n for(int i = 0; i < size-1; i++)\n {\n Scalar s(0), p(1);\n RealScalar minc(numext::real(v.coeff(i))), maxc(numext::real(v.coeff(i)));\n for(int j = i; j < size; j++)\n {\n s += v[j];\n p *= v_for_prod[j];\n minc = (std::min)(minc, numext::real(v[j]));\n maxc = (std::max)(maxc, numext::real(v[j]));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(s - v.tail(size-i).sum()), Scalar(1));\n VERIFY_IS_APPROX(p, v_for_prod.tail(size-i).prod());\n VERIFY_IS_APPROX(minc, v.real().tail(size-i).minCoeff());\n VERIFY_IS_APPROX(maxc, v.real().tail(size-i).maxCoeff());\n }\n\n for(int i = 0; i < size\/2; i++)\n {\n Scalar s(0), p(1);\n RealScalar minc(numext::real(v.coeff(i))), maxc(numext::real(v.coeff(i)));\n for(int j = i; j < size-i; j++)\n {\n s += v[j];\n p *= v_for_prod[j];\n minc = (std::min)(minc, numext::real(v[j]));\n maxc = (std::max)(maxc, numext::real(v[j]));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(s - v.segment(i, size-2*i).sum()), Scalar(1));\n VERIFY_IS_APPROX(p, v_for_prod.segment(i, size-2*i).prod());\n VERIFY_IS_APPROX(minc, v.real().segment(i, size-2*i).minCoeff());\n VERIFY_IS_APPROX(maxc, v.real().segment(i, size-2*i).maxCoeff());\n }\n \n \/\/ test empty objects\n VERIFY_IS_APPROX(v.head(0).sum(), Scalar(0));\n VERIFY_IS_APPROX(v.tail(0).prod(), Scalar(1));\n VERIFY_RAISES_ASSERT(v.head(0).mean());\n VERIFY_RAISES_ASSERT(v.head(0).minCoeff());\n VERIFY_RAISES_ASSERT(v.head(0).maxCoeff());\n}\n\nvoid test_redux()\n{\n \/\/ the max size cannot be too large, otherwise reduxion operations obviously generate large errors.\n int maxsize = (std::min)(100,EIGEN_TEST_MAX_SIZE);\n TEST_SET_BUT_UNUSED_VARIABLE(maxsize);\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( matrixRedux(Matrix()) );\n CALL_SUBTEST_1( matrixRedux(Array()) );\n CALL_SUBTEST_2( matrixRedux(Matrix2f()) );\n CALL_SUBTEST_2( matrixRedux(Array2f()) );\n CALL_SUBTEST_3( matrixRedux(Matrix4d()) );\n CALL_SUBTEST_3( matrixRedux(Array4d()) );\n CALL_SUBTEST_4( matrixRedux(MatrixXcf(internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_4( matrixRedux(ArrayXXcf(internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_5( matrixRedux(MatrixXd (internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_5( matrixRedux(ArrayXXd (internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_6( matrixRedux(MatrixXi (internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_6( matrixRedux(ArrayXXi (internal::random(1,maxsize), internal::random(1,maxsize))) );\n }\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_7( vectorRedux(Vector4f()) );\n CALL_SUBTEST_7( vectorRedux(Array4f()) );\n CALL_SUBTEST_5( vectorRedux(VectorXd(internal::random(1,maxsize))) );\n CALL_SUBTEST_5( vectorRedux(ArrayXd(internal::random(1,maxsize))) );\n CALL_SUBTEST_8( vectorRedux(VectorXf(internal::random(1,maxsize))) );\n CALL_SUBTEST_8( vectorRedux(ArrayXf(internal::random(1,maxsize))) );\n }\n}\nAdd unit test to check nesting of complex expressions in redux()\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define TEST_ENABLE_TEMPORARY_TRACKING\n\n#include \"main.h\"\n\ntemplate void matrixRedux(const MatrixType& m)\n{\n typedef typename MatrixType::Index Index;\n typedef typename MatrixType::Scalar Scalar;\n typedef typename MatrixType::RealScalar RealScalar;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols);\n\n \/\/ The entries of m1 are uniformly distributed in [0,1], so m1.prod() is very small. This may lead to test\n \/\/ failures if we underflow into denormals. Thus, we scale so that entires are close to 1.\n MatrixType m1_for_prod = MatrixType::Ones(rows, cols) + RealScalar(0.2) * m1;\n\n VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows, cols).sum(), Scalar(1));\n VERIFY_IS_APPROX(MatrixType::Ones(rows, cols).sum(), Scalar(float(rows*cols))); \/\/ the float() here to shut up excessive MSVC warning about int->complex conversion being lossy\n Scalar s(0), p(1), minc(numext::real(m1.coeff(0))), maxc(numext::real(m1.coeff(0)));\n for(int j = 0; j < cols; j++)\n for(int i = 0; i < rows; i++)\n {\n s += m1(i,j);\n p *= m1_for_prod(i,j);\n minc = (std::min)(numext::real(minc), numext::real(m1(i,j)));\n maxc = (std::max)(numext::real(maxc), numext::real(m1(i,j)));\n }\n const Scalar mean = s\/Scalar(RealScalar(rows*cols));\n\n VERIFY_IS_APPROX(m1.sum(), s);\n VERIFY_IS_APPROX(m1.mean(), mean);\n VERIFY_IS_APPROX(m1_for_prod.prod(), p);\n VERIFY_IS_APPROX(m1.real().minCoeff(), numext::real(minc));\n VERIFY_IS_APPROX(m1.real().maxCoeff(), numext::real(maxc));\n\n \/\/ test slice vectorization assuming assign is ok\n Index r0 = internal::random(0,rows-1);\n Index c0 = internal::random(0,cols-1);\n Index r1 = internal::random(r0+1,rows)-r0;\n Index c1 = internal::random(c0+1,cols)-c0;\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).sum(), m1.block(r0,c0,r1,c1).eval().sum());\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).mean(), m1.block(r0,c0,r1,c1).eval().mean());\n VERIFY_IS_APPROX(m1_for_prod.block(r0,c0,r1,c1).prod(), m1_for_prod.block(r0,c0,r1,c1).eval().prod());\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).real().minCoeff(), m1.block(r0,c0,r1,c1).real().eval().minCoeff());\n VERIFY_IS_APPROX(m1.block(r0,c0,r1,c1).real().maxCoeff(), m1.block(r0,c0,r1,c1).real().eval().maxCoeff());\n \n \/\/ test empty objects\n VERIFY_IS_APPROX(m1.block(r0,c0,0,0).sum(), Scalar(0));\n VERIFY_IS_APPROX(m1.block(r0,c0,0,0).prod(), Scalar(1));\n\n \/\/ test nesting complex expression\n VERIFY_EVALUATION_COUNT( (m1.matrix()*m1.matrix().transpose()).sum(), (MatrixType::SizeAtCompileTime==Dynamic ? 1 : 0) );\n VERIFY_EVALUATION_COUNT( ((m1.matrix()*m1.matrix().transpose())*Scalar(2)).sum(), (MatrixType::SizeAtCompileTime==Dynamic ? 1 : 0) );\n\n}\n\ntemplate void vectorRedux(const VectorType& w)\n{\n using std::abs;\n typedef typename VectorType::Index Index;\n typedef typename VectorType::Scalar Scalar;\n typedef typename NumTraits::Real RealScalar;\n Index size = w.size();\n\n VectorType v = VectorType::Random(size);\n VectorType v_for_prod = VectorType::Ones(size) + Scalar(0.2) * v; \/\/ see comment above declaration of m1_for_prod\n\n for(int i = 1; i < size; i++)\n {\n Scalar s(0), p(1);\n RealScalar minc(numext::real(v.coeff(0))), maxc(numext::real(v.coeff(0)));\n for(int j = 0; j < i; j++)\n {\n s += v[j];\n p *= v_for_prod[j];\n minc = (std::min)(minc, numext::real(v[j]));\n maxc = (std::max)(maxc, numext::real(v[j]));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(s - v.head(i).sum()), Scalar(1));\n VERIFY_IS_APPROX(p, v_for_prod.head(i).prod());\n VERIFY_IS_APPROX(minc, v.real().head(i).minCoeff());\n VERIFY_IS_APPROX(maxc, v.real().head(i).maxCoeff());\n }\n\n for(int i = 0; i < size-1; i++)\n {\n Scalar s(0), p(1);\n RealScalar minc(numext::real(v.coeff(i))), maxc(numext::real(v.coeff(i)));\n for(int j = i; j < size; j++)\n {\n s += v[j];\n p *= v_for_prod[j];\n minc = (std::min)(minc, numext::real(v[j]));\n maxc = (std::max)(maxc, numext::real(v[j]));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(s - v.tail(size-i).sum()), Scalar(1));\n VERIFY_IS_APPROX(p, v_for_prod.tail(size-i).prod());\n VERIFY_IS_APPROX(minc, v.real().tail(size-i).minCoeff());\n VERIFY_IS_APPROX(maxc, v.real().tail(size-i).maxCoeff());\n }\n\n for(int i = 0; i < size\/2; i++)\n {\n Scalar s(0), p(1);\n RealScalar minc(numext::real(v.coeff(i))), maxc(numext::real(v.coeff(i)));\n for(int j = i; j < size-i; j++)\n {\n s += v[j];\n p *= v_for_prod[j];\n minc = (std::min)(minc, numext::real(v[j]));\n maxc = (std::max)(maxc, numext::real(v[j]));\n }\n VERIFY_IS_MUCH_SMALLER_THAN(abs(s - v.segment(i, size-2*i).sum()), Scalar(1));\n VERIFY_IS_APPROX(p, v_for_prod.segment(i, size-2*i).prod());\n VERIFY_IS_APPROX(minc, v.real().segment(i, size-2*i).minCoeff());\n VERIFY_IS_APPROX(maxc, v.real().segment(i, size-2*i).maxCoeff());\n }\n \n \/\/ test empty objects\n VERIFY_IS_APPROX(v.head(0).sum(), Scalar(0));\n VERIFY_IS_APPROX(v.tail(0).prod(), Scalar(1));\n VERIFY_RAISES_ASSERT(v.head(0).mean());\n VERIFY_RAISES_ASSERT(v.head(0).minCoeff());\n VERIFY_RAISES_ASSERT(v.head(0).maxCoeff());\n}\n\nvoid test_redux()\n{\n \/\/ the max size cannot be too large, otherwise reduxion operations obviously generate large errors.\n int maxsize = (std::min)(100,EIGEN_TEST_MAX_SIZE);\n TEST_SET_BUT_UNUSED_VARIABLE(maxsize);\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( matrixRedux(Matrix()) );\n CALL_SUBTEST_1( matrixRedux(Array()) );\n CALL_SUBTEST_2( matrixRedux(Matrix2f()) );\n CALL_SUBTEST_2( matrixRedux(Array2f()) );\n CALL_SUBTEST_3( matrixRedux(Matrix4d()) );\n CALL_SUBTEST_3( matrixRedux(Array4d()) );\n CALL_SUBTEST_4( matrixRedux(MatrixXcf(internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_4( matrixRedux(ArrayXXcf(internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_5( matrixRedux(MatrixXd (internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_5( matrixRedux(ArrayXXd (internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_6( matrixRedux(MatrixXi (internal::random(1,maxsize), internal::random(1,maxsize))) );\n CALL_SUBTEST_6( matrixRedux(ArrayXXi (internal::random(1,maxsize), internal::random(1,maxsize))) );\n }\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_7( vectorRedux(Vector4f()) );\n CALL_SUBTEST_7( vectorRedux(Array4f()) );\n CALL_SUBTEST_5( vectorRedux(VectorXd(internal::random(1,maxsize))) );\n CALL_SUBTEST_5( vectorRedux(ArrayXd(internal::random(1,maxsize))) );\n CALL_SUBTEST_8( vectorRedux(VectorXf(internal::random(1,maxsize))) );\n CALL_SUBTEST_8( vectorRedux(ArrayXf(internal::random(1,maxsize))) );\n }\n}\n<|endoftext|>"} {"text":"AV1InvTxfm2d.RunRoundtripCheck: Add TX64X64 test.<|endoftext|>"} {"text":"\/*\n * This file is part of the SPLINTER library.\n * Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com).\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n\n#include \n#include \n\nnamespace SPLINTER\n{\n\n\/*\n * Comparison operators\n *\/\nbool operator==(const DataTable &lhs, const DataTable &rhs) {\n return\n lhs.getNumVariables() == rhs.getNumVariables()\n && lhs.getNumSamples() == rhs.getNumSamples()\n && lhs.getSamples() == rhs.getSamples()\n && lhs.getGrid() == rhs.getGrid();\n}\n\nbool operator==(const DataSample &lhs, const DataSample &rhs) {\n for(unsigned int i = 0; i < lhs.getDimX(); i++)\n {\n if(!equalsWithinRange(lhs.getX().at(i), rhs.getX().at(i))) {\n return false;\n }\n }\n\n if(!equalsWithinRange(lhs.getY(), rhs.getY())) {\n return false;\n }\n\n return true;\n}\n\nbool operator==(const BSpline &lhs, const BSpline &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables()\n && lhs.getNumControlPoints() == rhs.getNumControlPoints()\n && lhs.getNumBasisFunctions() == rhs.getNumBasisFunctions()\n && lhs.getKnotVectors() == rhs.getKnotVectors()\n && lhs.getBasisDegrees() == rhs.getBasisDegrees()\n && lhs.getDomainLowerBound() == rhs.getDomainLowerBound()\n && lhs.getDomainUpperBound() == rhs.getDomainUpperBound();\n}\n\nbool operator==(const PSpline &lhs, const PSpline &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables();\n}\n\nbool operator==(const RadialBasisFunction &lhs, const RadialBasisFunction &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables();\n}\n\nbool operator==(const PolynomialRegression &lhs, const PolynomialRegression &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables();\n}\n\ntemplate \nbool operator==(const std::vector &lhs, const std::vector &rhs)\n{\n auto lit = lhs.cbegin(), rit = rhs.cbegin();\n for (; lit != lhs.cend() && rit != rhs.cend(); ++lit, ++rit)\n {\n if(*lit != *rit) {\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool operator==(const std::set &lhs, const std::set &rhs)\n{\n auto lit = lhs.cbegin(), rit = rhs.cbegin();\n for (; lit != lhs.cend() && rit != rhs.cend(); ++lit, ++rit)\n {\n if(*lit != *rit) {\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool operator==(const std::multiset &lhs, const std::multiset &rhs)\n{\n auto lit = lhs.cbegin(), rit = rhs.cbegin();\n for (; lit != lhs.cend() && rit != rhs.cend(); ++lit, ++rit)\n {\n if(*lit != *rit) {\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool operator!=(const T &lhs, const T &rhs) {\n return !(lhs == rhs);\n}\n\n\/*\n * Output stream operator\n *\/\nstd::ostream &operator<<(std::ostream &out, const DataSample &sample) {\n out << \"(\";\n bool firstLoop = true;\n for(auto val : sample.getX()) {\n out << val;\n if(!firstLoop) {\n out << \", \";\n }\n firstLoop = false;\n }\n out << \") = (\" << sample.getY() << \")\";\n\n return out;\n}\n\nstd::ostream &operator<<(std::ostream &out, const DataTable &table) {\n out << \"numVariables: \" << table.getNumVariables() << std::endl;\n out << \"numSamples: \" << table.getNumSamples() << std::endl;\n \/\/ out << \"samples: \" << table.getSamples() << std::endl;\n out << \"grid dimensions: \";\n bool firstLoop = true;\n for(const auto &dimension : table.getGrid()) {\n out << dimension.size();\n if(!firstLoop) {\n out << \", \";\n }\n firstLoop = false;\n }\n\n return out;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &out, const std::vector &obj) {\n for(const T &elem : obj) {\n out << elem << std::endl;\n }\n\n return out;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &out, const std::set &obj) {\n for(const T &elem : obj) {\n out << elem << std::endl;\n }\n\n return out;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &out, const std::multiset &obj) {\n for(const T &elem : obj) {\n out << elem << std::endl;\n }\n\n return out;\n}\n\n} \/\/ namespace SPLINTER\nMinor fix to sample and grid printing\/*\n * This file is part of the SPLINTER library.\n * Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com).\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n\n#include \n#include \n\nnamespace SPLINTER\n{\n\n\/*\n * Comparison operators\n *\/\nbool operator==(const DataTable &lhs, const DataTable &rhs) {\n return\n lhs.getNumVariables() == rhs.getNumVariables()\n && lhs.getNumSamples() == rhs.getNumSamples()\n && lhs.getSamples() == rhs.getSamples()\n && lhs.getGrid() == rhs.getGrid();\n}\n\nbool operator==(const DataSample &lhs, const DataSample &rhs) {\n for(unsigned int i = 0; i < lhs.getDimX(); i++)\n {\n if(!equalsWithinRange(lhs.getX().at(i), rhs.getX().at(i))) {\n return false;\n }\n }\n\n if(!equalsWithinRange(lhs.getY(), rhs.getY())) {\n return false;\n }\n\n return true;\n}\n\nbool operator==(const BSpline &lhs, const BSpline &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables()\n && lhs.getNumControlPoints() == rhs.getNumControlPoints()\n && lhs.getNumBasisFunctions() == rhs.getNumBasisFunctions()\n && lhs.getKnotVectors() == rhs.getKnotVectors()\n && lhs.getBasisDegrees() == rhs.getBasisDegrees()\n && lhs.getDomainLowerBound() == rhs.getDomainLowerBound()\n && lhs.getDomainUpperBound() == rhs.getDomainUpperBound();\n}\n\nbool operator==(const PSpline &lhs, const PSpline &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables();\n}\n\nbool operator==(const RadialBasisFunction &lhs, const RadialBasisFunction &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables();\n}\n\nbool operator==(const PolynomialRegression &lhs, const PolynomialRegression &rhs)\n{\n return\n lhs.getNumVariables() == rhs.getNumVariables();\n}\n\ntemplate \nbool operator==(const std::vector &lhs, const std::vector &rhs)\n{\n auto lit = lhs.cbegin(), rit = rhs.cbegin();\n for (; lit != lhs.cend() && rit != rhs.cend(); ++lit, ++rit)\n {\n if(*lit != *rit) {\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool operator==(const std::set &lhs, const std::set &rhs)\n{\n auto lit = lhs.cbegin(), rit = rhs.cbegin();\n for (; lit != lhs.cend() && rit != rhs.cend(); ++lit, ++rit)\n {\n if(*lit != *rit) {\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool operator==(const std::multiset &lhs, const std::multiset &rhs)\n{\n auto lit = lhs.cbegin(), rit = rhs.cbegin();\n for (; lit != lhs.cend() && rit != rhs.cend(); ++lit, ++rit)\n {\n if(*lit != *rit) {\n return false;\n }\n }\n return true;\n}\n\ntemplate \nbool operator!=(const T &lhs, const T &rhs) {\n return !(lhs == rhs);\n}\n\n\/*\n * Output stream operator\n *\/\nstd::ostream &operator<<(std::ostream &out, const DataSample &sample) {\n out << \"(\";\n bool firstLoop = true;\n for(auto val : sample.getX()) {\n if(!firstLoop) {\n out << \", \";\n }\n out << val;\n firstLoop = false;\n }\n out << \") = (\" << sample.getY() << \")\";\n\n return out;\n}\n\nstd::ostream &operator<<(std::ostream &out, const DataTable &table) {\n out << \"numVariables: \" << table.getNumVariables() << std::endl;\n out << \"numSamples: \" << table.getNumSamples() << std::endl;\n \/\/out << \"samples: \" << table.getSamples() << std::endl;\n out << \"grid dimensions: \";\n bool firstLoop = true;\n for(const auto &dimension : table.getGrid()) {\n if(!firstLoop) {\n out << \", \";\n }\n out << dimension.size();\n firstLoop = false;\n }\n\n return out;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &out, const std::vector &obj) {\n for(const T &elem : obj) {\n out << elem << std::endl;\n }\n\n return out;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &out, const std::set &obj) {\n for(const T &elem : obj) {\n out << elem << std::endl;\n }\n\n return out;\n}\n\ntemplate \nstd::ostream &operator<<(std::ostream &out, const std::multiset &obj) {\n for(const T &elem : obj) {\n out << elem << std::endl;\n }\n\n return out;\n}\n\n} \/\/ namespace SPLINTER\n<|endoftext|>"} {"text":"#include \"Octree.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace AGE\n{\n\tOctree::Octree()\n\t{\n\t}\n\n\tOctree::~Octree(void)\n\t{\n\t\t_commandQueue.emplace();\n\t\t_commandQueue.releaseReadability();\n\t}\n\n\tbool Octree::_init()\n\t{\n\t\t_octreeDrawList = AGE::Vector();\n\t\treturn true;\n\t}\n\n\tbool Octree::_initInNewThread()\n\t{\n\t\treturn true;\n\t}\n\n\tbool Octree::_release()\n\t{\n\t\treturn true;\n\t}\n\n\tbool Octree::_releaseInNewThread()\n\t{\n\t\treturn true;\n\t}\n\n\tconst OctreeKey &Octree::addCullableElement()\n\t{\n\t\tOctreeKey res;\n\t\tres.type = OctreeKey::Type::Cullable;\n\t\tif (!_freeUserObjects.empty())\n\t\t{\n\t\t\tres.id = _freeUserObjects.front();\n\t\t\t_freeUserObjects.pop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres.id = _userObjectCounter++;\n\t\t}\n\n\t\t_commandQueue.emplace(res);\n\t\treturn res;\n\t}\n\n\tvoid Octree::removeElement(const OctreeKey &key)\n\t{\n\t\tassert(!key.invalid());\n\t\tswitch (key.type)\n\t\t{\n\t\tcase(OctreeKey::Type::Camera) :\n\t\t{\n\t\t\t_freeCameraObjects.push(key.id);\n\t\t\t_commandQueue.emplace(key);\n\t\t}\n\t\t\t\t\t\t\t\t\t break;\n\t\tcase(OctreeKey::Type::Cullable) :\n\t\t{\n\t\t\t_freeUserObjects.push(key.id);\n\t\t\t_commandQueue.emplace(key);\n\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst OctreeKey &Octree::addCameraElement()\n\t{\n\t\tOctreeKey res;\n\t\tres.type = OctreeKey::Type::Camera;\n\t\tif (!_freeCameraObjects.empty())\n\t\t{\n\t\t\tres.id = _freeCameraObjects.front();\n\t\t\t_freeCameraObjects.pop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres.id = _cameraCounter++;\n\t\t}\n\t\t_commandQueue.emplace(res);\n\n\t\treturn res;\n\t}\n\n\tvoid Octree::setPosition(const glm::vec3 &v, const OctreeKey &id)\n\t{\n\t\t_commandQueue.emplace(id, v);\n\t}\n\tvoid Octree::setOrientation(const glm::quat &v, const OctreeKey &id)\n\t{\n\t\t_commandQueue.emplace(id, v);\n\t}\n\n\tvoid Octree::setScale(const glm::vec3 &v, const OctreeKey &id)\n\t{\n\t\t_commandQueue.emplace(id, v);\n\t}\n\n\tvoid Octree::setCameraInfos(const OctreeKey &id\n\t\t, const glm::mat4 &projection)\n\t{\n\t\t_commandQueue.emplace(id, projection);\n\t}\n\n\tvoid Octree::setPosition(const glm::vec3 &v, const std::array &ids)\n\t{\n\t\tfor (auto &e : ids)\n\t\t\tsetPosition(v, e);\n\t}\n\n\tvoid Octree::setOrientation(const glm::quat &v, const std::array &ids)\n\t{\n\t\tfor (auto &e : ids)\n\t\t\tsetOrientation(v, e);\n\t}\n\n\tvoid Octree::setScale(const glm::vec3 &v, const std::array &ids)\n\t{\n\t\tfor (auto &e : ids)\n\t\t\tsetScale(v, e);\n\t}\n\n\tvoid Octree::updateGeometry(const OctreeKey &key\n\t\t, const AGE::Vector &meshs\n\t\t, const AGE::Vector &materials)\n\t{\n\t\tassert(!key.invalid() || key.type != OctreeKey::Type::Cullable);\n\t\t_commandQueue.emplace(key, meshs, materials);\n\t}\n\n\t\/\/-----------------------------------------------------------------\n\n\tOctree::DRAWABLE_ID Octree::addDrawableObject(Octree::USER_OBJECT_ID uid)\n\t{\n\t\tDRAWABLE_ID res = DRAWABLE_ID(-1);\n\t\tCullableObject *co = nullptr;\n\t\tif (!_freeCullableObjects.empty())\n\t\t{\n\t\t\tres = _freeCullableObjects.front();\n\t\t\t_freeCullableObjects.pop();\n\t\t\tco = &(_cullableObjects[res]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres = _cullableObjects.size();\n\t\t\t_cullableObjects.emplace_back(CullableObject());\n\t\t\tco = &(_cullableObjects.back());\n\t\t}\n\t\tco->id = res;\n\t\tco->active = true;\n\t\treturn res;\n\t}\n\n\tvoid Octree::removeDrawableObject(DRAWABLE_ID id)\n\t{\n\t\t_freeCullableObjects.push(id);\n\t\t_cullableObjects[id].active = false;\n\t\tassert(id != (std::size_t)(-1));\n\t}\n\n\n\tbool Octree::_update()\n\t{\n\t\t_commandQueue.getDispatcher()\n\t\t\t.handle([&](const OctreeCommand::CameraInfos& msg)\n\t\t{\n\t\t\tCameraObject *co = nullptr;\n\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\tco->hasMoved = true;\n\t\t\tco->projection = msg.projection;\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::CreateCamera& msg)\n\t\t{\n\t\t\tCameraObject *co = nullptr;\n\t\t\tif (msg.key.id >= _cameraObjects.size())\n\t\t\t{\n\t\t\t\t_cameraObjects.push_back(CameraObject());\n\t\t\t\tco = &_cameraObjects.back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t}\n\t\t\tco->key.id = msg.key.id;\n\t\t\tco->active = true;\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::CreateDrawable& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tif (msg.key.id >= _userObjects.size())\n\t\t\t{\n\t\t\t\t_userObjects.push_back(UserObject());\n\t\t\t\tuo = &_userObjects.back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::DeleteCamera& msg)\n\t\t{\n\t\t\tCameraObject *co = nullptr;\n\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\tco->active = false;\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::DeleteDrawable& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tuo = &this->_userObjects[msg.key.id];\n\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t{\n\t\t\t\tremoveDrawableObject(e);\n\t\t\t}\n\t\t\tuo->drawableCollection.clear();\n\t\t\tuo->active = false;\n\t\t})\n\t\t\t.handle([this](const OctreeCommand::Geometry& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\/\/assert(uo->active == true);\n\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t{\n\t\t\t\tremoveDrawableObject(e);\n\t\t\t}\n\t\t\tuo->drawableCollection.clear();\n\t\t\tfor (std::size_t i = 0; i < msg.submeshInstances.size(); ++i)\n\t\t\t{\n\t\t\t\tauto id = addDrawableObject(msg.key.id);\n\t\t\t\tuo->drawableCollection.push_back(id);\n\t\t\t\t_cullableObjects[id].mesh = msg.submeshInstances[i];\n\t\t\t\t_cullableObjects[id].material = msg.materialInstances[i];\n\t\t\t\t_cullableObjects[id].position = uo->position;\n\t\t\t\t_cullableObjects[id].orientation = uo->orientation;\n\t\t\t\t_cullableObjects[id].scale = uo->scale;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::Position& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tCameraObject *co = nullptr;\n\t\t\tswitch (msg.key.type)\n\t\t\t{\n\t\t\tcase(OctreeKey::Type::Camera) :\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t\tco->position = msg.position;\n\t\t\t\tco->hasMoved = true;\n\t\t\t\tbreak;\n\t\t\tcase(OctreeKey::Type::Cullable) :\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\tuo->position = msg.position;\n\t\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t\t{\n\t\t\t\t\t_cullableObjects[e].position = uo->position;\n\t\t\t\t\t_cullableObjects[e].hasMoved = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::Scale& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tCameraObject *co = nullptr;\n\t\t\tswitch (msg.key.type)\n\t\t\t{\n\t\t\tcase(OctreeKey::Type::Camera) :\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t\tco->scale = msg.scale;\n\t\t\t\tco->hasMoved = true;\n\t\t\t\tbreak;\n\t\t\tcase(OctreeKey::Type::Cullable) :\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\tuo->scale = msg.scale;\n\t\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t\t{\n\t\t\t\t\t_cullableObjects[e].scale = uo->scale;\n\t\t\t\t\t_cullableObjects[e].hasMoved = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::Orientation& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tCameraObject *co = nullptr;\n\t\t\tswitch (msg.key.type)\n\t\t\t{\n\t\t\tcase(OctreeKey::Type::Camera) :\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t\tco->orientation = msg.orientation;\n\t\t\t\tco->hasMoved = true;\n\t\t\t\tbreak;\n\t\t\tcase(OctreeKey::Type::Cullable) :\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\tuo->orientation = msg.orientation;\n\t\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t\t{\n\t\t\t\t\t_cullableObjects[e].orientation = uo->orientation;\n\t\t\t\t\t_cullableObjects[e].hasMoved = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const TMQ::CloseQueue& msg)\n\t\t{\n\t\t\t_isRunning = false;\n\t\t\treturn false;\n\t\t}).handle([&](OctreeCommand::PrepareDrawLists& msg)\n\t\t{\n\t\t\tstatic std::size_t cameraCounter = 0; cameraCounter = 0;\n\n\t\t\tfor (auto &camera : _cameraObjects)\n\t\t\t{\n\t\t\t\tif (!camera.active)\n\t\t\t\t\tcontinue;\n\t\t\t\tFrustum frustum;\n\t\t\t\tauto transformation = glm::scale(glm::translate(glm::mat4(1), camera.position) * glm::toMat4(camera.orientation), camera.scale);\n\t\t\t\tfrustum.setMatrix(camera.projection * transformation, true);\n\n\t\t\t\t_octreeDrawList.emplace_back();\n\t\t\t\tauto &drawList = _octreeDrawList.back();\n\n\t\t\t\tdrawList.drawables.clear();\n\n\t\t\t\tdrawList.transformation = transformation;\n\t\t\t\tdrawList.projection = camera.projection;\n\n\t\t\t\tstd::size_t drawed = 0; std::size_t total = 0;\n\n\t\t\t\tfor (auto &e : _cullableObjects)\n\t\t\t\t{\n\t\t\t\t\tif (e.active)\n\t\t\t\t\t\t++total;\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (frustum.pointIn(e.position) == true)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (e.hasMoved)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\te.transformation = glm::scale(glm::translate(glm::mat4(1), e.position) * glm::toMat4(e.orientation), e.scale);\n\t\t\t\t\t\t\te.hasMoved = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdrawList.drawables.emplace_back(e.mesh, e.material, e.transformation);\n\t\t\t\t\t\t++drawed;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++cameraCounter;\n\t\t\t}\n\n\t\t\tauto renderThread = getDependencyManager().lock()->getInstance();\n\t\t\tfor (auto &e : this->_octreeDrawList)\n\t\t\t{\n\t\t\t\trenderThread->getCommandQueue().safeEmplace([=](){\n\t\t\t\t\tmsg.function(e);\n\t\t\t\t});\n\t\t\t}\n\t\t\t_octreeDrawList.clear();\n\t\t\trenderThread->getCommandQueue().safeEmplace();\n\t\t\trenderThread->getCommandQueue().releaseReadability();\n\n\t\t\t\/\/msg.result.set_value(std::move(_octreeDrawList));\n\t\t\t\/\/_octreeDrawList.clear();\n\t\t});\n\n\t\treturn true;\n\t}\n\n}warning : i just correct tow little warning by casting a value 64bit into 32 bit maybe it's not what you would like, can you confirm ?#include \"Octree.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace AGE\n{\n\tOctree::Octree()\n\t{\n\t}\n\n\tOctree::~Octree(void)\n\t{\n\t\t_commandQueue.emplace();\n\t\t_commandQueue.releaseReadability();\n\t}\n\n\tbool Octree::_init()\n\t{\n\t\t_octreeDrawList = AGE::Vector();\n\t\treturn true;\n\t}\n\n\tbool Octree::_initInNewThread()\n\t{\n\t\treturn true;\n\t}\n\n\tbool Octree::_release()\n\t{\n\t\treturn true;\n\t}\n\n\tbool Octree::_releaseInNewThread()\n\t{\n\t\treturn true;\n\t}\n\n\tconst OctreeKey &Octree::addCullableElement()\n\t{\n\t\tOctreeKey res;\n\t\tres.type = OctreeKey::Type::Cullable;\n\t\tif (!_freeUserObjects.empty())\n\t\t{\n\t\t\tres.id = _freeUserObjects.front();\n\t\t\t_freeUserObjects.pop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres.id = uint32_t(_userObjectCounter++);\n\t\t}\n\n\t\t_commandQueue.emplace(res);\n\t\treturn res;\n\t}\n\n\tvoid Octree::removeElement(const OctreeKey &key)\n\t{\n\t\tassert(!key.invalid());\n\t\tswitch (key.type)\n\t\t{\n\t\tcase(OctreeKey::Type::Camera) :\n\t\t{\n\t\t\t_freeCameraObjects.push(key.id);\n\t\t\t_commandQueue.emplace(key);\n\t\t}\n\t\t\t\t\t\t\t\t\t break;\n\t\tcase(OctreeKey::Type::Cullable) :\n\t\t{\n\t\t\t_freeUserObjects.push(key.id);\n\t\t\t_commandQueue.emplace(key);\n\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst OctreeKey &Octree::addCameraElement()\n\t{\n\t\tOctreeKey res;\n\t\tres.type = OctreeKey::Type::Camera;\n\t\tif (!_freeCameraObjects.empty())\n\t\t{\n\t\t\tres.id = _freeCameraObjects.front();\n\t\t\t_freeCameraObjects.pop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres.id = _cameraCounter++;\n\t\t}\n\t\t_commandQueue.emplace(res);\n\n\t\treturn res;\n\t}\n\n\tvoid Octree::setPosition(const glm::vec3 &v, const OctreeKey &id)\n\t{\n\t\t_commandQueue.emplace(id, v);\n\t}\n\tvoid Octree::setOrientation(const glm::quat &v, const OctreeKey &id)\n\t{\n\t\t_commandQueue.emplace(id, v);\n\t}\n\n\tvoid Octree::setScale(const glm::vec3 &v, const OctreeKey &id)\n\t{\n\t\t_commandQueue.emplace(id, v);\n\t}\n\n\tvoid Octree::setCameraInfos(const OctreeKey &id\n\t\t, const glm::mat4 &projection)\n\t{\n\t\t_commandQueue.emplace(id, projection);\n\t}\n\n\tvoid Octree::setPosition(const glm::vec3 &v, const std::array &ids)\n\t{\n\t\tfor (auto &e : ids)\n\t\t\tsetPosition(v, e);\n\t}\n\n\tvoid Octree::setOrientation(const glm::quat &v, const std::array &ids)\n\t{\n\t\tfor (auto &e : ids)\n\t\t\tsetOrientation(v, e);\n\t}\n\n\tvoid Octree::setScale(const glm::vec3 &v, const std::array &ids)\n\t{\n\t\tfor (auto &e : ids)\n\t\t\tsetScale(v, e);\n\t}\n\n\tvoid Octree::updateGeometry(const OctreeKey &key\n\t\t, const AGE::Vector &meshs\n\t\t, const AGE::Vector &materials)\n\t{\n\t\tassert(!key.invalid() || key.type != OctreeKey::Type::Cullable);\n\t\t_commandQueue.emplace(key, meshs, materials);\n\t}\n\n\t\/\/-----------------------------------------------------------------\n\n\tOctree::DRAWABLE_ID Octree::addDrawableObject(Octree::USER_OBJECT_ID uid)\n\t{\n\t\tDRAWABLE_ID res = DRAWABLE_ID(-1);\n\t\tCullableObject *co = nullptr;\n\t\tif (!_freeCullableObjects.empty())\n\t\t{\n\t\t\tres = _freeCullableObjects.front();\n\t\t\t_freeCullableObjects.pop();\n\t\t\tco = &(_cullableObjects[res]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres = _cullableObjects.size();\n\t\t\t_cullableObjects.emplace_back(CullableObject());\n\t\t\tco = &(_cullableObjects.back());\n\t\t}\n\t\tco->id = res;\n\t\tco->active = true;\n\t\treturn res;\n\t}\n\n\tvoid Octree::removeDrawableObject(DRAWABLE_ID id)\n\t{\n\t\t_freeCullableObjects.push(uint32_t(id));\n\t\t_cullableObjects[id].active = false;\n\t\tassert(id != (std::size_t)(-1));\n\t}\n\n\n\tbool Octree::_update()\n\t{\n\t\t_commandQueue.getDispatcher()\n\t\t\t.handle([&](const OctreeCommand::CameraInfos& msg)\n\t\t{\n\t\t\tCameraObject *co = nullptr;\n\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\tco->hasMoved = true;\n\t\t\tco->projection = msg.projection;\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::CreateCamera& msg)\n\t\t{\n\t\t\tCameraObject *co = nullptr;\n\t\t\tif (msg.key.id >= _cameraObjects.size())\n\t\t\t{\n\t\t\t\t_cameraObjects.push_back(CameraObject());\n\t\t\t\tco = &_cameraObjects.back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t}\n\t\t\tco->key.id = msg.key.id;\n\t\t\tco->active = true;\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::CreateDrawable& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tif (msg.key.id >= _userObjects.size())\n\t\t\t{\n\t\t\t\t_userObjects.push_back(UserObject());\n\t\t\t\tuo = &_userObjects.back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::DeleteCamera& msg)\n\t\t{\n\t\t\tCameraObject *co = nullptr;\n\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\tco->active = false;\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::DeleteDrawable& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tuo = &this->_userObjects[msg.key.id];\n\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t{\n\t\t\t\tremoveDrawableObject(e);\n\t\t\t}\n\t\t\tuo->drawableCollection.clear();\n\t\t\tuo->active = false;\n\t\t})\n\t\t\t.handle([this](const OctreeCommand::Geometry& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\/\/assert(uo->active == true);\n\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t{\n\t\t\t\tremoveDrawableObject(e);\n\t\t\t}\n\t\t\tuo->drawableCollection.clear();\n\t\t\tfor (std::size_t i = 0; i < msg.submeshInstances.size(); ++i)\n\t\t\t{\n\t\t\t\tauto id = addDrawableObject(msg.key.id);\n\t\t\t\tuo->drawableCollection.push_back(id);\n\t\t\t\t_cullableObjects[id].mesh = msg.submeshInstances[i];\n\t\t\t\t_cullableObjects[id].material = msg.materialInstances[i];\n\t\t\t\t_cullableObjects[id].position = uo->position;\n\t\t\t\t_cullableObjects[id].orientation = uo->orientation;\n\t\t\t\t_cullableObjects[id].scale = uo->scale;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::Position& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tCameraObject *co = nullptr;\n\t\t\tswitch (msg.key.type)\n\t\t\t{\n\t\t\tcase(OctreeKey::Type::Camera) :\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t\tco->position = msg.position;\n\t\t\t\tco->hasMoved = true;\n\t\t\t\tbreak;\n\t\t\tcase(OctreeKey::Type::Cullable) :\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\tuo->position = msg.position;\n\t\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t\t{\n\t\t\t\t\t_cullableObjects[e].position = uo->position;\n\t\t\t\t\t_cullableObjects[e].hasMoved = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::Scale& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tCameraObject *co = nullptr;\n\t\t\tswitch (msg.key.type)\n\t\t\t{\n\t\t\tcase(OctreeKey::Type::Camera) :\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t\tco->scale = msg.scale;\n\t\t\t\tco->hasMoved = true;\n\t\t\t\tbreak;\n\t\t\tcase(OctreeKey::Type::Cullable) :\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\tuo->scale = msg.scale;\n\t\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t\t{\n\t\t\t\t\t_cullableObjects[e].scale = uo->scale;\n\t\t\t\t\t_cullableObjects[e].hasMoved = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const OctreeCommand::Orientation& msg)\n\t\t{\n\t\t\tUserObject *uo = nullptr;\n\t\t\tCameraObject *co = nullptr;\n\t\t\tswitch (msg.key.type)\n\t\t\t{\n\t\t\tcase(OctreeKey::Type::Camera) :\n\t\t\t\tco = &_cameraObjects[msg.key.id];\n\t\t\t\tco->orientation = msg.orientation;\n\t\t\t\tco->hasMoved = true;\n\t\t\t\tbreak;\n\t\t\tcase(OctreeKey::Type::Cullable) :\n\t\t\t\tuo = &_userObjects[msg.key.id];\n\t\t\t\tuo->orientation = msg.orientation;\n\t\t\t\tfor (auto &e : uo->drawableCollection)\n\t\t\t\t{\n\t\t\t\t\t_cullableObjects[e].orientation = uo->orientation;\n\t\t\t\t\t_cullableObjects[e].hasMoved = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t})\n\t\t\t.handle([&](const TMQ::CloseQueue& msg)\n\t\t{\n\t\t\t_isRunning = false;\n\t\t\treturn false;\n\t\t}).handle([&](OctreeCommand::PrepareDrawLists& msg)\n\t\t{\n\t\t\tstatic std::size_t cameraCounter = 0; cameraCounter = 0;\n\n\t\t\tfor (auto &camera : _cameraObjects)\n\t\t\t{\n\t\t\t\tif (!camera.active)\n\t\t\t\t\tcontinue;\n\t\t\t\tFrustum frustum;\n\t\t\t\tauto transformation = glm::scale(glm::translate(glm::mat4(1), camera.position) * glm::toMat4(camera.orientation), camera.scale);\n\t\t\t\tfrustum.setMatrix(camera.projection * transformation, true);\n\n\t\t\t\t_octreeDrawList.emplace_back();\n\t\t\t\tauto &drawList = _octreeDrawList.back();\n\n\t\t\t\tdrawList.drawables.clear();\n\n\t\t\t\tdrawList.transformation = transformation;\n\t\t\t\tdrawList.projection = camera.projection;\n\n\t\t\t\tstd::size_t drawed = 0; std::size_t total = 0;\n\n\t\t\t\tfor (auto &e : _cullableObjects)\n\t\t\t\t{\n\t\t\t\t\tif (e.active)\n\t\t\t\t\t\t++total;\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (frustum.pointIn(e.position) == true)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (e.hasMoved)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\te.transformation = glm::scale(glm::translate(glm::mat4(1), e.position) * glm::toMat4(e.orientation), e.scale);\n\t\t\t\t\t\t\te.hasMoved = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdrawList.drawables.emplace_back(e.mesh, e.material, e.transformation);\n\t\t\t\t\t\t++drawed;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++cameraCounter;\n\t\t\t}\n\n\t\t\tauto renderThread = getDependencyManager().lock()->getInstance();\n\t\t\tfor (auto &e : this->_octreeDrawList)\n\t\t\t{\n\t\t\t\trenderThread->getCommandQueue().safeEmplace([=](){\n\t\t\t\t\tmsg.function(e);\n\t\t\t\t});\n\t\t\t}\n\t\t\t_octreeDrawList.clear();\n\t\t\trenderThread->getCommandQueue().safeEmplace();\n\t\t\trenderThread->getCommandQueue().releaseReadability();\n\n\t\t\t\/\/msg.result.set_value(std::move(_octreeDrawList));\n\t\t\t\/\/_octreeDrawList.clear();\n\t\t});\n\n\t\treturn true;\n\t}\n\n}<|endoftext|>"} {"text":"\/\/ coding: utf-8\n\/\/ ----------------------------------------------------------------------------\n\/* Copyright (c) 2009, Roboterclub Aachen e.V.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Roboterclub Aachen e.V. nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef\tXPCC__ANGLE_HPP\n#define\tXPCC__ANGLE_HPP\n\n#include \n\n\/\/ The circumference of a circle with diameter 1\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#ifndef M_PI_2\n#define M_PI_2 (M_PI\/2.0)\n#endif\n\n\/\/ The square root of 2.\n#ifndef M_SQRT2 \n#define M_SQRT2 1.41421356237309504880 \n#endif \n\nnamespace xpcc\n{\n\t\/**\n\t * \\brief\tCollection of functions for handling of angles\n\t * \n\t * Angles are always represented by float values in the range\n\t * from -Pi to Pi.\n\t * \n\t * \\ingroup\tgeometry\n\t *\/\n\tclass Angle\n\t{\n\tpublic:\n\t\ttypedef float Type;\n\t\t\n\t\t\/**\n\t\t * \\brief\tNormalize angle\n\t\t * \n\t\t * Normalize the given angle to [-Pi,Pi] by repeatedly\n\t\t * adding\/subtracting 2*Pi.\n\t\t *\/\n\t\tstatic float\n\t\tnormalize(float angle);\n\t\t\n\t\t\/**\n\t\t * \\brief\tReverse the angle\n\t\t * \n\t\t * Reverse the angle and keep it normalized to [-Pi,Pi].\n\t\t * \n\t\t * Equivalent to:\n\t\t * \\code\n\t\t * float angle = xpcc::Angle::normalize(angle + M_PI);\n\t\t * \\endcode\n\t\t *\/\n\t\tstatic float\n\t\treverse(float angle);\n\t\t\n\t\t\/**\n\t\t * \\brief\tFind a perpendicular angle\n\t\t *\n\t\t * \\param\tangle\n\t\t * \\param\tcw\tIf cw is true the angle is rotated clockwise.\n\t\t * \t\t\t\tOhterwise the angle is rotated anti clockwise.\n\t\t *\/\n\n\t\tstatic float\n\t\tperpendicular(float angle, const bool cw);\n\t\t\n\t\tstatic inline float\n\t\ttoRadian(float angle)\n\t\t{\n\t\t\treturn (angle * M_PI) \/ 180.0;\n\t\t}\n\t\t\n\t\tstatic inline float\n\t\ttoDegree(float angle)\n\t\t{\n\t\t\treturn (angle * 180.0) \/ M_PI;\n\t\t}\n\t};\n}\n\n#endif\t\/\/ XPCC__ANGLE_HPP\nAdd some constants derived from Pi\/\/ coding: utf-8\n\/\/ ----------------------------------------------------------------------------\n\/* Copyright (c) 2009, Roboterclub Aachen e.V.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Roboterclub Aachen e.V. nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef\tXPCC__ANGLE_HPP\n#define\tXPCC__ANGLE_HPP\n\n#include \n#include \n\n\/\/ The circumference of a circle with diameter 1\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#ifndef M_PI_2\n#define M_PI_2 1.57079632679489661923\n#endif\n\n#ifndef M_PI_4\n#define M_PI_4 0.78539816339744830962\n#endif\n\n#ifndef M_TWOPI\n#define M_TWOPI (M_PI * 2.0)\n#endif\n\n#ifndef M_1_PI\n#define M_1_PI 0.31830988618379067154\n#endif\n\n#ifdef M_2_PI\n#define M_2_PI 0.63661977236758134308\n#endif\n\n\/\/ The square root of 2.\n#ifndef M_SQRT2 \n#define M_SQRT2 1.41421356237309504880 \n#endif \n\nnamespace xpcc\n{\n\t\/**\n\t * \\brief\tCollection of functions for handling of angles\n\t * \n\t * Angles are always represented by float values in the range\n\t * from -Pi to Pi.\n\t * \n\t * \\ingroup\tgeometry\n\t *\/\n\tclass Angle\n\t{\n\tpublic:\n\t\ttypedef float Type;\n\t\t\n\t\t\/**\n\t\t * \\brief\tNormalize angle\n\t\t * \n\t\t * Normalize the given angle to [-Pi,Pi] by repeatedly\n\t\t * adding\/subtracting 2*Pi.\n\t\t *\/\n\t\tstatic float\n\t\tnormalize(float angle);\n\t\t\n\t\t\/**\n\t\t * \\brief\tReverse the angle\n\t\t * \n\t\t * Reverse the angle and keep it normalized to [-Pi,Pi].\n\t\t * \n\t\t * Equivalent to:\n\t\t * \\code\n\t\t * float angle = xpcc::Angle::normalize(angle + M_PI);\n\t\t * \\endcode\n\t\t *\/\n\t\tstatic float\n\t\treverse(float angle);\n\t\t\n\t\t\/**\n\t\t * \\brief\tFind a perpendicular angle\n\t\t *\n\t\t * \\param\tangle\n\t\t * \\param\tcw\tIf cw is true the angle is rotated clockwise.\n\t\t * \t\t\t\tOhterwise the angle is rotated anti clockwise.\n\t\t *\/\n\n\t\tstatic float\n\t\tperpendicular(float angle, const bool cw);\n\t\t\n\t\tstatic inline float\n\t\ttoRadian(float angle)\n\t\t{\n\t\t\treturn (angle * M_PI) \/ 180.0;\n\t\t}\n\t\t\n\t\tstatic inline float\n\t\ttoDegree(float angle)\n\t\t{\n\t\t\treturn (angle * 180.0) \/ M_PI;\n\t\t}\n\t};\n}\n\n#endif\t\/\/ XPCC__ANGLE_HPP\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ cache_test.cpp\n\/\/\n\/\/ Identification: tests\/common\/cache_test.cpp\n\/\/\n\/\/ Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n#include \"backend\/common\/cache.h\"\n#include \"backend\/common\/logger.h\"\n#include \"backend\/planner\/mock_plan.h\"\n\n#include \n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Cache Test\n\/\/===--------------------------------------------------------------------===\/\/\n\n#define CACHE_SIZE 5\n\n\n\/**\n * Test basic functionality\n *\n *\/\nTEST(CacheTest, Basic) {\n\n Cache cache(CACHE_SIZE);\n\n EXPECT_EQ(0, cache.size());\n}\n\n\/**\n * Test find operation\n *\n *\/\nTEST(CacheTest, Find) {\n Cache cache(CACHE_SIZE);\n\n EXPECT_EQ(cache.end(), cache.find(1));\n}\n\n\n\/**\n * Test insert operation\n *\n *\/\nTEST(CacheTest, Insert) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE];\n\n cache.insert(std::make_pair(0, plans));\n\n auto cache_it = cache.find(0);\n\n EXPECT_EQ(*cache_it, plans);\n\n for (int i = 1; i < CACHE_SIZE; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n EXPECT_EQ(CACHE_SIZE, cache.size());\n}\n\n\/**\n * Test iterator function\n *\/\nTEST(CacheTest, Iterator) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE];\n std::unordered_set set;\n\n for (int i = 0; i < CACHE_SIZE; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n for (int i = 0; i < CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\/**\n * Test eviction\n *\n * Try to insert 2 times of the capacity of the cache\n * The cache should keep the most recent half\n *\/\nTEST(CacheTest, EvictionByInsert) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE * 2];\n std::unordered_set set;\n\n for (int i = 0; i < 2 * CACHE_SIZE; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n for (int i = 0; i < CACHE_SIZE; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (int i = CACHE_SIZE; i < 2 * CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\/**\n * Test eviction\n *\n * Try to insert 2 times of the capacity of the cache\n * The cache should keep the most recent half\n *\/\nTEST(CacheTest, EvictionWithAccessing) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE * 2];\n std::unordered_set set;\n\n int i = 0;\n \/* insert 0,1,2,3,4,5,6,7\n *\n * The cache should keep 3,4,5,6,7\n * *\/\n for (; i < CACHE_SIZE * 1.5; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n\n int diff = CACHE_SIZE \/ 2;\n\n \/* read 4, 3\n * *\/\n for (int idx = CACHE_SIZE - 1; idx > CACHE_SIZE - diff - 1; idx--) {\n auto it = cache.find(idx);\n EXPECT_NE(it, cache.end());\n EXPECT_EQ(*it, plans + idx);\n }\n\n \/* Insert 8, 9 *\/\n for (; i < CACHE_SIZE * 2; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.clear();\n set.insert(cache.begin(), cache.end());\n\n for (auto it : set) {\n LOG_INFO(\"%lu\", it - reinterpret_cast(&plans[0]));\n }\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n\n i = 0;\n for (; i < CACHE_SIZE - diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE + diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE * 2; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n\n i = 0;\n for (; i < CACHE_SIZE; i++) {\n cache.insert(std::make_pair(i, plans + i));\n }\n\n set.clear();\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, cache.size());\n\n i = 0;\n for (; i < CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\n\/**\n * Test eviction\n *\n * Try to insert 2 times of the capacity of the cache\n * The cache should keep the most recent half\n *\/\nTEST(CacheTest, Updating) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE * 2];\n\n std::unordered_set set;\n\n \/* insert 0,1,2,3,4,5,6,7\n *\n * The cache should keep 3,4,5,6,7\n * *\/\n int i = 0;\n for (; i < CACHE_SIZE * 1.5; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n\n int diff = CACHE_SIZE \/ 2;\n\n MockPlan plans2[diff];\n\n \/* update 4, 3\n * *\/\n for (int idx = CACHE_SIZE - 1, j = 0; idx > CACHE_SIZE - diff - 1; idx--, j++) {\n cache.insert(std::make_pair(idx, plans2 + j));\n }\n\n for (; i < CACHE_SIZE * 2; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.clear();\n set.insert(cache.begin(), cache.end());\n\n for (auto it : set) {\n LOG_INFO(\"%lu\", it - reinterpret_cast(&plans[0]));\n }\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n\n i = 0;\n for (; i < CACHE_SIZE - diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (int j = 0; i < CACHE_SIZE; i++, j++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n EXPECT_NE(set.end(), set.find(plans2 + j));\n }\n\n for (; i < CACHE_SIZE + diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE * 2; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\n\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\nadd test for empty\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ cache_test.cpp\n\/\/\n\/\/ Identification: tests\/common\/cache_test.cpp\n\/\/\n\/\/ Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n#include \"backend\/common\/cache.h\"\n#include \"backend\/common\/logger.h\"\n#include \"backend\/planner\/mock_plan.h\"\n\n#include \n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Cache Test\n\/\/===--------------------------------------------------------------------===\/\/\n\n#define CACHE_SIZE 5\n\n\n\/**\n * Test basic functionality\n *\n *\/\nTEST(CacheTest, Basic) {\n\n Cache cache(CACHE_SIZE);\n\n EXPECT_EQ(0, cache.size());\n EXPECT_EQ(true, cache.empty());\n}\n\n\/**\n * Test find operation\n *\n *\/\nTEST(CacheTest, Find) {\n Cache cache(CACHE_SIZE);\n\n EXPECT_EQ(cache.end(), cache.find(1));\n}\n\n\n\/**\n * Test insert operation\n *\n *\/\nTEST(CacheTest, Insert) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE];\n\n cache.insert(std::make_pair(0, plans));\n\n auto cache_it = cache.find(0);\n\n EXPECT_EQ(*cache_it, plans);\n\n for (int i = 1; i < CACHE_SIZE; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n EXPECT_EQ(CACHE_SIZE, cache.size());\n EXPECT_EQ(false, cache.empty());\n}\n\n\/**\n * Test iterator function\n *\/\nTEST(CacheTest, Iterator) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE];\n std::unordered_set set;\n\n for (int i = 0; i < CACHE_SIZE; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n EXPECT_EQ(false, cache.empty());\n for (int i = 0; i < CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\/**\n * Test eviction\n *\n * Try to insert 2 times of the capacity of the cache\n * The cache should keep the most recent half\n *\/\nTEST(CacheTest, EvictionByInsert) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE * 2];\n std::unordered_set set;\n\n for (int i = 0; i < 2 * CACHE_SIZE; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n EXPECT_EQ(false, cache.empty());\n for (int i = 0; i < CACHE_SIZE; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (int i = CACHE_SIZE; i < 2 * CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\/**\n * Test eviction\n *\n * Try to insert 2 times of the capacity of the cache\n * The cache should keep the most recent half\n *\/\nTEST(CacheTest, EvictionWithAccessing) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE * 2];\n std::unordered_set set;\n\n int i = 0;\n \/* insert 0,1,2,3,4,5,6,7\n *\n * The cache should keep 3,4,5,6,7\n * *\/\n for (; i < CACHE_SIZE * 1.5; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n EXPECT_EQ(false, cache.empty());\n\n int diff = CACHE_SIZE \/ 2;\n\n \/* read 4, 3\n * *\/\n for (int idx = CACHE_SIZE - 1; idx > CACHE_SIZE - diff - 1; idx--) {\n auto it = cache.find(idx);\n EXPECT_NE(it, cache.end());\n EXPECT_EQ(*it, plans + idx);\n }\n\n \/* Insert 8, 9 *\/\n for (; i < CACHE_SIZE * 2; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.clear();\n set.insert(cache.begin(), cache.end());\n\n for (auto it : set) {\n LOG_INFO(\"%lu\", it - reinterpret_cast(&plans[0]));\n }\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n EXPECT_EQ(false, cache.empty());\n\n i = 0;\n for (; i < CACHE_SIZE - diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE + diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE * 2; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n\n i = 0;\n for (; i < CACHE_SIZE; i++) {\n cache.insert(std::make_pair(i, plans + i));\n }\n\n set.clear();\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, cache.size());\n EXPECT_EQ(false, cache.empty());\n\n i = 0;\n for (; i < CACHE_SIZE; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\n\/**\n * Test eviction\n *\n * Try to insert 2 times of the capacity of the cache\n * The cache should keep the most recent half\n *\/\nTEST(CacheTest, Updating) {\n Cache cache(CACHE_SIZE);\n\n MockPlan plans[CACHE_SIZE * 2];\n\n std::unordered_set set;\n\n \/* insert 0,1,2,3,4,5,6,7\n *\n * The cache should keep 3,4,5,6,7\n * *\/\n int i = 0;\n for (; i < CACHE_SIZE * 1.5; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.insert(cache.begin(), cache.end());\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n EXPECT_EQ(false, cache.empty());\n\n int diff = CACHE_SIZE \/ 2;\n\n MockPlan plans2[diff];\n\n \/* update 4, 3\n * *\/\n for (int idx = CACHE_SIZE - 1, j = 0; idx > CACHE_SIZE - diff - 1; idx--, j++) {\n cache.insert(std::make_pair(idx, plans2 + j));\n }\n\n for (; i < CACHE_SIZE * 2; i++)\n cache.insert(std::make_pair(i, plans + i));\n\n set.clear();\n set.insert(cache.begin(), cache.end());\n\n for (auto it : set) {\n LOG_INFO(\"%lu\", it - reinterpret_cast(&plans[0]));\n }\n\n EXPECT_EQ(CACHE_SIZE, set.size());\n EXPECT_EQ(false, cache.empty());\n\n i = 0;\n for (; i < CACHE_SIZE - diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (int j = 0; i < CACHE_SIZE; i++, j++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n EXPECT_NE(set.end(), set.find(plans2 + j));\n }\n\n for (; i < CACHE_SIZE + diff; i++) {\n EXPECT_EQ(set.end(), set.find(plans + i));\n }\n\n for (; i < CACHE_SIZE * 2; i++) {\n EXPECT_NE(set.end(), set.find(plans + i));\n }\n}\n\n\n\n\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n\n\/*\n * The tests in this file are here to catch any branches of code that\n * are not picked up by the main tests testing the API of the library\n *\/\nTEST(Coverage, connectionComment)\n{\n const std::string in =\n \"\\n\"\n \"\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/component>\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/map_variables>\\n\"\n \" <\/connection>\\n\"\n \"<\/model>\\n\";\n\n libcellml::Parser p;\n p.parseModel(in);\n EXPECT_EQ(size_t(4), p.errorCount());\n}\n\nTEST(Coverage, import)\n{\n const std::string e;\n libcellml::ImportSource i;\n libcellml::ImportSource im;\n\n im = std::move(i);\n\n \/\/ Copy constructor\n libcellml::ImportSource ic(im);\n\n const std::string a = ic.id();\n EXPECT_EQ(e, a);\n}\n\nTEST(Coverage, importWithNonHrefXlink)\n{\n const std::string e =\n \"\\n\"\n \"\\n\"\n \" \\n\"\n \" \\n\"\n \" \\n\"\n \" <\/import>\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/component>\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/connection>\\n\"\n \"<\/model>\\n\";\n\n \/\/ Parse\n libcellml::Parser parser;\n parser.parseModel(e);\n EXPECT_EQ(size_t(0), parser.errorCount());\n \/\/ EXPECT_EQ(\"bob\", parser.error(0)->description());\n}\n\nTEST(Coverage, printer)\n{\n libcellml::Printer p;\n libcellml::Printer pm;\n\n pm = std::move(p);\n\n \/\/ Copy constructor\n libcellml::Printer pc(pm);\n\n size_t error_count = pc.errorCount();\n EXPECT_EQ(size_t(0), error_count);\n}\n\nTEST(Coverage, units)\n{\n const std::string e = \"\\n\";\n libcellml::Units u;\n libcellml::Units um;\n\n u.setName(\"dimensionless\");\n\n um = std::move(u);\n\n \/\/ Copy constructor\n libcellml::Units uc(um);\n\n EXPECT_EQ(\"dimensionless\", uc.name());\n}\n\nTEST(Coverage, when)\n{\n const std::string randomValue = \"4738\";\n\n libcellml::When w;\n libcellml::When wm;\n libcellml::Reset r;\n\n w.setValue(randomValue);\n wm = std::move(w);\n\n libcellml::When wc(wm);\n\n libcellml::WhenPtr wp = std::make_shared(wc);\n r.addWhen(wp);\n\n EXPECT_EQ(randomValue, wc.value());\n}\n\nTEST(Coverage, unitsGetVariations)\n{\n libcellml::Model m;\n\n libcellml::UnitsPtr u = std::make_shared();\n u->setName(\"a_unit\");\n\n u->addUnit(libcellml::Units::StandardUnit::AMPERE, \"micro\");\n m.addUnits(u);\n\n libcellml::UnitsPtr un = m.units(0);\n EXPECT_EQ(\"a_unit\", un->name());\n libcellml::UnitsPtr uSn = static_cast(m).units(0);\n EXPECT_EQ(\"a_unit\", uSn->name());\n\n libcellml::UnitsPtr uns = m.units(\"a_unit\");\n EXPECT_EQ(\"a_unit\", uns->name());\n libcellml::UnitsPtr uSns = static_cast(m).units(\"a_unit\");\n EXPECT_EQ(\"a_unit\", uSns->name());\n\n EXPECT_EQ(nullptr, m.units(\"b_unit\"));\n EXPECT_EQ(nullptr, m.units(4));\n}\n\nTEST(Coverage, prefixToString)\n{\n libcellml::Model m;\n libcellml::Printer printer;\n\n std::vector prefixString =\n {\"atto\",\n \"centi\",\n \"deca\",\n \"deci\",\n \"exa\",\n \"femto\",\n \"giga\",\n \"hecto\",\n \"kilo\",\n \"mega\",\n \"micro\",\n \"milli\",\n \"nano\",\n \"peta\",\n \"pico\",\n \"tera\",\n \"yocto\",\n \"yotta\",\n \"zepto\",\n \"zetta\"};\n std::vector prefixEnum =\n {libcellml::Prefix::ATTO,\n libcellml::Prefix::CENTI,\n libcellml::Prefix::DECA,\n libcellml::Prefix::DECI,\n libcellml::Prefix::EXA,\n libcellml::Prefix::FEMTO,\n libcellml::Prefix::GIGA,\n libcellml::Prefix::HECTO,\n libcellml::Prefix::KILO,\n libcellml::Prefix::MEGA,\n libcellml::Prefix::MICRO,\n libcellml::Prefix::MILLI,\n libcellml::Prefix::NANO,\n libcellml::Prefix::PETA,\n libcellml::Prefix::PICO,\n libcellml::Prefix::TERA,\n libcellml::Prefix::YOCTO,\n libcellml::Prefix::YOTTA,\n libcellml::Prefix::ZEPTO,\n libcellml::Prefix::ZETTA};\n for (std::vector::size_type i = 0; i != prefixString.size(); ++i) {\n libcellml::UnitsPtr u = std::make_shared();\n u->setName(\"abcdefg\");\n u->addUnit(\"empty\", prefixEnum[i]);\n\n m.addUnits(u);\n\n const std::string a = printer.printModel(m);\n std::size_t found = a.find(prefixString[i]);\n EXPECT_NE(std::string::npos, found);\n m.removeAllUnits();\n }\n}\n\nTEST(Coverage, variable)\n{\n const std::string e = \"\\n\";\n const std::string dimensionless = \"dimensionless\";\n libcellml::Variable v;\n libcellml::Variable vm;\n libcellml::UnitsPtr u = std::make_shared();\n\n v.setInitialValue(1.0);\n v.setInterfaceType(\"public\");\n u->setName(dimensionless);\n v.setUnits(u);\n\n vm = std::move(v);\n\n \/\/ Copy constructor\n libcellml::Variable vc(vm);\n\n EXPECT_EQ(dimensionless, vc.units());\n}\n\nTEST(Coverage, component)\n{\n const std::string math = \"<1+1=2>\\n\";\n libcellml::Component c;\n libcellml::Component cm;\n libcellml::VariablePtr v = std::make_shared();\n\n c.setName(\"name\");\n c.addVariable(v);\n c.setMath(math);\n\n EXPECT_EQ(size_t(1), c.variableCount());\n\n cm = std::move(c);\n EXPECT_EQ(size_t(1), cm.variableCount());\n\n \/\/ Copy constructor\n libcellml::Component cc(cm);\n EXPECT_EQ(size_t(1), cc.variableCount());\n}\n\nTEST(Coverage, error)\n{\n libcellml::ErrorPtr err = std::make_shared();\n libcellml::Error e;\n libcellml::Error em;\n const std::string description = \"test\";\n\n e.setDescription(description);\n e.setKind(libcellml::Error::Kind::XML);\n\n em = std::move(e);\n \/\/ Copy constructor\n libcellml::Error ec(em);\n\n EXPECT_EQ(description, ec.description());\n EXPECT_EQ(libcellml::Error::Kind::XML, ec.kind());\n}\nRemove commented out line in coverage test.\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n\n\/*\n * The tests in this file are here to catch any branches of code that\n * are not picked up by the main tests testing the API of the library\n *\/\nTEST(Coverage, connectionComment)\n{\n const std::string in =\n \"\\n\"\n \"\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/component>\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/map_variables>\\n\"\n \" <\/connection>\\n\"\n \"<\/model>\\n\";\n\n libcellml::Parser p;\n p.parseModel(in);\n EXPECT_EQ(size_t(4), p.errorCount());\n}\n\nTEST(Coverage, import)\n{\n const std::string e;\n libcellml::ImportSource i;\n libcellml::ImportSource im;\n\n im = std::move(i);\n\n \/\/ Copy constructor\n libcellml::ImportSource ic(im);\n\n const std::string a = ic.id();\n EXPECT_EQ(e, a);\n}\n\nTEST(Coverage, importWithNonHrefXlink)\n{\n const std::string e =\n \"\\n\"\n \"\\n\"\n \" \\n\"\n \" \\n\"\n \" \\n\"\n \" <\/import>\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/component>\\n\"\n \" \\n\"\n \" \\n\"\n \" <\/connection>\\n\"\n \"<\/model>\\n\";\n\n \/\/ Parse\n libcellml::Parser parser;\n parser.parseModel(e);\n EXPECT_EQ(size_t(0), parser.errorCount());\n}\n\nTEST(Coverage, printer)\n{\n libcellml::Printer p;\n libcellml::Printer pm;\n\n pm = std::move(p);\n\n \/\/ Copy constructor\n libcellml::Printer pc(pm);\n\n size_t error_count = pc.errorCount();\n EXPECT_EQ(size_t(0), error_count);\n}\n\nTEST(Coverage, units)\n{\n const std::string e = \"\\n\";\n libcellml::Units u;\n libcellml::Units um;\n\n u.setName(\"dimensionless\");\n\n um = std::move(u);\n\n \/\/ Copy constructor\n libcellml::Units uc(um);\n\n EXPECT_EQ(\"dimensionless\", uc.name());\n}\n\nTEST(Coverage, when)\n{\n const std::string randomValue = \"4738\";\n\n libcellml::When w;\n libcellml::When wm;\n libcellml::Reset r;\n\n w.setValue(randomValue);\n wm = std::move(w);\n\n libcellml::When wc(wm);\n\n libcellml::WhenPtr wp = std::make_shared(wc);\n r.addWhen(wp);\n\n EXPECT_EQ(randomValue, wc.value());\n}\n\nTEST(Coverage, unitsGetVariations)\n{\n libcellml::Model m;\n\n libcellml::UnitsPtr u = std::make_shared();\n u->setName(\"a_unit\");\n\n u->addUnit(libcellml::Units::StandardUnit::AMPERE, \"micro\");\n m.addUnits(u);\n\n libcellml::UnitsPtr un = m.units(0);\n EXPECT_EQ(\"a_unit\", un->name());\n libcellml::UnitsPtr uSn = static_cast(m).units(0);\n EXPECT_EQ(\"a_unit\", uSn->name());\n\n libcellml::UnitsPtr uns = m.units(\"a_unit\");\n EXPECT_EQ(\"a_unit\", uns->name());\n libcellml::UnitsPtr uSns = static_cast(m).units(\"a_unit\");\n EXPECT_EQ(\"a_unit\", uSns->name());\n\n EXPECT_EQ(nullptr, m.units(\"b_unit\"));\n EXPECT_EQ(nullptr, m.units(4));\n}\n\nTEST(Coverage, prefixToString)\n{\n libcellml::Model m;\n libcellml::Printer printer;\n\n std::vector prefixString =\n {\"atto\",\n \"centi\",\n \"deca\",\n \"deci\",\n \"exa\",\n \"femto\",\n \"giga\",\n \"hecto\",\n \"kilo\",\n \"mega\",\n \"micro\",\n \"milli\",\n \"nano\",\n \"peta\",\n \"pico\",\n \"tera\",\n \"yocto\",\n \"yotta\",\n \"zepto\",\n \"zetta\"};\n std::vector prefixEnum =\n {libcellml::Prefix::ATTO,\n libcellml::Prefix::CENTI,\n libcellml::Prefix::DECA,\n libcellml::Prefix::DECI,\n libcellml::Prefix::EXA,\n libcellml::Prefix::FEMTO,\n libcellml::Prefix::GIGA,\n libcellml::Prefix::HECTO,\n libcellml::Prefix::KILO,\n libcellml::Prefix::MEGA,\n libcellml::Prefix::MICRO,\n libcellml::Prefix::MILLI,\n libcellml::Prefix::NANO,\n libcellml::Prefix::PETA,\n libcellml::Prefix::PICO,\n libcellml::Prefix::TERA,\n libcellml::Prefix::YOCTO,\n libcellml::Prefix::YOTTA,\n libcellml::Prefix::ZEPTO,\n libcellml::Prefix::ZETTA};\n for (std::vector::size_type i = 0; i != prefixString.size(); ++i) {\n libcellml::UnitsPtr u = std::make_shared();\n u->setName(\"abcdefg\");\n u->addUnit(\"empty\", prefixEnum[i]);\n\n m.addUnits(u);\n\n const std::string a = printer.printModel(m);\n std::size_t found = a.find(prefixString[i]);\n EXPECT_NE(std::string::npos, found);\n m.removeAllUnits();\n }\n}\n\nTEST(Coverage, variable)\n{\n const std::string e = \"\\n\";\n const std::string dimensionless = \"dimensionless\";\n libcellml::Variable v;\n libcellml::Variable vm;\n libcellml::UnitsPtr u = std::make_shared();\n\n v.setInitialValue(1.0);\n v.setInterfaceType(\"public\");\n u->setName(dimensionless);\n v.setUnits(u);\n\n vm = std::move(v);\n\n \/\/ Copy constructor\n libcellml::Variable vc(vm);\n\n EXPECT_EQ(dimensionless, vc.units());\n}\n\nTEST(Coverage, component)\n{\n const std::string math = \"<1+1=2>\\n\";\n libcellml::Component c;\n libcellml::Component cm;\n libcellml::VariablePtr v = std::make_shared();\n\n c.setName(\"name\");\n c.addVariable(v);\n c.setMath(math);\n\n EXPECT_EQ(size_t(1), c.variableCount());\n\n cm = std::move(c);\n EXPECT_EQ(size_t(1), cm.variableCount());\n\n \/\/ Copy constructor\n libcellml::Component cc(cm);\n EXPECT_EQ(size_t(1), cc.variableCount());\n}\n\nTEST(Coverage, error)\n{\n libcellml::ErrorPtr err = std::make_shared();\n libcellml::Error e;\n libcellml::Error em;\n const std::string description = \"test\";\n\n e.setDescription(description);\n e.setKind(libcellml::Error::Kind::XML);\n\n em = std::move(e);\n \/\/ Copy constructor\n libcellml::Error ec(em);\n\n EXPECT_EQ(description, ec.description());\n EXPECT_EQ(libcellml::Error::Kind::XML, ec.kind());\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if SILICIUM_COMPILER_GENERATES_MOVES\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) SILICIUM_DEFAULT_NOEXCEPT_MOVE(struct_name)\n#else\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() : member_name() BOOST_NOEXCEPT {} \\\n\tstruct_name(struct_name &&other) BOOST_NOEXCEPT : member_name(std::move(other.member_name)) {} \\\n\tstruct_name &operator = (struct_name &&other) BOOST_NOEXCEPT { member_name = std::move(other.member_name); return *this; }\n#endif\n\n#define SILICIUM_DETAIL_MAKE_PARAMETER(z, n, array) BOOST_PP_COMMA_IF(n) BOOST_PP_ARRAY_ELEM(n, array) BOOST_PP_CAT(arg, n)\n#define SILICIUM_DETAIL_MAKE_PARAMETERS(array) ( BOOST_PP_REPEAT(BOOST_PP_ARRAY_SIZE(array), SILICIUM_DETAIL_MAKE_PARAMETER, array) )\n\n#define SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\t= 0;\n\n#define SILICIUM_DETAIL_MAKE_INTERFACE(name, methods) struct name { \\\n\tvirtual ~name() {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_ERASER_METHOD_ARGUMENT(z, n, text) , BOOST_PP_CAT(_, n)\n\n#define SILICIUM_DETAIL_MAKE_ERASER_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\tSILICIUM_OVERRIDE { \\\n\t\treturn original. BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_BOX_METHOD(r, data, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) { \\\n\t\tassert(original); \\\n\t\treturn original -> BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_ERASER(name, methods) template struct name : interface { \\\n\tOriginal original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(Original original) : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_ERASER_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_MAKE_BOX(name, methods) struct box { \\\n\tstd::unique_ptr original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(std::unique_ptr original) BOOST_NOEXCEPT : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_BOX_METHOD, _, methods) \\\n};\n\n#define SILICIUM_TRAIT(name, methods) struct name { \\\n\tSILICIUM_DETAIL_MAKE_INTERFACE(interface, methods) \\\n\tSILICIUM_DETAIL_MAKE_ERASER(eraser, methods) \\\n\tSILICIUM_DETAIL_MAKE_BOX(box, methods) \\\n\ttemplate \\\n\tstatic eraser::type> erase(Original &&original) { \\\n\t\treturn eraser::type>{std::forward(original)}; \\\n\t} \\\n\ttemplate \\\n\tstatic box make_box(Original &&original) { \\\n\t\treturn box{Si::to_unique(erase(std::forward(original)))}; \\\n\t} \\\n};\n\ntypedef long element;\n\nSILICIUM_TRAIT(\n\tProducer,\n\t((get, (0, ()), element))\n)\n\nstruct test_producer\n{\n\telement get()\n\t{\n\t\treturn 42;\n\t}\n};\n\nBOOST_AUTO_TEST_CASE(trivial_trait)\n{\n\tstd::unique_ptr p = Si::to_unique(Producer::erase(test_producer{}));\n\tBOOST_REQUIRE(p);\n\tBOOST_CHECK_EQUAL(42, p->get());\n}\n\ntemplate \nSILICIUM_TRAIT(\n\tContainer,\n\t((emplace_back, (1, (T)), void))\n\t((resize, (1, (size_t)), void))\n\t((resize, (2, (size_t, T const &)), void))\n\t((empty, (0, ()), bool, const))\n\t((size, (0, ()), size_t, const BOOST_NOEXCEPT))\n)\n\nBOOST_AUTO_TEST_CASE(templatized_trait)\n{\n\tauto container = Container::erase(std::vector{});\n\tcontainer.emplace_back(123);\n\t{\n\t\tstd::vector const expected{123};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(2);\n\t{\n\t\tstd::vector const expected{123, 0};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(3, 7);\n\t{\n\t\tstd::vector const expected{123, 0, 7};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(trait_const_method)\n{\n\tauto container = Container::erase(std::vector{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK(const_ref.empty());\n\tcontainer.original.resize(1);\n\tBOOST_CHECK(!const_ref.empty());\n}\n\n#if SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT\nBOOST_AUTO_TEST_CASE(trait_noexcept_method)\n{\n\tauto container = Container::erase(std::vector{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK_EQUAL(0, const_ref.size());\n\tcontainer.original.resize(3);\n\tBOOST_CHECK_EQUAL(3, const_ref.size());\n\tBOOST_STATIC_ASSERT(BOOST_NOEXCEPT_EXPR(const_ref.size()));\n}\n#endif\n\nBOOST_AUTO_TEST_CASE(trait_box)\n{\n\tContainer::box container = Container::make_box(std::vector{});\n\tcontainer.emplace_back(3);\n\tBOOST_CHECK(!container.empty());\n\tBOOST_CHECK_EQUAL(1, container.size());\n}\ngenerate a default constructor for trait box and eraser#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if SILICIUM_COMPILER_GENERATES_MOVES\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() = default; \\\n\tSILICIUM_DEFAULT_MOVE(struct_name)\n#else\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() : member_name() BOOST_NOEXCEPT {} \\\n\tstruct_name(struct_name &&other) BOOST_NOEXCEPT : member_name(std::move(other.member_name)) {} \\\n\tstruct_name &operator = (struct_name &&other) BOOST_NOEXCEPT { member_name = std::move(other.member_name); return *this; }\n#endif\n\n#define SILICIUM_DETAIL_MAKE_PARAMETER(z, n, array) BOOST_PP_COMMA_IF(n) BOOST_PP_ARRAY_ELEM(n, array) BOOST_PP_CAT(arg, n)\n#define SILICIUM_DETAIL_MAKE_PARAMETERS(array) ( BOOST_PP_REPEAT(BOOST_PP_ARRAY_SIZE(array), SILICIUM_DETAIL_MAKE_PARAMETER, array) )\n\n#define SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\t= 0;\n\n#define SILICIUM_DETAIL_MAKE_INTERFACE(name, methods) struct name { \\\n\tvirtual ~name() {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_ERASER_METHOD_ARGUMENT(z, n, text) , BOOST_PP_CAT(_, n)\n\n#define SILICIUM_DETAIL_MAKE_ERASER_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\tSILICIUM_OVERRIDE { \\\n\t\treturn original. BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_BOX_METHOD(r, data, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) { \\\n\t\tassert(original); \\\n\t\treturn original -> BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_ERASER(name, methods) template struct name : interface { \\\n\tOriginal original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(Original original) : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_ERASER_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_MAKE_BOX(name, methods) struct box { \\\n\tstd::unique_ptr original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(std::unique_ptr original) BOOST_NOEXCEPT : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_BOX_METHOD, _, methods) \\\n};\n\n#define SILICIUM_TRAIT(name, methods) struct name { \\\n\tSILICIUM_DETAIL_MAKE_INTERFACE(interface, methods) \\\n\tSILICIUM_DETAIL_MAKE_ERASER(eraser, methods) \\\n\tSILICIUM_DETAIL_MAKE_BOX(box, methods) \\\n\ttemplate \\\n\tstatic eraser::type> erase(Original &&original) { \\\n\t\treturn eraser::type>{std::forward(original)}; \\\n\t} \\\n\ttemplate \\\n\tstatic box make_box(Original &&original) { \\\n\t\treturn box{Si::to_unique(erase(std::forward(original)))}; \\\n\t} \\\n};\n\ntypedef long element;\n\nSILICIUM_TRAIT(\n\tProducer,\n\t((get, (0, ()), element))\n)\n\nstruct test_producer\n{\n\telement get()\n\t{\n\t\treturn 42;\n\t}\n};\n\nBOOST_AUTO_TEST_CASE(trivial_trait)\n{\n\tstd::unique_ptr p = Si::to_unique(Producer::erase(test_producer{}));\n\tBOOST_REQUIRE(p);\n\tBOOST_CHECK_EQUAL(42, p->get());\n}\n\ntemplate \nSILICIUM_TRAIT(\n\tContainer,\n\t((emplace_back, (1, (T)), void))\n\t((resize, (1, (size_t)), void))\n\t((resize, (2, (size_t, T const &)), void))\n\t((empty, (0, ()), bool, const))\n\t((size, (0, ()), size_t, const BOOST_NOEXCEPT))\n)\n\nBOOST_AUTO_TEST_CASE(templatized_trait)\n{\n\tauto container = Container::erase(std::vector{});\n\tcontainer.emplace_back(123);\n\t{\n\t\tstd::vector const expected{123};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(2);\n\t{\n\t\tstd::vector const expected{123, 0};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(3, 7);\n\t{\n\t\tstd::vector const expected{123, 0, 7};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(trait_const_method)\n{\n\tauto container = Container::erase(std::vector{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK(const_ref.empty());\n\tcontainer.original.resize(1);\n\tBOOST_CHECK(!const_ref.empty());\n}\n\n#if SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT\nBOOST_AUTO_TEST_CASE(trait_noexcept_method)\n{\n\tauto container = Container::erase(std::vector{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK_EQUAL(0, const_ref.size());\n\tcontainer.original.resize(3);\n\tBOOST_CHECK_EQUAL(3, const_ref.size());\n\tBOOST_STATIC_ASSERT(BOOST_NOEXCEPT_EXPR(const_ref.size()));\n}\n#endif\n\nBOOST_AUTO_TEST_CASE(trait_box)\n{\n\tContainer::box container = Container::make_box(std::vector{});\n\tcontainer.emplace_back(3);\n\tBOOST_CHECK(!container.empty());\n\tBOOST_CHECK_EQUAL(1, container.size());\n}\n<|endoftext|>"} {"text":"#include \"FanCalculatorScene.h\"\n#include \"..\/mahjong-algorithm\/stringify.h\"\n#include \"..\/mahjong-algorithm\/fan_calculator.h\"\n#include \"..\/widget\/TilePickWidget.h\"\n#include \"..\/widget\/ExtraInfoWidget.h\"\n#include \"..\/widget\/AlertView.h\"\n#include \"..\/widget\/TilesKeyboard.h\"\n#include \"..\/FanTable\/FanDefinition.h\"\n\nUSING_NS_CC;\n\nbool FanCalculatorScene::init() {\n if (UNLIKELY(!BaseScene::initWithTitle(\"国标麻将算番器\"))) {\n return false;\n }\n\n Size visibleSize = Director::getInstance()->getVisibleSize();\n Vec2 origin = Director::getInstance()->getVisibleOrigin();\n\n \/\/ 选牌面板\n TilePickWidget *tilePicker = TilePickWidget::create();\n const Size &widgetSize = tilePicker->getContentSize();\n this->addChild(tilePicker);\n tilePicker->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,\n origin.y + visibleSize.height - 35 - widgetSize.height * 0.5f));\n _tilePicker = tilePicker;\n\n \/\/ 其他信息的相关控件\n ExtraInfoWidget *extraInfo = ExtraInfoWidget::create();\n const Size &extraSize = extraInfo->getContentSize();\n this->addChild(extraInfo);\n extraInfo->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,\n origin.y + visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height * 0.5f));\n _extraInfo = extraInfo;\n\n \/\/ 直接输入\n ui::Button *button = ui::Button::create(\"source_material\/btn_square_highlighted.png\", \"source_material\/btn_square_selected.png\");\n button->setScale9Enabled(true);\n button->setContentSize(Size(55.0f, 20.0f));\n button->setTitleFontSize(12);\n button->setTitleText(\"直接输入\");\n extraInfo->addChild(button);\n button->setPosition(Vec2(visibleSize.width - 40, 100.0f));\n button->addClickEventListener([this](Ref *) { showInputAlert(nullptr); });\n\n \/\/ 番算按钮\n button = ui::Button::create(\"source_material\/btn_square_highlighted.png\", \"source_material\/btn_square_selected.png\");\n button->setScale9Enabled(true);\n button->setContentSize(Size(55.0f, 20.0f));\n button->setTitleFontSize(12);\n button->setTitleText(\"算 番\");\n extraInfo->addChild(button);\n button->setPosition(Vec2(visibleSize.width - 40, 10.0f));\n button->addClickEventListener([this](Ref *) { calculate(); });\n\n \/\/ 番种显示的Node\n Size areaSize(visibleSize.width, visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height - 10);\n _fanAreaNode = Node::create();\n _fanAreaNode->setContentSize(areaSize);\n _fanAreaNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE);\n _fanAreaNode->setIgnoreAnchorPointForPosition(false);\n this->addChild(_fanAreaNode);\n _fanAreaNode->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + areaSize.height * 0.5f + 5));\n\n tilePicker->setFixedPacksChangedCallback([tilePicker, extraInfo]() {\n extraInfo->refreshByKong(tilePicker->isFixedPacksContainsKong());\n });\n\n tilePicker->setWinTileChangedCallback([tilePicker, extraInfo]() {\n ExtraInfoWidget::RefreshByWinTile rt;\n rt.getWinTile = std::bind(&TilePickWidget::getServingTile, tilePicker);\n rt.isStandingTilesContainsServingTile = std::bind(&TilePickWidget::isStandingTilesContainsServingTile, tilePicker);\n rt.countServingTileInFixedPacks = std::bind(&TilePickWidget::countServingTileInFixedPacks, tilePicker);\n rt.isFixedPacksContainsKong = std::bind(&TilePickWidget::isFixedPacksContainsKong, tilePicker);\n extraInfo->refreshByWinTile(rt);\n });\n\n return true;\n}\n\nstatic cocos2d::Node *createFanResultNode(const mahjong::fan_table_t &fan_table, int fontSize, float resultAreaWidth) {\n \/\/ 有n个番种,每行排2个\n ptrdiff_t n = mahjong::FAN_TABLE_SIZE - std::count(std::begin(fan_table), std::end(fan_table), 0);\n ptrdiff_t rows = (n >> 1) + (n & 1); \/\/ 需要这么多行\n\n \/\/ 排列\n Node *node = Node::create();\n const int lineHeight = fontSize + 2;\n ptrdiff_t resultAreaHeight = lineHeight * rows; \/\/ 每行间隔2像素\n resultAreaHeight += (5 + lineHeight) + 20; \/\/ 总计+提示\n node->setContentSize(Size(resultAreaWidth, static_cast(resultAreaHeight)));\n\n long fan = 0;\n for (int i = 0, j = 0; i < n; ++i) {\n while (fan_table[++j] == 0) continue;\n\n int f = mahjong::fan_value_table[j];\n long n = fan_table[j];\n fan += f * n;\n std::string str = (n == 1) ? Common::format<128>(\"%s %d番\\n\", mahjong::fan_name[j], f)\n : Common::format<128>(\"%s %d番x%ld\\n\", mahjong::fan_name[j], f, fan_table[j]);\n\n \/\/ 创建label,每行排2个\n Label *label = Label::createWithSystemFont(str, \"Arial\", static_cast(fontSize));\n label->setColor(Color3B(0x60, 0x60, 0x60));\n node->addChild(label);\n label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n div_t ret = div(i, 2);\n label->setPosition(Vec2(ret.rem == 0 ? 0.0f : resultAreaWidth * 0.5f, static_cast(resultAreaHeight - lineHeight * (ret.quot + 1))));\n\n \/\/ 创建与label同位置的button\n ui::Button *button = ui::Button::create();\n button->setScale9Enabled(true);\n button->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n button->setPosition(label->getPosition());\n button->setContentSize(label->getContentSize());\n node->addChild(button);\n button->addClickEventListener([j](Ref *) {\n Director::getInstance()->pushScene(FanDefinitionScene::create(j));\n });\n }\n\n Label *label = Label::createWithSystemFont(Common::format<64>(\"总计:%ld番\", fan), \"Arial\", static_cast(fontSize));\n label->setColor(Color3B::BLACK);\n node->addChild(label);\n label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n label->setPosition(Vec2(0.0f, lineHeight * 0.5f + 20));\n\n label = Label::createWithSystemFont(\"点击番种名可查看番种介绍。\", \"Arial\", 10);\n label->setColor(Color3B(51, 204, 255));\n node->addChild(label);\n label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n label->setPosition(Vec2(0.0f, 5));\n\n return node;\n}\n\nvoid FanCalculatorScene::showInputAlert(const char *prevInput) {\n Size visibleSize = Director::getInstance()->getVisibleSize();\n const float width = visibleSize.width * 0.8f - 10;\n\n Node *rootNode = Node::create();\n\n Label *label = Label::createWithSystemFont(\"使用说明:\\n\"\n \"1.\" INPUT_GUIDE_STRING_1 \"\\n\"\n \"2.\" INPUT_GUIDE_STRING_2 \"\\n\"\n \"3.\" INPUT_GUIDE_STRING_3 \"\\n\"\n \"输入范例1:[EEEE][CCCC][FFFF][PPPP]NN\\n\"\n \"输入范例2:1112345678999s9s\\n\"\n \"输入范例3:WWWW 444s 45m678pFF6m\\n\", \"Arial\", 10);\n label->setColor(Color3B::BLACK);\n label->setDimensions(width, 0);\n rootNode->addChild(label);\n\n \/\/ 输入手牌\n ui::EditBox *editBox = ui::EditBox::create(Size(width - 10, 20.0f), ui::Scale9Sprite::create(\"source_material\/btn_square_normal.png\"));\n editBox->setInputFlag(ui::EditBox::InputFlag::SENSITIVE);\n editBox->setInputMode(ui::EditBox::InputMode::SINGLE_LINE);\n editBox->setReturnType(ui::EditBox::KeyboardReturnType::DONE);\n editBox->setFontColor(Color4B::BLACK);\n editBox->setFontSize(12);\n editBox->setPlaceholderFontColor(Color4B::GRAY);\n editBox->setPlaceHolder(\"输入手牌\");\n if (prevInput != nullptr) {\n editBox->setText(prevInput);\n }\n TilesKeyboard::hookEditBox(editBox);\n rootNode->addChild(editBox);\n\n const Size &labelSize = label->getContentSize();\n rootNode->setContentSize(Size(width, labelSize.height + 30));\n editBox->setPosition(Vec2(width * 0.5f, 10));\n label->setPosition(Vec2(width * 0.5f, labelSize.height * 0.5f + 30));\n\n AlertView::showWithNode(\"直接输入\", rootNode, [this, editBox]() {\n const char *input = editBox->getText();\n const char *errorStr = TilesKeyboard::parseInput(input,\n std::bind(&TilePickWidget::setData, _tilePicker, std::placeholders::_1, std::placeholders::_2));\n if (errorStr != nullptr) {\n const std::string str = input;\n AlertView::showWithMessage(\"直接输入牌\", errorStr, 12, [this, str]() {\n showInputAlert(str.c_str());\n }, nullptr);\n }\n }, nullptr);\n}\n\nvoid FanCalculatorScene::calculate() {\n _fanAreaNode->removeAllChildren();\n\n const Size &fanAreaSize = _fanAreaNode->getContentSize();\n Vec2 pos(fanAreaSize.width * 0.5f, fanAreaSize.height * 0.5f);\n\n int flowerCnt = _extraInfo->getFlowerCount();\n if (flowerCnt > 8) {\n AlertView::showWithMessage(\"算番\", \"花牌数的范围为0~8\", 12, nullptr, nullptr);\n return;\n }\n\n mahjong::calculate_param_t param;\n _tilePicker->getData(¶m.hand_tiles, ¶m.win_tile);\n if (param.win_tile == 0) {\n AlertView::showWithMessage(\"算番\", \"牌张数错误\", 12, nullptr, nullptr);\n return;\n }\n\n std::sort(param.hand_tiles.standing_tiles, param.hand_tiles.standing_tiles + param.hand_tiles.tile_count);\n\n param.flower_count = flowerCnt;\n mahjong::fan_table_t fan_table = { 0 };\n\n \/\/ 获取绝张、杠开、抢杠、海底信息\n mahjong::win_flag_t win_flag = _extraInfo->getWinFlag();\n\n \/\/ 获取圈风门风\n mahjong::wind_t prevalent_wind = _extraInfo->getPrevalentWind();\n mahjong::wind_t seat_wind = _extraInfo->getSeatWind();\n\n \/\/ 算番\n param.win_flag = win_flag;\n param.prevalent_wind = prevalent_wind;\n param.seat_wind = seat_wind;\n int fan = calculate_fan(¶m, fan_table);\n\n if (fan == ERROR_NOT_WIN) {\n Label *errorLabel = Label::createWithSystemFont(\"诈和\", \"Arial\", 14);\n errorLabel->setColor(Color3B::BLACK);\n _fanAreaNode->addChild(errorLabel);\n errorLabel->setPosition(pos);\n return;\n }\n if (fan == ERROR_WRONG_TILES_COUNT) {\n AlertView::showWithMessage(\"算番\", \"牌张数错误\", 12, nullptr, nullptr);\n return;\n }\n if (fan == ERROR_TILE_COUNT_GREATER_THAN_4) {\n AlertView::showWithMessage(\"算番\", \"同一种牌最多只能使用4枚\", 12, nullptr, nullptr);\n return;\n }\n\n Node *innerNode = createFanResultNode(fan_table, 14, fanAreaSize.width - 10);\n\n \/\/ 超出高度就使用ScrollView\n if (innerNode->getContentSize().height <= fanAreaSize.height) {\n _fanAreaNode->addChild(innerNode);\n innerNode->setAnchorPoint(Vec2(0.5f, 0.5f));\n innerNode->setPosition(pos);\n }\n else {\n ui::ScrollView *scrollView = ui::ScrollView::create();\n scrollView->setDirection(ui::ScrollView::Direction::VERTICAL);\n scrollView->setScrollBarPositionFromCorner(Vec2(2, 2));\n scrollView->setScrollBarWidth(4);\n scrollView->setScrollBarOpacity(0x99);\n scrollView->setContentSize(Size(fanAreaSize.width - 10, fanAreaSize.height));\n scrollView->setInnerContainerSize(innerNode->getContentSize());\n scrollView->addChild(innerNode);\n\n _fanAreaNode->addChild(scrollView);\n scrollView->setAnchorPoint(Vec2(0.5f, 0.5f));\n scrollView->setPosition(pos);\n }\n}\n修复GCC编译警告#include \"FanCalculatorScene.h\"\n#include \"..\/mahjong-algorithm\/stringify.h\"\n#include \"..\/mahjong-algorithm\/fan_calculator.h\"\n#include \"..\/widget\/TilePickWidget.h\"\n#include \"..\/widget\/ExtraInfoWidget.h\"\n#include \"..\/widget\/AlertView.h\"\n#include \"..\/widget\/TilesKeyboard.h\"\n#include \"..\/FanTable\/FanDefinition.h\"\n\nUSING_NS_CC;\n\nbool FanCalculatorScene::init() {\n if (UNLIKELY(!BaseScene::initWithTitle(\"国标麻将算番器\"))) {\n return false;\n }\n\n Size visibleSize = Director::getInstance()->getVisibleSize();\n Vec2 origin = Director::getInstance()->getVisibleOrigin();\n\n \/\/ 选牌面板\n TilePickWidget *tilePicker = TilePickWidget::create();\n const Size &widgetSize = tilePicker->getContentSize();\n this->addChild(tilePicker);\n tilePicker->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,\n origin.y + visibleSize.height - 35 - widgetSize.height * 0.5f));\n _tilePicker = tilePicker;\n\n \/\/ 其他信息的相关控件\n ExtraInfoWidget *extraInfo = ExtraInfoWidget::create();\n const Size &extraSize = extraInfo->getContentSize();\n this->addChild(extraInfo);\n extraInfo->setPosition(Vec2(origin.x + visibleSize.width * 0.5f,\n origin.y + visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height * 0.5f));\n _extraInfo = extraInfo;\n\n \/\/ 直接输入\n ui::Button *button = ui::Button::create(\"source_material\/btn_square_highlighted.png\", \"source_material\/btn_square_selected.png\");\n button->setScale9Enabled(true);\n button->setContentSize(Size(55.0f, 20.0f));\n button->setTitleFontSize(12);\n button->setTitleText(\"直接输入\");\n extraInfo->addChild(button);\n button->setPosition(Vec2(visibleSize.width - 40, 100.0f));\n button->addClickEventListener([this](Ref *) { showInputAlert(nullptr); });\n\n \/\/ 番算按钮\n button = ui::Button::create(\"source_material\/btn_square_highlighted.png\", \"source_material\/btn_square_selected.png\");\n button->setScale9Enabled(true);\n button->setContentSize(Size(55.0f, 20.0f));\n button->setTitleFontSize(12);\n button->setTitleText(\"算 番\");\n extraInfo->addChild(button);\n button->setPosition(Vec2(visibleSize.width - 40, 10.0f));\n button->addClickEventListener([this](Ref *) { calculate(); });\n\n \/\/ 番种显示的Node\n Size areaSize(visibleSize.width, visibleSize.height - 35 - widgetSize.height - 5 - extraSize.height - 10);\n _fanAreaNode = Node::create();\n _fanAreaNode->setContentSize(areaSize);\n _fanAreaNode->setAnchorPoint(Vec2::ANCHOR_MIDDLE);\n _fanAreaNode->setIgnoreAnchorPointForPosition(false);\n this->addChild(_fanAreaNode);\n _fanAreaNode->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + areaSize.height * 0.5f + 5));\n\n tilePicker->setFixedPacksChangedCallback([tilePicker, extraInfo]() {\n extraInfo->refreshByKong(tilePicker->isFixedPacksContainsKong());\n });\n\n tilePicker->setWinTileChangedCallback([tilePicker, extraInfo]() {\n ExtraInfoWidget::RefreshByWinTile rt;\n rt.getWinTile = std::bind(&TilePickWidget::getServingTile, tilePicker);\n rt.isStandingTilesContainsServingTile = std::bind(&TilePickWidget::isStandingTilesContainsServingTile, tilePicker);\n rt.countServingTileInFixedPacks = std::bind(&TilePickWidget::countServingTileInFixedPacks, tilePicker);\n rt.isFixedPacksContainsKong = std::bind(&TilePickWidget::isFixedPacksContainsKong, tilePicker);\n extraInfo->refreshByWinTile(rt);\n });\n\n return true;\n}\n\nstatic cocos2d::Node *createFanResultNode(const mahjong::fan_table_t &fan_table, int fontSize, float resultAreaWidth) {\n \/\/ 有n个番种,每行排2个\n ptrdiff_t n = mahjong::FAN_TABLE_SIZE - std::count(std::begin(fan_table), std::end(fan_table), 0);\n ptrdiff_t rows = (n >> 1) + (n & 1); \/\/ 需要这么多行\n\n \/\/ 排列\n Node *node = Node::create();\n const int lineHeight = fontSize + 2;\n ptrdiff_t resultAreaHeight = lineHeight * rows; \/\/ 每行间隔2像素\n resultAreaHeight += (5 + lineHeight) + 20; \/\/ 总计+提示\n node->setContentSize(Size(resultAreaWidth, static_cast(resultAreaHeight)));\n\n uint16_t fan = 0;\n for (int i = 0, j = 0; i < n; ++i) {\n while (fan_table[++j] == 0) continue;\n\n uint16_t f = mahjong::fan_value_table[j];\n uint16_t n = fan_table[j];\n fan += f * n;\n std::string str = (n == 1) ? Common::format<128>(\"%s %hd番\\n\", mahjong::fan_name[j], f)\n : Common::format<128>(\"%s %hd番x%hd\\n\", mahjong::fan_name[j], f, fan_table[j]);\n\n \/\/ 创建label,每行排2个\n Label *label = Label::createWithSystemFont(str, \"Arial\", static_cast(fontSize));\n label->setColor(Color3B(0x60, 0x60, 0x60));\n node->addChild(label);\n label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n div_t ret = div(i, 2);\n label->setPosition(Vec2(ret.rem == 0 ? 0.0f : resultAreaWidth * 0.5f, static_cast(resultAreaHeight - lineHeight * (ret.quot + 1))));\n\n \/\/ 创建与label同位置的button\n ui::Button *button = ui::Button::create();\n button->setScale9Enabled(true);\n button->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n button->setPosition(label->getPosition());\n button->setContentSize(label->getContentSize());\n node->addChild(button);\n button->addClickEventListener([j](Ref *) {\n Director::getInstance()->pushScene(FanDefinitionScene::create(j));\n });\n }\n\n Label *label = Label::createWithSystemFont(Common::format<64>(\"总计:%ld番\", fan), \"Arial\", static_cast(fontSize));\n label->setColor(Color3B::BLACK);\n node->addChild(label);\n label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n label->setPosition(Vec2(0.0f, lineHeight * 0.5f + 20));\n\n label = Label::createWithSystemFont(\"点击番种名可查看番种介绍。\", \"Arial\", 10);\n label->setColor(Color3B(51, 204, 255));\n node->addChild(label);\n label->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);\n label->setPosition(Vec2(0.0f, 5));\n\n return node;\n}\n\nvoid FanCalculatorScene::showInputAlert(const char *prevInput) {\n Size visibleSize = Director::getInstance()->getVisibleSize();\n const float width = visibleSize.width * 0.8f - 10;\n\n Node *rootNode = Node::create();\n\n Label *label = Label::createWithSystemFont(\"使用说明:\\n\"\n \"1.\" INPUT_GUIDE_STRING_1 \"\\n\"\n \"2.\" INPUT_GUIDE_STRING_2 \"\\n\"\n \"3.\" INPUT_GUIDE_STRING_3 \"\\n\"\n \"输入范例1:[EEEE][CCCC][FFFF][PPPP]NN\\n\"\n \"输入范例2:1112345678999s9s\\n\"\n \"输入范例3:WWWW 444s 45m678pFF6m\\n\", \"Arial\", 10);\n label->setColor(Color3B::BLACK);\n label->setDimensions(width, 0);\n rootNode->addChild(label);\n\n \/\/ 输入手牌\n ui::EditBox *editBox = ui::EditBox::create(Size(width - 10, 20.0f), ui::Scale9Sprite::create(\"source_material\/btn_square_normal.png\"));\n editBox->setInputFlag(ui::EditBox::InputFlag::SENSITIVE);\n editBox->setInputMode(ui::EditBox::InputMode::SINGLE_LINE);\n editBox->setReturnType(ui::EditBox::KeyboardReturnType::DONE);\n editBox->setFontColor(Color4B::BLACK);\n editBox->setFontSize(12);\n editBox->setPlaceholderFontColor(Color4B::GRAY);\n editBox->setPlaceHolder(\"输入手牌\");\n if (prevInput != nullptr) {\n editBox->setText(prevInput);\n }\n TilesKeyboard::hookEditBox(editBox);\n rootNode->addChild(editBox);\n\n const Size &labelSize = label->getContentSize();\n rootNode->setContentSize(Size(width, labelSize.height + 30));\n editBox->setPosition(Vec2(width * 0.5f, 10));\n label->setPosition(Vec2(width * 0.5f, labelSize.height * 0.5f + 30));\n\n AlertView::showWithNode(\"直接输入\", rootNode, [this, editBox]() {\n const char *input = editBox->getText();\n const char *errorStr = TilesKeyboard::parseInput(input,\n std::bind(&TilePickWidget::setData, _tilePicker, std::placeholders::_1, std::placeholders::_2));\n if (errorStr != nullptr) {\n const std::string str = input;\n AlertView::showWithMessage(\"直接输入牌\", errorStr, 12, [this, str]() {\n showInputAlert(str.c_str());\n }, nullptr);\n }\n }, nullptr);\n}\n\nvoid FanCalculatorScene::calculate() {\n _fanAreaNode->removeAllChildren();\n\n const Size &fanAreaSize = _fanAreaNode->getContentSize();\n Vec2 pos(fanAreaSize.width * 0.5f, fanAreaSize.height * 0.5f);\n\n int flowerCnt = _extraInfo->getFlowerCount();\n if (flowerCnt > 8) {\n AlertView::showWithMessage(\"算番\", \"花牌数的范围为0~8\", 12, nullptr, nullptr);\n return;\n }\n\n mahjong::calculate_param_t param;\n _tilePicker->getData(¶m.hand_tiles, ¶m.win_tile);\n if (param.win_tile == 0) {\n AlertView::showWithMessage(\"算番\", \"牌张数错误\", 12, nullptr, nullptr);\n return;\n }\n\n std::sort(param.hand_tiles.standing_tiles, param.hand_tiles.standing_tiles + param.hand_tiles.tile_count);\n\n param.flower_count = flowerCnt;\n mahjong::fan_table_t fan_table = { 0 };\n\n \/\/ 获取绝张、杠开、抢杠、海底信息\n mahjong::win_flag_t win_flag = _extraInfo->getWinFlag();\n\n \/\/ 获取圈风门风\n mahjong::wind_t prevalent_wind = _extraInfo->getPrevalentWind();\n mahjong::wind_t seat_wind = _extraInfo->getSeatWind();\n\n \/\/ 算番\n param.win_flag = win_flag;\n param.prevalent_wind = prevalent_wind;\n param.seat_wind = seat_wind;\n int fan = calculate_fan(¶m, fan_table);\n\n if (fan == ERROR_NOT_WIN) {\n Label *errorLabel = Label::createWithSystemFont(\"诈和\", \"Arial\", 14);\n errorLabel->setColor(Color3B::BLACK);\n _fanAreaNode->addChild(errorLabel);\n errorLabel->setPosition(pos);\n return;\n }\n if (fan == ERROR_WRONG_TILES_COUNT) {\n AlertView::showWithMessage(\"算番\", \"牌张数错误\", 12, nullptr, nullptr);\n return;\n }\n if (fan == ERROR_TILE_COUNT_GREATER_THAN_4) {\n AlertView::showWithMessage(\"算番\", \"同一种牌最多只能使用4枚\", 12, nullptr, nullptr);\n return;\n }\n\n Node *innerNode = createFanResultNode(fan_table, 14, fanAreaSize.width - 10);\n\n \/\/ 超出高度就使用ScrollView\n if (innerNode->getContentSize().height <= fanAreaSize.height) {\n _fanAreaNode->addChild(innerNode);\n innerNode->setAnchorPoint(Vec2(0.5f, 0.5f));\n innerNode->setPosition(pos);\n }\n else {\n ui::ScrollView *scrollView = ui::ScrollView::create();\n scrollView->setDirection(ui::ScrollView::Direction::VERTICAL);\n scrollView->setScrollBarPositionFromCorner(Vec2(2, 2));\n scrollView->setScrollBarWidth(4);\n scrollView->setScrollBarOpacity(0x99);\n scrollView->setContentSize(Size(fanAreaSize.width - 10, fanAreaSize.height));\n scrollView->setInnerContainerSize(innerNode->getContentSize());\n scrollView->addChild(innerNode);\n\n _fanAreaNode->addChild(scrollView);\n scrollView->setAnchorPoint(Vec2(0.5f, 0.5f));\n scrollView->setPosition(pos);\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mvdDatabaseBrowserWidget.h\"\n#include \"ui_mvdDatabaseBrowserWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Gui\/mvdDatabaseTreeWidget.h\"\n#include \"Gui\/mvdTreeWidgetItem.h\"\n\n#define ENABLE_DISPLAY_ID 1\n\nnamespace mvd\n{\n\n\/*\n TRANSLATOR mvd::DatabaseBrowserWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::DatabaseBrowserWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::DatabaseBrowserWidget() ),\n m_DatasetRootItem( NULL ),\n m_DatasetList(),\n m_StartDragPosition(),\n m_SearchText()\n{\n m_UI->setupUi( this );\n\n SetupUI();\n\n \/*\n \/\/ Devember 12th, 2013 - Trainee example. \n QPushButton* button=new QPushButton (\"Click me\", this);\n layout()->addWidget(button);\n *\/\n}\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::~DatabaseBrowserWidget()\n{\n delete m_UI;\n m_UI = NULL;\n}\n\n\/*****************************************************************************\/\nconst QTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem() const\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*****************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem()\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertNodeItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_NODE,\n text,\n id,\n columns\n );\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertLeafItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_LEAF,\n text,\n id,\n columns\n );\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertItem( QTreeWidgetItem* parent,\n TreeWidgetItem::ItemType type,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n TreeWidgetItem* item =\n new TreeWidgetItem(\n parent,\n text,\n id,\n columns,\n type\n );\n\n return item;\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetDatasetList( const StringPairListType& list )\n{\n \/\/ qDebug() << this << \"::SetDatasetList(\" << list << \")\";\n\n \/\/ remember dataset list\n m_DatasetList = list;\n\n \/\/ Fill Tree\n FillTree();\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::FillTree()\n{\n \/\/ get the currentItem Id if any selected.\n \/\/ since all the TreeWidgetItem are deleted next, need to remember\n \/\/ it in order to set it back\n QString currentItemHash;\n\n TreeWidgetItem* selectedItem = \n dynamic_cast< TreeWidgetItem* >(\n GetDatabaseTreeWidget()->currentItem()\n );\n\n if (selectedItem)\n {\n currentItemHash = selectedItem->GetHash();\n }\n\n \/\/ TODO: Get initial algorithm back (synchronizes two ordered\n \/\/ sequences using QTreeWidget::findItems<>().\n \/\/\n \/\/ Because:\n \/\/ 1. removing items can provoque selection changes;\n \/\/ 2. it's needed to re-emit signal to keep current selection\n \/\/ active.\n \/\/\n \/\/ Initial algorithm took care of current-selection and was\n \/\/ optimized to not delete useful items which must be inserted\n \/\/ again.\n\n \/\/ Remove all previously stored dataset child items.\n while( m_DatasetRootItem->childCount()>0 )\n {\n \/\/ Remove dataset child item and reference it.\n QTreeWidgetItem* child = m_DatasetRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \/\/ Append full dataset list...\n for( StringPairListType::const_iterator it( m_DatasetList.begin() );\n it!=m_DatasetList.end();\n ++it )\n {\n \/\/ current alias\n const StringPairListType::value_type::first_type& alias = it->first;\n const StringPairListType::value_type::second_type& hash = it->second;\n\n TreeWidgetItem* item =\n new TreeWidgetItem(\n m_DatasetRootItem,\n alias,\n QVariant(),\n QStringList( hash )\n );\n\n \/\/ Item is visible is search-text is empty or if alias contains\n \/\/ search-text.\n item->setHidden(\n !m_SearchText.isEmpty() &&\n !item->text( 0 ).contains( m_SearchText, Qt::CaseInsensitive )\n );\n\n \/\/ was it the selected item ?\n if( currentItemHash == hash )\n {\n \/\/ ...add this child item as currentItem\n GetDatabaseTreeWidget()->setCurrentItem( item );\n }\n }\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetupUI()\n{\n setAcceptDrops( true );\n\n \/\/\n \/\/ Header columns.\n m_UI->databaseTreeWidget->headerItem()->setText( 1, \"Id\" );\n m_UI->databaseTreeWidget->headerItem()->setText( 2, \"Info\" );\n\n#if (!defined( _DEBUG ) && 1) || 0\n m_UI->databaseTreeWidget->setColumnHidden( 1, true );\n m_UI->databaseTreeWidget->setColumnHidden( 2, true );\n#endif\n\n \/\/\n \/\/ Dataset root item.\n#if 0\n m_DatasetRootItem = new QTreeWidgetItem( \"Datasets\", m_UI->databaseTreeWidget );\n\n m_DatasetRootItem->setChildIndicatorPolicy(\n QTreeWidgetItem::DontShowIndicatorWhenChildless\n );\n\n m_DatasetRootItem->setExpanded( true );\n#endif\n\n \/\/ set placeholder text\n#if (QT_VERSION >= 0x407000)\n m_UI->m_SearchLine->setPlaceholderText( tr( \"Search Dataset...\" ) );\n#endif\n}\n\n\/*******************************************************************************\/\nDatabaseTreeWidget*\nDatabaseBrowserWidget\n::GetDatabaseTreeWidget()\n{\n return m_UI->databaseTreeWidget;\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetCurrentDataset( const QString& hash )\n{\n \/\/ qDebug() << this << \"::SetCurrentDataset(\" << id << \")\";\n\n assert( m_UI!=NULL );\n assert( m_UI->databaseTreeWidget!=NULL );\n\n QList< QTreeWidgetItem* > items(\n m_UI->databaseTreeWidget->findItems(\n hash,\n Qt::MatchExactly | Qt::MatchRecursive,\n 1\n )\n );\n\n assert( items.isEmpty() || items.size() == 1 );\n\n \/*\n qDebug()\n << ( items.isEmpty() ? \"NONE\" : items.first()->text( 0 ) )\n << m_UI->databaseTreeWidget->selectionModel()->selectedIndexes().size();\n *\/\n\n#if 0\n\n m_UI->databaseTreeWidget->setCurrentItem(\n items.isEmpty() ? NULL : items.first(),\n 0,\n QItemSelectionModel::Clear |\n QItemSelectionModel::Current\n );\n#else\n if( items.isEmpty() )\n return;\n\n m_UI->databaseTreeWidget->setCurrentItem( items.first() );\n#endif\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_databaseTreeWidget_currentItemChanged( QTreeWidgetItem* current,\n\t\t\t\t\t QTreeWidgetItem* previous )\n{\n \/\/\n \/\/ Current\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString currentHash;\n\n TreeWidgetItem* currentItem = dynamic_cast< TreeWidgetItem* >( current );\n\n if( currentItem!=NULL && currentItem->parent()!=NULL )\n \/\/ if current is root and not NULL get the Id of the corresponding\n \/\/ Dataset.\n currentHash = currentItem->GetHash();\n\n \/\/\n \/\/ Previous\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString previousHash;\n\n TreeWidgetItem* previousItem = dynamic_cast< TreeWidgetItem* >( previous );\n\n if( previousItem!=NULL )\n previousHash = previousItem->GetHash();\n\n \/\/\n \/\/ Emit event.\n emit CurrentDatasetChanged( currentHash, previousHash );\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_m_SearchLine_textChanged( const QString& search )\n{\n \/\/ \n \/\/ get the search text\n m_SearchText = search;\n\n#if 0\n \/\/ fill the tree with the application\n FillTree(); \n#else\n for( int i=0; ichildCount(); ++i )\n {\n QTreeWidgetItem* item = m_DatasetRootItem->child( i );\n assert( item!=NULL );\n\n \/\/ Item is visible if search is empty or if alias contains\n \/\/ search-text.\n item->setHidden(\n !search.isEmpty() &&\n !item->text( 0 ).contains( search, Qt::CaseInsensitive )\n );\n }\n#endif\n}\n\n} \/\/ end namespace 'mvd'\nENH: Fixed crash when typing text into DatabaseBrowser search filter line-edit.\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"mvdDatabaseBrowserWidget.h\"\n#include \"ui_mvdDatabaseBrowserWidget.h\"\n\n\n\/*****************************************************************************\/\n\/* INCLUDE SECTION *\/\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"Gui\/mvdDatabaseTreeWidget.h\"\n#include \"Gui\/mvdTreeWidgetItem.h\"\n\n#define ENABLE_DISPLAY_ID 1\n\nnamespace mvd\n{\n\n\/*\n TRANSLATOR mvd::DatabaseBrowserWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\n\/*****************************************************************************\/\n\/* CONSTANTS *\/\n\n\n\/*****************************************************************************\/\n\/* STATIC IMPLEMENTATION SECTION *\/\n\n\n\/*****************************************************************************\/\n\/* CLASS IMPLEMENTATION SECTION *\/\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::DatabaseBrowserWidget( QWidget* parent, Qt::WindowFlags flags ):\n QWidget( parent, flags ),\n m_UI( new mvd::Ui::DatabaseBrowserWidget() ),\n m_DatasetRootItem( NULL ),\n m_DatasetList(),\n m_StartDragPosition(),\n m_SearchText()\n{\n m_UI->setupUi( this );\n\n SetupUI();\n\n \/*\n \/\/ Devember 12th, 2013 - Trainee example. \n QPushButton* button=new QPushButton (\"Click me\", this);\n layout()->addWidget(button);\n *\/\n}\n\n\/*******************************************************************************\/\nDatabaseBrowserWidget\n::~DatabaseBrowserWidget()\n{\n delete m_UI;\n m_UI = NULL;\n}\n\n\/*****************************************************************************\/\nconst QTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem() const\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*****************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::GetRootItem()\n{\n return m_UI->databaseTreeWidget->invisibleRootItem();\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertNodeItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_NODE,\n text,\n id,\n columns\n );\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertLeafItem( QTreeWidgetItem* parent,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n return\n InsertItem(\n parent,\n TreeWidgetItem::ITEM_TYPE_LEAF,\n text,\n id,\n columns\n );\n}\n\n\/*******************************************************************************\/\nQTreeWidgetItem*\nDatabaseBrowserWidget\n::InsertItem( QTreeWidgetItem* parent,\n TreeWidgetItem::ItemType type,\n const QString& text,\n const QVariant& id,\n const QStringList& columns )\n{\n TreeWidgetItem* item =\n new TreeWidgetItem(\n parent,\n text,\n id,\n columns,\n type\n );\n\n return item;\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetDatasetList( const StringPairListType& list )\n{\n \/\/ qDebug() << this << \"::SetDatasetList(\" << list << \")\";\n\n \/\/ remember dataset list\n m_DatasetList = list;\n\n \/\/ Fill Tree\n FillTree();\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::FillTree()\n{\n \/\/ get the currentItem Id if any selected.\n \/\/ since all the TreeWidgetItem are deleted next, need to remember\n \/\/ it in order to set it back\n QString currentItemHash;\n\n TreeWidgetItem* selectedItem = \n dynamic_cast< TreeWidgetItem* >(\n GetDatabaseTreeWidget()->currentItem()\n );\n\n if (selectedItem)\n {\n currentItemHash = selectedItem->GetHash();\n }\n\n \/\/ TODO: Get initial algorithm back (synchronizes two ordered\n \/\/ sequences using QTreeWidget::findItems<>().\n \/\/\n \/\/ Because:\n \/\/ 1. removing items can provoque selection changes;\n \/\/ 2. it's needed to re-emit signal to keep current selection\n \/\/ active.\n \/\/\n \/\/ Initial algorithm took care of current-selection and was\n \/\/ optimized to not delete useful items which must be inserted\n \/\/ again.\n\n \/\/ Remove all previously stored dataset child items.\n while( m_DatasetRootItem->childCount()>0 )\n {\n \/\/ Remove dataset child item and reference it.\n QTreeWidgetItem* child = m_DatasetRootItem->takeChild( 0 );\n\n \/\/ Delete it from memory.\n delete child;\n child = NULL;\n }\n\n \/\/ Append full dataset list...\n for( StringPairListType::const_iterator it( m_DatasetList.begin() );\n it!=m_DatasetList.end();\n ++it )\n {\n \/\/ current alias\n const StringPairListType::value_type::first_type& alias = it->first;\n const StringPairListType::value_type::second_type& hash = it->second;\n\n TreeWidgetItem* item =\n new TreeWidgetItem(\n m_DatasetRootItem,\n alias,\n QVariant(),\n QStringList( hash )\n );\n\n \/\/ Item is visible is search-text is empty or if alias contains\n \/\/ search-text.\n item->setHidden(\n !m_SearchText.isEmpty() &&\n !item->text( 0 ).contains( m_SearchText, Qt::CaseInsensitive )\n );\n\n \/\/ was it the selected item ?\n if( currentItemHash == hash )\n {\n \/\/ ...add this child item as currentItem\n GetDatabaseTreeWidget()->setCurrentItem( item );\n }\n }\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetupUI()\n{\n setAcceptDrops( true );\n\n \/\/\n \/\/ Header columns.\n m_UI->databaseTreeWidget->headerItem()->setText( 1, \"Id\" );\n m_UI->databaseTreeWidget->headerItem()->setText( 2, \"Info\" );\n\n#if (!defined( _DEBUG ) && 1) || 0\n m_UI->databaseTreeWidget->setColumnHidden( 1, true );\n m_UI->databaseTreeWidget->setColumnHidden( 2, true );\n#endif\n\n \/\/\n \/\/ Dataset root item.\n#if 0\n m_DatasetRootItem = new QTreeWidgetItem( \"Datasets\", m_UI->databaseTreeWidget );\n\n m_DatasetRootItem->setChildIndicatorPolicy(\n QTreeWidgetItem::DontShowIndicatorWhenChildless\n );\n\n m_DatasetRootItem->setExpanded( true );\n#endif\n\n \/\/ set placeholder text\n#if (QT_VERSION >= 0x407000)\n m_UI->m_SearchLine->setPlaceholderText( tr( \"Search Dataset...\" ) );\n#endif\n}\n\n\/*******************************************************************************\/\nDatabaseTreeWidget*\nDatabaseBrowserWidget\n::GetDatabaseTreeWidget()\n{\n return m_UI->databaseTreeWidget;\n}\n\n\/*****************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::SetCurrentDataset( const QString& hash )\n{\n \/\/ qDebug() << this << \"::SetCurrentDataset(\" << id << \")\";\n\n assert( m_UI!=NULL );\n assert( m_UI->databaseTreeWidget!=NULL );\n\n QList< QTreeWidgetItem* > items(\n m_UI->databaseTreeWidget->findItems(\n hash,\n Qt::MatchExactly | Qt::MatchRecursive,\n 1\n )\n );\n\n assert( items.isEmpty() || items.size() == 1 );\n\n \/*\n qDebug()\n << ( items.isEmpty() ? \"NONE\" : items.first()->text( 0 ) )\n << m_UI->databaseTreeWidget->selectionModel()->selectedIndexes().size();\n *\/\n\n#if 0\n\n m_UI->databaseTreeWidget->setCurrentItem(\n items.isEmpty() ? NULL : items.first(),\n 0,\n QItemSelectionModel::Clear |\n QItemSelectionModel::Current\n );\n#else\n if( items.isEmpty() )\n return;\n\n m_UI->databaseTreeWidget->setCurrentItem( items.first() );\n#endif\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_databaseTreeWidget_currentItemChanged( QTreeWidgetItem* current,\n\t\t\t\t\t QTreeWidgetItem* previous )\n{\n \/\/\n \/\/ Current\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString currentHash;\n\n TreeWidgetItem* currentItem = dynamic_cast< TreeWidgetItem* >( current );\n\n if( currentItem!=NULL && currentItem->parent()!=NULL )\n \/\/ if current is root and not NULL get the Id of the corresponding\n \/\/ Dataset.\n currentHash = currentItem->GetHash();\n\n \/\/\n \/\/ Previous\n\n \/\/ TODO: Should be DatabaseModel::DatasetId but widgets should not depend on models!!!\n QString previousHash;\n\n TreeWidgetItem* previousItem = dynamic_cast< TreeWidgetItem* >( previous );\n\n if( previousItem!=NULL )\n previousHash = previousItem->GetHash();\n\n \/\/\n \/\/ Emit event.\n emit CurrentDatasetChanged( currentHash, previousHash );\n}\n\n\/*******************************************************************************\/\nvoid\nDatabaseBrowserWidget\n::on_m_SearchLine_textChanged( const QString& search )\n{\n \/\/ \n \/\/ get the search text\n m_SearchText = search;\n\n#if 0\n \/\/ fill the tree with the application\n FillTree(); \n#else\n if( m_DatasetRootItem==NULL )\n return;\n\n for( int i=0; ichildCount(); ++i )\n {\n QTreeWidgetItem* item = m_DatasetRootItem->child( i );\n assert( item!=NULL );\n\n \/\/ Item is visible if search is empty or if alias contains\n \/\/ search-text.\n item->setHidden(\n !search.isEmpty() &&\n !item->text( 0 ).contains( search, Qt::CaseInsensitive )\n );\n }\n#endif\n}\n\n} \/\/ end namespace 'mvd'\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \"vector_utils.h\"\n#include \"time_utils.h\"\n\n#include \"vector_utils.cpp\"\n#include \"time_utils.cpp\"\n\n#include \"sse_set_intersection.cpp\"\n#include \"binarysearch_set_intersection.cpp\"\n\nconstexpr int STD = 0;\nconstexpr int SSE = 1;\nconstexpr int BINARY = 2;\n\nclass Application final {\n\n vec input_vec;\n static constexpr size_t input_size = 1024*1024;\n static constexpr size_t iterations = 1000;\n\n FILE* csv = nullptr;\n\npublic:\n void run() {\n\n csv = fopen(\"out.csv\", \"wt\");\n assert((csv != nullptr) && \"can't open file\");\n\n measure_time(\"create input table: \", [this]{\n input_vec = create_sorted(input_size);\n });\n\n for (size_t base_size: {128, 1024}) {\n for (size_t factor: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 50}) {\n const size_t size = base_size * factor;\n test_all(size);\n }\n }\n\n fclose(csv);\n }\n\nprivate:\n template \n void test(const char* info, const vec& a, const vec& b, int k) {\n\n vec result;\n volatile int32_t ref = 0;\n\n printf(\"%s [a.size = %lu, b.size = %lu, %d iterations] \", info, a.size(), b.size(), k);\n fflush(stdout);\n\n Clock::rep best_time = 0;\n int tmp = k;\n while (tmp-- > 0) {\n result.clear();\n const auto t1 = Clock::now();\n if constexpr (version == STD) {\n std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(result));\n } else if constexpr (version == SSE) {\n sse_set_intersection(a, b, std::back_inserter(result));\n } else if constexpr (version == BINARY) {\n binsearch_set_intersection(a, b, std::back_inserter(result));\n }\n const auto t2 = Clock::now();\n best_time += elapsed(t1, t2);\n\n ref += std::accumulate(result.begin(), result.end(), int32_t(0));\n }\n\n printf(\"%lu us (%d)\\n\", best_time, ref);\n\n fprintf(csv, \"%s,%lu,%lu,%lu\\n\", info, a.size(), b.size(), best_time);\n }\n\n void test_all(size_t size) {\n\n auto sampled = sample_sorted(input_vec, size);\n\n test(\"std\", sampled, input_vec, iterations);\n test(\"SSE\", sampled, input_vec, iterations);\n test(\"binsearch\", sampled, input_vec, iterations);\n }\n\n};\n\nint main() {\n\n Application app;\n app.run();\n}\n\nenable result validation#include \n#include \n\n#include \n\n#include \"vector_utils.h\"\n#include \"time_utils.h\"\n\n#include \"vector_utils.cpp\"\n#include \"time_utils.cpp\"\n\n#include \"sse_set_intersection.cpp\"\n#include \"binarysearch_set_intersection.cpp\"\n\nconstexpr int STD = 0;\nconstexpr int SSE = 1;\nconstexpr int BINARY = 2;\n\nclass Application final {\n\n vec input_vec;\n static constexpr size_t input_size = 1024*1024;\n static constexpr size_t iterations = 1000;\n\n FILE* csv = nullptr;\n\npublic:\n void run() {\n\n csv = fopen(\"out.csv\", \"wt\");\n assert((csv != nullptr) && \"can't open file\");\n\n measure_time(\"create input table: \", [this]{\n input_vec = create_sorted(input_size);\n });\n\n for (size_t base_size: {128, 1024}) {\n for (size_t factor: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 50}) {\n const size_t size = base_size * factor;\n test_all(size);\n }\n }\n\n fclose(csv);\n }\n\nprivate:\n template \n int32_t test(const char* info, const vec& a, const vec& b, int k, int32_t valid_ref = 0) {\n\n vec result;\n volatile int32_t ref = 0;\n\n printf(\"%s [a.size = %lu, b.size = %lu, %d iterations] \", info, a.size(), b.size(), k);\n fflush(stdout);\n\n Clock::rep best_time = 0;\n int tmp = k;\n while (tmp-- > 0) {\n result.clear();\n const auto t1 = Clock::now();\n if constexpr (version == STD) {\n std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(result));\n } else if constexpr (version == SSE) {\n sse_set_intersection(a, b, std::back_inserter(result));\n } else if constexpr (version == BINARY) {\n binsearch_set_intersection(a, b, std::back_inserter(result));\n }\n const auto t2 = Clock::now();\n best_time += elapsed(t1, t2);\n\n ref += std::accumulate(result.begin(), result.end(), int32_t(0));\n }\n\n printf(\"%lu us (%d)\", best_time, ref);\n if (valid_ref != 0 && valid_ref != ref) {\n printf(\" !!! ERROR !!!\");\n }\n\n putchar('\\n');\n\n fprintf(csv, \"%s,%lu,%lu,%lu\\n\", info, a.size(), b.size(), best_time);\n\n return ref;\n }\n\n void test_all(size_t size) {\n\n auto sampled = sample_sorted(input_vec, size);\n\n const int32_t ref = test(\"std\", sampled, input_vec, iterations);\n test(\"SSE\", sampled, input_vec, iterations, ref);\n test(\"binsearch\", sampled, input_vec, iterations, ref);\n }\n\n};\n\nint main() {\n\n Application app;\n app.run();\n}\n\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_CORE_PROFILING_HPP\n#define STAN_MATH_REV_CORE_PROFILING_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Class used for storing profiling information.\n *\/\nclass profile_info {\n private:\n bool active_;\n\n double fwd_pass_time_;\n double rev_pass_time_;\n size_t n_fwd_AD_passes_;\n size_t n_fwd_no_AD_passes_;\n size_t n_rev_passes_;\n size_t chain_stack_size_sum_;\n size_t nochain_stack_size_sum_;\n std::chrono::time_point fwd_pass_tp_;\n std::chrono::time_point rev_pass_tp_;\n size_t start_chain_stack_size_;\n size_t start_nochain_stack_size_;\n\n public:\n profile_info()\n : active_(false),\n fwd_pass_time_(0.0),\n rev_pass_time_(0.0),\n n_fwd_AD_passes_(0),\n n_fwd_no_AD_passes_(0),\n n_rev_passes_(0),\n chain_stack_size_sum_(0),\n nochain_stack_size_sum_(0),\n fwd_pass_tp_(std::chrono::steady_clock::now()),\n rev_pass_tp_(std::chrono::steady_clock::now()),\n start_chain_stack_size_(0),\n start_nochain_stack_size_(0){};\n\n bool is_active() const noexcept { return active_; }\n\n template \n void fwd_pass_start() {\n if (!is_constant::value) {\n start_chain_stack_size_ = ChainableStack::instance_->var_stack_.size();\n start_nochain_stack_size_\n = ChainableStack::instance_->var_nochain_stack_.size();\n }\n fwd_pass_tp_ = std::chrono::steady_clock::now();\n active_ = true;\n }\n\n template \n void fwd_pass_stop() {\n if (!is_constant::value) {\n n_fwd_AD_passes_++;\n chain_stack_size_sum_ += (ChainableStack::instance_->var_stack_.size()\n - start_chain_stack_size_ - 1);\n nochain_stack_size_sum_\n += (ChainableStack::instance_->var_nochain_stack_.size()\n - start_nochain_stack_size_);\n } else {\n n_fwd_no_AD_passes_++;\n }\n fwd_pass_time_ += std::chrono::duration(\n std::chrono::steady_clock::now() - fwd_pass_tp_)\n .count();\n active_ = false;\n }\n\n void rev_pass_start() { rev_pass_tp_ = std::chrono::steady_clock::now(); }\n\n void rev_pass_stop() {\n rev_pass_time_ += std::chrono::duration(\n std::chrono::steady_clock::now() - rev_pass_tp_)\n .count();\n n_rev_passes_++;\n }\n\n size_t get_chain_stack_used() const noexcept {\n return chain_stack_size_sum_;\n };\n\n size_t get_nochain_stack_used() const noexcept {\n return nochain_stack_size_sum_;\n };\n\n size_t get_num_no_AD_fwd_passes() const noexcept {\n return n_fwd_no_AD_passes_;\n }\n\n size_t get_num_AD_fwd_passes() const noexcept { return n_fwd_AD_passes_; }\n\n size_t get_num_fwd_passes() const noexcept {\n return n_fwd_AD_passes_ + n_fwd_no_AD_passes_;\n }\n\n double get_fwd_time() const noexcept { return fwd_pass_time_; }\n\n size_t get_num_rev_passes() const noexcept { return n_rev_passes_; }\n\n double get_rev_time() const noexcept { return rev_pass_time_; }\n};\n\nusing profile_key = std::pair;\n\nusing profile_map = std::map;\n\n\/**\n * Profiles C++ lines where the object is in scope.\n * When T is var, the constructor starts the profile for the forward pass\n * and places a var with a callback to stop the reverse pass on the\n * AD tape. The destructor stops the profile for the forward pass and\n * places a var with a callback to start the profile for the reverse pass.\n * When T is not var, the constructor and destructor only profile the\n *\n *\n * @tparam T type of profile class. If var, the created object is used\n * to profile reverse mode AD. Only profiles the forward pass otherwise.\n *\/\ntemplate \nclass profile {\n profile_key key_;\n profile_info* profile_;\n\n public:\n profile(std::string name, profile_map& profiles)\n : key_({name, std::this_thread::get_id()}) {\n profile_map::iterator p = profiles.find(key_);\n if (p == profiles.end()) {\n profiles[key_] = profile_info();\n }\n profile_ = &profiles[key_];\n if (profile_->is_active()) {\n std::ostringstream msg;\n msg << \"Profile '\" << key_.first << \"' already started!\";\n throw std::runtime_error(msg.str());\n }\n profile_->fwd_pass_start();\n if (!is_constant::value) {\n reverse_pass_callback([=]() mutable { profile_->rev_pass_stop(); });\n }\n }\n ~profile() {\n profile_->fwd_pass_stop();\n if (!is_constant::value) {\n reverse_pass_callback([=]() mutable { profile_->rev_pass_start(); });\n }\n }\n};\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nremove \";\"#ifndef STAN_MATH_REV_CORE_PROFILING_HPP\n#define STAN_MATH_REV_CORE_PROFILING_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Class used for storing profiling information.\n *\/\nclass profile_info {\n private:\n bool active_;\n\n double fwd_pass_time_;\n double rev_pass_time_;\n size_t n_fwd_AD_passes_;\n size_t n_fwd_no_AD_passes_;\n size_t n_rev_passes_;\n size_t chain_stack_size_sum_;\n size_t nochain_stack_size_sum_;\n std::chrono::time_point fwd_pass_tp_;\n std::chrono::time_point rev_pass_tp_;\n size_t start_chain_stack_size_;\n size_t start_nochain_stack_size_;\n\n public:\n profile_info()\n : active_(false),\n fwd_pass_time_(0.0),\n rev_pass_time_(0.0),\n n_fwd_AD_passes_(0),\n n_fwd_no_AD_passes_(0),\n n_rev_passes_(0),\n chain_stack_size_sum_(0),\n nochain_stack_size_sum_(0),\n fwd_pass_tp_(std::chrono::steady_clock::now()),\n rev_pass_tp_(std::chrono::steady_clock::now()),\n start_chain_stack_size_(0),\n start_nochain_stack_size_(0){}\n\n bool is_active() const noexcept { return active_; }\n\n template \n void fwd_pass_start() {\n if (!is_constant::value) {\n start_chain_stack_size_ = ChainableStack::instance_->var_stack_.size();\n start_nochain_stack_size_\n = ChainableStack::instance_->var_nochain_stack_.size();\n }\n fwd_pass_tp_ = std::chrono::steady_clock::now();\n active_ = true;\n }\n\n template \n void fwd_pass_stop() {\n if (!is_constant::value) {\n n_fwd_AD_passes_++;\n chain_stack_size_sum_ += (ChainableStack::instance_->var_stack_.size()\n - start_chain_stack_size_ - 1);\n nochain_stack_size_sum_\n += (ChainableStack::instance_->var_nochain_stack_.size()\n - start_nochain_stack_size_);\n } else {\n n_fwd_no_AD_passes_++;\n }\n fwd_pass_time_ += std::chrono::duration(\n std::chrono::steady_clock::now() - fwd_pass_tp_)\n .count();\n active_ = false;\n }\n\n void rev_pass_start() { rev_pass_tp_ = std::chrono::steady_clock::now(); }\n\n void rev_pass_stop() {\n rev_pass_time_ += std::chrono::duration(\n std::chrono::steady_clock::now() - rev_pass_tp_)\n .count();\n n_rev_passes_++;\n }\n\n size_t get_chain_stack_used() const noexcept {\n return chain_stack_size_sum_;\n };\n\n size_t get_nochain_stack_used() const noexcept {\n return nochain_stack_size_sum_;\n };\n\n size_t get_num_no_AD_fwd_passes() const noexcept {\n return n_fwd_no_AD_passes_;\n }\n\n size_t get_num_AD_fwd_passes() const noexcept { return n_fwd_AD_passes_; }\n\n size_t get_num_fwd_passes() const noexcept {\n return n_fwd_AD_passes_ + n_fwd_no_AD_passes_;\n }\n\n double get_fwd_time() const noexcept { return fwd_pass_time_; }\n\n size_t get_num_rev_passes() const noexcept { return n_rev_passes_; }\n\n double get_rev_time() const noexcept { return rev_pass_time_; }\n};\n\nusing profile_key = std::pair;\n\nusing profile_map = std::map;\n\n\/**\n * Profiles C++ lines where the object is in scope.\n * When T is var, the constructor starts the profile for the forward pass\n * and places a var with a callback to stop the reverse pass on the\n * AD tape. The destructor stops the profile for the forward pass and\n * places a var with a callback to start the profile for the reverse pass.\n * When T is not var, the constructor and destructor only profile the\n *\n *\n * @tparam T type of profile class. If var, the created object is used\n * to profile reverse mode AD. Only profiles the forward pass otherwise.\n *\/\ntemplate \nclass profile {\n profile_key key_;\n profile_info* profile_;\n\n public:\n profile(std::string name, profile_map& profiles)\n : key_({name, std::this_thread::get_id()}) {\n profile_map::iterator p = profiles.find(key_);\n if (p == profiles.end()) {\n profiles[key_] = profile_info();\n }\n profile_ = &profiles[key_];\n if (profile_->is_active()) {\n std::ostringstream msg;\n msg << \"Profile '\" << key_.first << \"' already started!\";\n throw std::runtime_error(msg.str());\n }\n profile_->fwd_pass_start();\n if (!is_constant::value) {\n reverse_pass_callback([=]() mutable { profile_->rev_pass_stop(); });\n }\n }\n ~profile() {\n profile_->fwd_pass_stop();\n if (!is_constant::value) {\n reverse_pass_callback([=]() mutable { profile_->rev_pass_start(); });\n }\n }\n};\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file\n *\n * @brief Tests for KDB\n *\n * @copyright BSD License (see doc\/COPYING or http:\/\/www.libelektra.org)\n *\n *\/\n\n#include \n\n#include \n\n#include \n\nclass Error : public ::testing::Test\n{\nprotected:\n\tstatic const std::string testRoot;\n\tstatic const std::string configFileRoot;\n\n\n\ttesting::Namespaces namespaces;\n\ttesting::MountpointPtr mpRoot;\n\n\tError () : namespaces ()\n\t{\n\t}\n\n\tvirtual void SetUp () override\n\t{\n\t\tmpRoot.reset (new testing::Mountpoint (testRoot, configFileRoot));\n\t}\n\n\tvirtual void TearDown () override\n\t{\n\t\tmpRoot.reset ();\n\t}\n};\n\nconst std::string Error::testRoot = \"\/tests\/kdb\/\";\nconst std::string Error::configFileRoot = \"kdbFileError.dump\";\n\n\nTEST_F (Error, Simple)\n{\n\tusing namespace kdb;\n\tKDB kdb;\n\tKeySet ks;\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdb.get (ks, testRoot), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ks.size (), 1) << \"did not keep key at get\" << ks;\n\n\tKey parentKey (testRoot, KEY_END);\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error\";\n\tstruct stat buf;\n\tASSERT_EQ (stat (mpRoot->systemConfigFile.c_str (), &buf), -1) << \"found wrong file\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 10);\n\n\tASSERT_EQ (ks.size (), 1) << \"did not keep key at set\" << ks;\n}\n\nTEST_F (Error, Again)\n{\n\tusing namespace kdb;\n\tKDB kdb;\n\tKeySet ks;\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdb.get (ks, testRoot), 0) << \"should be nothing to update\";\n\n\tKey parentKey (testRoot, KEY_END);\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 10);\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"110\", KEY_END));\n\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error (again)\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 110);\n\n\tASSERT_EQ (ks.size (), 1) << \"did not keep key at set (again)\" << ks;\n}\n\n\nTEST_F (Error, CSimple)\n{\n\tusing namespace ckdb;\n\tKey * parentKey = keyNew (testRoot.c_str (), KEY_END);\n\tKDB * kdb = kdbOpen (parentKey);\n\tKeySet * ks = ksNew (20, KS_END);\n\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key\").c_str (), KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdbGet (kdb, ks, parentKey), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ksGetSize (ks), 1) << \"did not keep key at get\" << ks;\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), -1) << \"could not trigger error\";\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\tkdbClose (kdb, parentKey);\n\tkeyDel (parentKey);\n\tksDel (ks);\n}\n\nTEST_F (Error, ToWarning)\n{\n\tusing namespace ckdb;\n\tKey * parentKey = keyNew (testRoot.c_str (), KEY_END);\n\tKDB * kdb = kdbOpen (parentKey);\n\tKeySet * ks = ksNew (20, KS_END);\n\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key1\").c_str (), KEY_META, \"trigger\/error\/nofail\", \"10\", KEY_END));\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key2\").c_str (), KEY_META, \"trigger\/error\", \"110\", KEY_END));\n\n\tASSERT_EQ (kdbGet (kdb, ks, parentKey), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ksGetSize (ks), 2) << \"did not keep key at get\" << ks;\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), -1) << \"could not trigger error\";\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"warnings\/#00\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"warnings\/#00\/number\")), \"110\");\n\n\n\tkdbClose (kdb, parentKey);\n\tkeyDel (parentKey);\n\tksDel (ks);\n}\n\nTEST_F (Error, Persists)\n{\n\tusing namespace ckdb;\n\tKey * parentKey = keyNew (testRoot.c_str (), KEY_END);\n\tKDB * kdb = kdbOpen (parentKey);\n\tKeySet * ks = ksNew (20, KS_END);\n\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key\").c_str (), KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdbGet (kdb, ks, parentKey), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ksGetSize (ks), 1) << \"did not keep key at get\" << ks;\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), -1) << \"could not trigger error\";\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\n\tkeyDel (ksLookup (ks, keyNew ((\"system\" + testRoot + \"key\").c_str (), KEY_END), KDB_O_POP));\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), 0) << \"kdbSet failed\";\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\n\tkdbClose (kdb, parentKey);\n\tkeyDel (parentKey);\n\tksDel (ks);\n}\ntest: readd repeat again test case\/**\n * @file\n *\n * @brief Tests for KDB\n *\n * @copyright BSD License (see doc\/COPYING or http:\/\/www.libelektra.org)\n *\n *\/\n\n#include \n\n#include \n\n#include \n\nclass Error : public ::testing::Test\n{\nprotected:\n\tstatic const std::string testRoot;\n\tstatic const std::string configFileRoot;\n\n\n\ttesting::Namespaces namespaces;\n\ttesting::MountpointPtr mpRoot;\n\n\tError () : namespaces ()\n\t{\n\t}\n\n\tvirtual void SetUp () override\n\t{\n\t\tmpRoot.reset (new testing::Mountpoint (testRoot, configFileRoot));\n\t}\n\n\tvirtual void TearDown () override\n\t{\n\t\tmpRoot.reset ();\n\t}\n};\n\nconst std::string Error::testRoot = \"\/tests\/kdb\/\";\nconst std::string Error::configFileRoot = \"kdbFileError.dump\";\n\n\nTEST_F (Error, Simple)\n{\n\tusing namespace kdb;\n\tKDB kdb;\n\tKeySet ks;\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdb.get (ks, testRoot), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ks.size (), 1) << \"did not keep key at get\" << ks;\n\n\tKey parentKey (testRoot, KEY_END);\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error\";\n\tstruct stat buf;\n\tASSERT_EQ (stat (mpRoot->systemConfigFile.c_str (), &buf), -1) << \"found wrong file\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 10);\n\n\tASSERT_EQ (ks.size (), 1) << \"did not keep key at set\" << ks;\n}\n\nTEST_F (Error, Again)\n{\n\tusing namespace kdb;\n\tKDB kdb;\n\tKeySet ks;\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdb.get (ks, testRoot), 0) << \"should be nothing to update\";\n\n\tKey parentKey (testRoot, KEY_END);\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 10);\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"110\", KEY_END));\n\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error (again)\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 110);\n\n\tASSERT_EQ (ks.size (), 1) << \"did not keep key at set (again)\" << ks;\n}\n\nTEST_F (Error, AgainRepeat)\n{\n\tusing namespace kdb;\n\tKDB kdb;\n\tKeySet ks;\n\n\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdb.get (ks, testRoot), 0) << \"should be nothing to update\";\n\n\tKey parentKey (testRoot, KEY_END);\n\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error\";\n\n\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 10);\n\n\tfor (int i = 0; i < 10; ++i)\n\t{\n\t\tks.append (Key (\"system\" + testRoot + \"key\", KEY_END));\n\n\t\tEXPECT_NO_THROW (kdb.set (ks, parentKey)) << \"no error trigger?\";\n\n\t\tks.append (Key (\"system\" + testRoot + \"key\", KEY_META, \"trigger\/error\", std::to_string (119 + i).c_str (), KEY_END));\n\n\t\tEXPECT_THROW (kdb.set (ks, parentKey), kdb::KDBException) << \"could not trigger error (again)\";\n\n\t\tEXPECT_TRUE (parentKey.getMeta (\"error\"));\n\t\tEXPECT_TRUE (parentKey.getMeta (\"error\/number\"));\n\t\tEXPECT_EQ (parentKey.getMeta (\"error\/number\"), 119 + i);\n\n\t\tASSERT_EQ (ks.size (), 1) << \"did not keep key at set (again)\" << ks;\n\t}\n}\n\n\nTEST_F (Error, CSimple)\n{\n\tusing namespace ckdb;\n\tKey * parentKey = keyNew (testRoot.c_str (), KEY_END);\n\tKDB * kdb = kdbOpen (parentKey);\n\tKeySet * ks = ksNew (20, KS_END);\n\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key\").c_str (), KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdbGet (kdb, ks, parentKey), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ksGetSize (ks), 1) << \"did not keep key at get\" << ks;\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), -1) << \"could not trigger error\";\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\tkdbClose (kdb, parentKey);\n\tkeyDel (parentKey);\n\tksDel (ks);\n}\n\nTEST_F (Error, ToWarning)\n{\n\tusing namespace ckdb;\n\tKey * parentKey = keyNew (testRoot.c_str (), KEY_END);\n\tKDB * kdb = kdbOpen (parentKey);\n\tKeySet * ks = ksNew (20, KS_END);\n\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key1\").c_str (), KEY_META, \"trigger\/error\/nofail\", \"10\", KEY_END));\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key2\").c_str (), KEY_META, \"trigger\/error\", \"110\", KEY_END));\n\n\tASSERT_EQ (kdbGet (kdb, ks, parentKey), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ksGetSize (ks), 2) << \"did not keep key at get\" << ks;\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), -1) << \"could not trigger error\";\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"warnings\/#00\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"warnings\/#00\/number\")), \"110\");\n\n\n\tkdbClose (kdb, parentKey);\n\tkeyDel (parentKey);\n\tksDel (ks);\n}\n\nTEST_F (Error, Persists)\n{\n\tusing namespace ckdb;\n\tKey * parentKey = keyNew (testRoot.c_str (), KEY_END);\n\tKDB * kdb = kdbOpen (parentKey);\n\tKeySet * ks = ksNew (20, KS_END);\n\n\tksAppendKey (ks, keyNew ((\"system\" + testRoot + \"key\").c_str (), KEY_META, \"trigger\/error\", \"10\", KEY_END));\n\n\tASSERT_EQ (kdbGet (kdb, ks, parentKey), 0) << \"should be nothing to update\";\n\tASSERT_EQ (ksGetSize (ks), 1) << \"did not keep key at get\" << ks;\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), -1) << \"could not trigger error\";\n\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\n\tkeyDel (ksLookup (ks, keyNew ((\"system\" + testRoot + \"key\").c_str (), KEY_END), KDB_O_POP));\n\n\tEXPECT_EQ (kdbSet (kdb, ks, parentKey), 0) << \"kdbSet failed\";\n\tEXPECT_TRUE (ckdb::keyGetMeta (parentKey, \"error\"));\n\tEXPECT_STREQ (keyString (ckdb::keyGetMeta (parentKey, \"error\/number\")), \"10\");\n\n\n\tkdbClose (kdb, parentKey);\n\tkeyDel (parentKey);\n\tksDel (ks);\n}\n<|endoftext|>"} {"text":"#include \n\nusing namespace std;\n\nTAU_BEGIN\n\nnamespace Generate\n{\n\tbool Agent::Generate(TauParser const &p, const char *fname) override\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Namespace(TauParser::AstNode const &ns)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Class(TauParser::AstNode const &cl)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Property(TauParser::AstNode const &prop)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Method(TauParser::AstNode const &method)\n\t{\n\t\treturn false;\n\t}\n\n\tstd::string Agent::ArgType(std::string &&text) const\n\t{\n\t\treturn move(text);\n\t}\n\n\tstd::string ReturnType(std::string &&text) const\n\t{\n\t\treturn move(text);\n\t}\n}\n\nTAU_END\nFalling asleep#include \n\nusing namespace std;\n\nTAU_BEGIN\n\nnamespace Generate\n{\n\tbool Agent::Generate(TauParser const &p, const char *fname)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Namespace(TauParser::AstNode const &ns)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Class(TauParser::AstNode const &cl)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Property(TauParser::AstNode const &prop)\n\t{\n\t\treturn false;\n\t}\n\n\tbool Agent::Method(TauParser::AstNode const &method)\n\t{\n\t\treturn false;\n\t}\n\n\tstd::string Agent::ArgType(std::string &&text) const\n\t{\n\t\treturn move(text);\n\t}\n\n\tstd::string Agent::ReturnType(std::string &&text) const\n\t{\n\t\treturn move(text);\n\t}\n}\n\nTAU_END\n<|endoftext|>"} {"text":"Revert \"MLDB-1058: improved performance by making HttpRestEndpoint::RestConnectionHandler::sendResponse call \"send\" directly, instead of instantiating an HttpResponse\"<|endoftext|>"} {"text":"EDID vendor and product IDs were swapped. Oops!<|endoftext|>"} {"text":"\/\/\n\/\/ Created by dar on 1\/23\/16.\n\/\/\n\n#include \n#include \n#include \"Application.h\"\n#include \"render\/RenderManager.h\"\n#include \"logging.h\"\n#include \n#include \n\nApplication::Application() {\n this->renderer = new RenderManager();\n auto switchWindow = [&](Window *window) {\n if (window == nullptr) {\n this->running = false;\n return false;\n }\n this->previousWindow = this->window;\n this->window = window;\n this->renderer->initWindow(this->window);\n this->resize(this->renderer->getRenderContext()->getWindowWidth(), this->renderer->getRenderContext()->getWindowHeight());\n return true;\n };\n this->window = new LoadingScreen(new ApplicationContext(switchWindow));\n this->timer = new Timer();\n this->inputManager = new InputManager();\n this->reinit();\n this->resize(1366, 750);\n}\n\nvoid Application::reinit() {\n this->renderer->init();\n this->renderer->initWindow(this->window); \/\/TODO\n timer->GetDelta(); \/\/if not called right now, first call in game loop would return a very huge value\n this->inputManager->reload();\n}\n\n\nvoid Application::run() {\n while (isRunning()) {\n update(true);\n }\n}\n\nvoid Application::update(bool dynamic) {\n if (this->previousWindow != nullptr) {\n delete this->previousWindow;\n this->previousWindow = nullptr;\n }\n if (dynamic) {\n this->deltaTimeHistory[this->ticks] = timer->GetDelta();\n if (this->ticks == 14) {\n this->averageDeltaTime = 0.0;\n for (int i = 0; i < 15; i++) {\n this->averageDeltaTime += this->deltaTimeHistory[i];\n }\n }\n this->getCurrentWindow()->tick(this->averageDeltaTime * 4.0); \/\/multiplied by 4.0 to make the whole equal ~1.0\n } else {\n this->getCurrentWindow()->tick(1.0);\n }\n this->renderer->render(this->getCurrentWindow());\n if (!IS_MOBILE) this->handleEvents();\n this->inputManager->tick(this->getCurrentWindow());\n this->ticks++;\n if (this->ticks > 14) {\n this->ticks = 0;\n }\n}\n\nApplication::~Application() {\n delete this->window;\n}\n\n#ifdef __ANDROID__\n\n#include \n\nApplication *application = nullptr;\n\nextern \"C\" {\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj);\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height);\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj);\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y);\n};\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj) {\n if (application == nullptr || application->getCurrentWindow() == nullptr) {\n application = new Application();\n } else {\n application->reinit();\n }\n \/*jclass cls = env->GetObjectClass(obj);\n jmethodID mid = env->GetMethodID(cls, \"loadTexture\", \"()V\");\n if (mid == 0) {\n return;\n }\n env->CallVoidMethod(obj, mid);*\/\n}\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height) {\n application->resize(width, height);\n}\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj) {\n application->update(false);\n if (!application->isRunning()) {\n jclass cls = env->GetObjectClass(obj);\n jmethodID mid = env->GetMethodID(cls, \"exit\", \"()V\");\n if (mid != 0) {\n delete application;\n env->CallVoidMethod(obj, mid);\n }\n }\n}\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y) {\n application->handleClick(i, action, x, y);\n}\n\n#endif \/\/__ANDROID__\n\nvoid Application::resize(int width, int height) {\n this->getCurrentWindow()->reload(width, height);\n this->renderer->resize(this->getCurrentWindow(), width, height);\n}\n\nvoid Application::handleClick(int i, int action, float x, float y) {\n this->inputManager->handleClick(i, action, x, y);\n}\n\nvoid Application::handleEvents() {\n#ifndef __ANDROID__\n while (SDL_PollEvent(&e) != 0) {\n switch (e.type) {\n case SDL_QUIT:\n this->running = false;\n break;\n case SDL_WINDOWEVENT:\n if (e.window.event == SDL_WINDOWEVENT_RESIZED || e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {\n this->resize((unsigned int) e.window.data1, (unsigned int) e.window.data2);\n }\n break;\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n this->inputManager->handleKeypress(&e);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n Log::debug(\"%s button with id %d\\n\", e.type == SDL_MOUSEBUTTONDOWN ? \"Pressed\" : \"Unpressed\", e.button.button);\n case SDL_MOUSEMOTION: {\n int button = (int) round(log((double) e.button.button) \/ log(2.0)) + 1;\n if (button < 0 || button >= 5) break;\n int x, y;\n SDL_GetMouseState(&x, &y);\n this->handleClick(button, e.type == SDL_MOUSEBUTTONDOWN ? 0 : (e.type == SDL_MOUSEBUTTONUP ? 1 : 2), x, y);\n break;\n }\n }\n }\n#else \/\/__ANDROID__\n LOGW(\"SDL is not supported on this platform\\n\");\n#endif \/\/__ANDROID__\n\n}\nKeep application object by value on Android\/\/\n\/\/ Created by dar on 1\/23\/16.\n\/\/\n\n#include \n#include \n#include \"Application.h\"\n#include \"render\/RenderManager.h\"\n#include \"logging.h\"\n#include \n#include \n\nApplication::Application() {\n this->renderer = new RenderManager();\n auto switchWindow = [&](Window *window) {\n if (window == nullptr) {\n this->running = false;\n return false;\n }\n this->previousWindow = this->window;\n this->window = window;\n this->renderer->initWindow(this->window);\n this->resize(this->renderer->getRenderContext()->getWindowWidth(), this->renderer->getRenderContext()->getWindowHeight());\n return true;\n };\n this->window = new LoadingScreen(new ApplicationContext(switchWindow));\n this->timer = new Timer();\n this->inputManager = new InputManager();\n this->reinit();\n this->resize(1366, 750);\n}\n\nvoid Application::reinit() {\n this->renderer->init();\n this->renderer->initWindow(this->window); \/\/TODO\n timer->GetDelta(); \/\/if not called right now, first call in game loop would return a very huge value\n this->inputManager->reload();\n}\n\n\nvoid Application::run() {\n while (isRunning()) {\n update(true);\n }\n}\n\nvoid Application::update(bool dynamic) {\n if (this->previousWindow != nullptr) {\n delete this->previousWindow;\n this->previousWindow = nullptr;\n }\n if (dynamic) {\n this->deltaTimeHistory[this->ticks] = timer->GetDelta();\n if (this->ticks == 14) {\n this->averageDeltaTime = 0.0;\n for (int i = 0; i < 15; i++) {\n this->averageDeltaTime += this->deltaTimeHistory[i];\n }\n }\n this->getCurrentWindow()->tick(this->averageDeltaTime * 4.0); \/\/multiplied by 4.0 to make the whole equal ~1.0\n } else {\n this->getCurrentWindow()->tick(1.0);\n }\n this->renderer->render(this->getCurrentWindow());\n if (!IS_MOBILE) this->handleEvents();\n this->inputManager->tick(this->getCurrentWindow());\n this->ticks++;\n if (this->ticks > 14) {\n this->ticks = 0;\n }\n}\n\nApplication::~Application() {\n delete this->window;\n}\n\n#ifdef __ANDROID__\n\n#include \n\nApplication application;\nbool initialized = false;\n\nextern \"C\" {\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj);\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height);\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj);\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y);\n};\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_init(JNIEnv *env, jobject obj) {\n if (initialized) {\n application.reinit();\n }\n \/*jclass cls = env->GetObjectClass(obj);\n jmethodID mid = env->GetMethodID(cls, \"loadTexture\", \"()V\");\n if (mid == 0) {\n return;\n }\n env->CallVoidMethod(obj, mid);*\/\n}\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_resize(JNIEnv *env, jobject obj, jint width, jint height) {\n application.resize(width, height);\n}\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_tick(JNIEnv *env, jobject obj) {\n application.update(false);\n if (!application.isRunning()) {\n jclass cls = env->GetObjectClass(obj);\n jmethodID mid = env->GetMethodID(cls, \"exit\", \"()V\");\n if (mid != 0) {\n env->CallVoidMethod(obj, mid);\n }\n }\n}\n\nJNIEXPORT void JNICALL Java_tk_approach_android_spookytom_JniBridge_handleTouch(JNIEnv *env, jobject obj, jint i, jint action, jfloat x, jfloat y) {\n application.handleClick(i, action, x, y);\n}\n\n#endif \/\/__ANDROID__\n\nvoid Application::resize(int width, int height) {\n this->getCurrentWindow()->reload(width, height);\n this->renderer->resize(this->getCurrentWindow(), width, height);\n}\n\nvoid Application::handleClick(int i, int action, float x, float y) {\n this->inputManager->handleClick(i, action, x, y);\n}\n\nvoid Application::handleEvents() {\n#ifndef __ANDROID__\n while (SDL_PollEvent(&e) != 0) {\n switch (e.type) {\n case SDL_QUIT:\n this->running = false;\n break;\n case SDL_WINDOWEVENT:\n if (e.window.event == SDL_WINDOWEVENT_RESIZED || e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {\n this->resize((unsigned int) e.window.data1, (unsigned int) e.window.data2);\n }\n break;\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n this->inputManager->handleKeypress(&e);\n break;\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n Log::debug(\"%s button with id %d\\n\", e.type == SDL_MOUSEBUTTONDOWN ? \"Pressed\" : \"Unpressed\", e.button.button);\n case SDL_MOUSEMOTION: {\n int button = (int) round(log((double) e.button.button) \/ log(2.0)) + 1;\n if (button < 0 || button >= 5) break;\n int x, y;\n SDL_GetMouseState(&x, &y);\n this->handleClick(button, e.type == SDL_MOUSEBUTTONDOWN ? 0 : (e.type == SDL_MOUSEBUTTONUP ? 1 : 2), x, y);\n break;\n }\n }\n }\n#else \/\/__ANDROID__\n LOGW(\"SDL is not supported on this platform\\n\");\n#endif \/\/__ANDROID__\n\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of playd.\n\/\/ playd is licensed under the MIT licence: see LICENSE.txt.\n\n\/**\n * @file\n * Implementation of the Mp3AudioSource class.\n * @see audio\/sources\/mp3.hpp\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n#include \n}\n\n#include \"..\/..\/errors.hpp\"\n#include \"..\/..\/messages.h\"\n#include \"..\/audio_source.hpp\"\n#include \"..\/sample_formats.hpp\"\n#include \"mp3.hpp\"\n\n\/\/ This value is somewhat arbitrary, but corresponds to the minimum buffer size\n\/\/ used by ffmpeg, so it's probably sensible.\nconst size_t Mp3AudioSource::BUFFER_SIZE = 16384;\n\nMp3AudioSource::Mp3AudioSource(const std::string &path)\n : AudioSource(path), buffer(BUFFER_SIZE), context(nullptr)\n{\n\tthis->context = mpg123_new(nullptr, nullptr);\n\tmpg123_format_none(this->context);\n\n\tconst long *rates = nullptr;\n\tsize_t nrates = 0;\n\tmpg123_rates(&rates, &nrates);\n\tfor (size_t r = 0; r < nrates; r++) {\n\t\tDebug() << \"trying to enable formats at \" << rates[r]\n\t\t << std::endl;\n\t\tAddFormat(rates[r]);\n\t}\n\n\tif (mpg123_open(this->context, path.c_str()) == MPG123_ERR) {\n\t\tthrow FileError(\"mp3: can't open \" + path + \": \" +\n\t\t mpg123_strerror(this->context));\n\t}\n\n\tDebug() << \"mp3: sample rate:\" << this->SampleRate() << std::endl;\n\tDebug() << \"mp3: bytes per sample:\" << this->BytesPerSample()\n\t << std::endl;\n\tDebug() << \"mp3: channels:\" << (int)this->ChannelCount() << std::endl;\n\tDebug() << \"mp3: playd format:\" << (int)this->OutputSampleFormat()\n\t << std::endl;\n}\n\nMp3AudioSource::~Mp3AudioSource()\n{\n\tmpg123_delete(this->context);\n\tthis->context = nullptr;\n}\n\nvoid Mp3AudioSource::AddFormat(long rate)\n{\n\t\/\/ The requested encodings correspond to the sample formats available in\n\t\/\/ the SampleFormat enum.\n\tif (mpg123_format(this->context, rate, MPG123_STEREO | MPG123_MONO,\n\t (MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_8 |\n\t MPG123_ENC_SIGNED_16 | MPG123_ENC_SIGNED_24 |\n\t MPG123_ENC_SIGNED_32 | MPG123_ENC_FLOAT_32)) ==\n\t MPG123_ERR) {\n\t\t\/\/ Ignore the error for now -- another sample rate may be\n\t\t\/\/ available.\n\t\t\/\/ If no sample rates work, loading a file will fail anyway.\n\t\tDebug() << \"can't support\" << rate << std::endl;\n\t};\n}\n\nstd::uint8_t Mp3AudioSource::ChannelCount() const\n{\n\tassert(this->context != nullptr);\n\n\tint chans = 0;\n\tmpg123_getformat(this->context, nullptr, &chans, nullptr);\n\tassert(chans != 0);\n\treturn static_cast(chans);\n}\n\nstd::uint32_t Mp3AudioSource::SampleRate() const\n{\n\tassert(this->context != nullptr);\n\n\tlong rate = 0;\n\tmpg123_getformat(this->context, &rate, nullptr, nullptr);\n\n\tassert(0 < rate);\n\t\/\/ INT32_MAX isn't a typo; if we compare against UINT32_MAX, we'll\n\t\/\/ set off sign-compare errors, and the sample rate shouldn't be above\n\t\/\/ INT32_MAX anyroad.\n\tassert(rate <= INT32_MAX);\n\treturn static_cast(rate);\n}\n\nstd::uint64_t Mp3AudioSource::Seek(std::uint64_t in_samples)\n{\n\tassert(this->context != nullptr);\n\n\t\/\/ See BytesPerSample() for an explanation of this ChannelCount().\n\tauto mono_samples = in_samples * this->ChannelCount();\n\n\t\/\/ Have we tried to seek past the end of the file?\n\tauto clen = static_cast(mpg123_length(this->context));\n\tif (clen < mono_samples) {\n\t\tDebug() << \"mp3: seek at\" << mono_samples << \"past EOF at\"\n\t\t << clen << std::endl;\n\t\tthrow SeekError(MSG_SEEK_FAIL);\n\t}\n\n\tif (mpg123_seek(this->context, mono_samples, SEEK_SET) == MPG123_ERR) {\n\t\tDebug() << \"mp3: seek failed:\" << mpg123_strerror(this->context)\n\t\t << std::endl;\n\t\tthrow SeekError(MSG_SEEK_FAIL);\n\t}\n\n\t\/\/ The actual seek position may not be the same as the requested\n\t\/\/ position.\n\t\/\/ mpg123_tell gives us the exact mono-samples position.\n\treturn mpg123_tell(this->context) \/ this->ChannelCount();\n}\n\nMp3AudioSource::DecodeResult Mp3AudioSource::Decode()\n{\n\tassert(this->context != nullptr);\n\n\tauto buf = reinterpret_cast(&this->buffer.front());\n\tsize_t rbytes = 0;\n\tint err = mpg123_read(this->context, buf, this->buffer.size(), &rbytes);\n\n\tDecodeVector decoded;\n\tDecodeState decode_state;\n\n\tif (err == MPG123_DONE) {\n\t\tDebug() << \"mp3: end of file\" << std::endl;\n\t\tdecode_state = DecodeState::END_OF_FILE;\n\t} else if (err != MPG123_OK && err != MPG123_NEW_FORMAT) {\n\t\tDebug() << \"mp3: decode error:\" << mpg123_strerror(this->context)\n\t\t << std::endl;\n\t\tdecode_state = DecodeState::END_OF_FILE;\n\t} else {\n\t\tdecode_state = DecodeState::DECODING;\n\n\t\t\/\/ Copy only the bit of the buffer occupied by decoded data\n\t\tauto front = this->buffer.begin();\n\t\tdecoded = DecodeVector(front, front + rbytes);\n\t}\n\n\treturn std::make_pair(decode_state, decoded);\n}\n\nSampleFormat Mp3AudioSource::OutputSampleFormat() const\n{\n\tassert(this->context != nullptr);\n\n\tint encoding = 0;\n\tmpg123_getformat(this->context, nullptr, nullptr, &encoding);\n\n\tswitch (encoding) {\n\t\tcase MPG123_ENC_UNSIGNED_8:\n\t\t\treturn SampleFormat::PACKED_UNSIGNED_INT_8;\n\t\tcase MPG123_ENC_SIGNED_8:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_8;\n\t\tcase MPG123_ENC_SIGNED_16:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_16;\n\t\tcase MPG123_ENC_SIGNED_24:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_24;\n\t\tcase MPG123_ENC_SIGNED_32:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_32;\n\t\tcase MPG123_ENC_FLOAT_32:\n\t\t\treturn SampleFormat::PACKED_FLOAT_32;\n\t\tdefault:\n\t\t\t\/\/ We shouldn't get here, if the format was set up\n\t\t\t\/\/ correctly earlier.\n\t\t\tassert(false);\n\t}\n}\nAdd polyfills for Ubuntu 12.04's ancient libmpg123.\/\/ This file is part of playd.\n\/\/ playd is licensed under the MIT licence: see LICENSE.txt.\n\n\/**\n * @file\n * Implementation of the Mp3AudioSource class.\n * @see audio\/sources\/mp3.hpp\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" {\n#include \n}\n\n#include \"..\/..\/errors.hpp\"\n#include \"..\/..\/messages.h\"\n#include \"..\/audio_source.hpp\"\n#include \"..\/sample_formats.hpp\"\n#include \"mp3.hpp\"\n\n\/\/ Fix for the ancient 2010 version of mpg123 carried by Ubuntu 12.04 and pals,\n\/\/ which doesn't have 24-bit support\n\/\/ See http:\/\/www.mpg123.de\/cgi-bin\/scm\/mpg123\/trunk\/NEWS?pathrev=2791\n#if MPG123_API_VERSION < 28\n\t\/\/ Let us be able to omit the check for 24-bit formats later.\n\t#define HAVE_MPG123_24BIT 1\n\n\t\/\/ Make the use of this when divining formats a no-op.\n\t#define MPG123_ENC_SIGNED_24 0\n#endif\n\n\/\/ This value is somewhat arbitrary, but corresponds to the minimum buffer size\n\/\/ used by ffmpeg, so it's probably sensible.\nconst size_t Mp3AudioSource::BUFFER_SIZE = 16384;\n\nMp3AudioSource::Mp3AudioSource(const std::string &path)\n : AudioSource(path), buffer(BUFFER_SIZE), context(nullptr)\n{\n\tthis->context = mpg123_new(nullptr, nullptr);\n\tmpg123_format_none(this->context);\n\n\tconst long *rates = nullptr;\n\tsize_t nrates = 0;\n\tmpg123_rates(&rates, &nrates);\n\tfor (size_t r = 0; r < nrates; r++) {\n\t\tDebug() << \"trying to enable formats at \" << rates[r]\n\t\t << std::endl;\n\t\tAddFormat(rates[r]);\n\t}\n\n\tif (mpg123_open(this->context, path.c_str()) == MPG123_ERR) {\n\t\tthrow FileError(\"mp3: can't open \" + path + \": \" +\n\t\t mpg123_strerror(this->context));\n\t}\n\n\tDebug() << \"mp3: sample rate:\" << this->SampleRate() << std::endl;\n\tDebug() << \"mp3: bytes per sample:\" << this->BytesPerSample()\n\t << std::endl;\n\tDebug() << \"mp3: channels:\" << (int)this->ChannelCount() << std::endl;\n\tDebug() << \"mp3: playd format:\" << (int)this->OutputSampleFormat()\n\t << std::endl;\n}\n\nMp3AudioSource::~Mp3AudioSource()\n{\n\tmpg123_delete(this->context);\n\tthis->context = nullptr;\n}\n\nvoid Mp3AudioSource::AddFormat(long rate)\n{\n\t\/\/ The requested encodings correspond to the sample formats available in\n\t\/\/ the SampleFormat enum.\n\tif (mpg123_format(this->context, rate, MPG123_STEREO | MPG123_MONO,\n\t (MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_8 |\n\t MPG123_ENC_SIGNED_16 | MPG123_ENC_SIGNED_24 |\n\t MPG123_ENC_SIGNED_32 | MPG123_ENC_FLOAT_32)) ==\n\t MPG123_ERR) {\n\t\t\/\/ Ignore the error for now -- another sample rate may be\n\t\t\/\/ available.\n\t\t\/\/ If no sample rates work, loading a file will fail anyway.\n\t\tDebug() << \"can't support\" << rate << std::endl;\n\t};\n}\n\nstd::uint8_t Mp3AudioSource::ChannelCount() const\n{\n\tassert(this->context != nullptr);\n\n\tint chans = 0;\n\tmpg123_getformat(this->context, nullptr, &chans, nullptr);\n\tassert(chans != 0);\n\treturn static_cast(chans);\n}\n\nstd::uint32_t Mp3AudioSource::SampleRate() const\n{\n\tassert(this->context != nullptr);\n\n\tlong rate = 0;\n\tmpg123_getformat(this->context, &rate, nullptr, nullptr);\n\n\tassert(0 < rate);\n\t\/\/ INT32_MAX isn't a typo; if we compare against UINT32_MAX, we'll\n\t\/\/ set off sign-compare errors, and the sample rate shouldn't be above\n\t\/\/ INT32_MAX anyroad.\n\tassert(rate <= INT32_MAX);\n\treturn static_cast(rate);\n}\n\nstd::uint64_t Mp3AudioSource::Seek(std::uint64_t in_samples)\n{\n\tassert(this->context != nullptr);\n\n\t\/\/ See BytesPerSample() for an explanation of this ChannelCount().\n\tauto mono_samples = in_samples * this->ChannelCount();\n\n\t\/\/ Have we tried to seek past the end of the file?\n\tauto clen = static_cast(mpg123_length(this->context));\n\tif (clen < mono_samples) {\n\t\tDebug() << \"mp3: seek at\" << mono_samples << \"past EOF at\"\n\t\t << clen << std::endl;\n\t\tthrow SeekError(MSG_SEEK_FAIL);\n\t}\n\n\tif (mpg123_seek(this->context, mono_samples, SEEK_SET) == MPG123_ERR) {\n\t\tDebug() << \"mp3: seek failed:\" << mpg123_strerror(this->context)\n\t\t << std::endl;\n\t\tthrow SeekError(MSG_SEEK_FAIL);\n\t}\n\n\t\/\/ The actual seek position may not be the same as the requested\n\t\/\/ position.\n\t\/\/ mpg123_tell gives us the exact mono-samples position.\n\treturn mpg123_tell(this->context) \/ this->ChannelCount();\n}\n\nMp3AudioSource::DecodeResult Mp3AudioSource::Decode()\n{\n\tassert(this->context != nullptr);\n\n\tauto buf = reinterpret_cast(&this->buffer.front());\n\tsize_t rbytes = 0;\n\tint err = mpg123_read(this->context, buf, this->buffer.size(), &rbytes);\n\n\tDecodeVector decoded;\n\tDecodeState decode_state;\n\n\tif (err == MPG123_DONE) {\n\t\tDebug() << \"mp3: end of file\" << std::endl;\n\t\tdecode_state = DecodeState::END_OF_FILE;\n\t} else if (err != MPG123_OK && err != MPG123_NEW_FORMAT) {\n\t\tDebug() << \"mp3: decode error:\" << mpg123_strerror(this->context)\n\t\t << std::endl;\n\t\tdecode_state = DecodeState::END_OF_FILE;\n\t} else {\n\t\tdecode_state = DecodeState::DECODING;\n\n\t\t\/\/ Copy only the bit of the buffer occupied by decoded data\n\t\tauto front = this->buffer.begin();\n\t\tdecoded = DecodeVector(front, front + rbytes);\n\t}\n\n\treturn std::make_pair(decode_state, decoded);\n}\n\nSampleFormat Mp3AudioSource::OutputSampleFormat() const\n{\n\tassert(this->context != nullptr);\n\n\tint encoding = 0;\n\tmpg123_getformat(this->context, nullptr, nullptr, &encoding);\n\n\tswitch (encoding) {\n\t\tcase MPG123_ENC_UNSIGNED_8:\n\t\t\treturn SampleFormat::PACKED_UNSIGNED_INT_8;\n\t\tcase MPG123_ENC_SIGNED_8:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_8;\n\t\tcase MPG123_ENC_SIGNED_16:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_16;\n#ifdef HAVE_MPG123_24BIT\n\t\tcase MPG123_ENC_SIGNED_24:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_24;\n#endif\n\t\tcase MPG123_ENC_SIGNED_32:\n\t\t\treturn SampleFormat::PACKED_SIGNED_INT_32;\n\t\tcase MPG123_ENC_FLOAT_32:\n\t\t\treturn SampleFormat::PACKED_FLOAT_32;\n\t\tdefault:\n\t\t\t\/\/ We shouldn't get here, if the format was set up\n\t\t\t\/\/ correctly earlier.\n\t\t\tassert(false);\n\t}\n}\n<|endoftext|>"} {"text":"no message<|endoftext|>"} {"text":"\/*************************************************************************\nDictionnaire - Classe de stockage des donnes de maladies\n-------------------\ndbut :\t06\/05\/17\ncopyright :\t(C) 2017 par VOGEL\ne-mail :\thugues.vogel@insa-lyon.fr\n*************************************************************************\/\n\n\/\/- Ralisation de la classe (fichier Dictionnaire.cpp) -\/\/\n\n\/\/---------------------------------------------------------------- INCLUDE\n\n\/\/-------------------------------------------------------- Include systme\n\n\/\/------------------------------------------------------ Include personnel\n\n#include \"Dictionnaire.h\"\n#include \"Mots.h\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/----------------------------------------------------------------- PUBLIC\n\n\nDictionnaire & Dictionnaire::ObtenirInstance()\n{\n\t\/\/ TODO: changer le retour par l'instance du singleton\n\treturn *((Dictionnaire*) nullptr);\n}\n\nvoid Dictionnaire::RafraichirInstance()\n{\n\t\/* EXEMPLE\n\tif (instanceMots != nullptr) {\n\t\tdelete instanceMots;\n\t}\n\n\tinstanceMots = new Mots();\n\t*\/\n}\n\nvoid Dictionnaire::ChargerFichier(const string & fichierDico)\n{\n\t\/\/TODO Destroy Maladies *\n\t\/\/Reinitialisation des attributs\n\tmaladies= unordered_map();\n\tmaladiesParMot = unordered_map>();\n\n\t\/\/Variables local\n\tunsigned int l = 0; \/\/numero de ligne actuel\n\tstring ligne;\n\n\tifstream inDico(fichierDico);\n\n\t\/\/1er ligne\n\tl++;\n\tif (!getline(inDico, ligne)||ligne != \"MA v1.0\") {\/\/Si on n'arrive pas a lire la 1er ligne\n\t\tthrow runtime_error(\"FileTypeINVALIDE\");\n\t}\n\n\t\/\/boucle sur tous les autres ligne (les maladies)\n\twhile (getline(inDico, ligne)) {\n\t\tl++;\n\t\tif (ligne.empty()) {\n\t\t\t\/\/On Ignor les ligne vide\n\t\t}\n\t\t\/*else if (ligne.at(0)=='#') { \/\/ Pour l'implementation de ligne de commentaire\n\t\t\t\/\/On Ignor les ligne de commentaire\n\t\t}*\/\n\t\telse {\n\t\t\t\/\/Recuperation du nom de la maladie\n\t\t\tunsigned int pos = ligne.find(';');\n\t\t\tif (pos = string::npos || pos == ligne.length-1) {\n\t\t\t\tthrow runtime_error(\"Nom de maladie sans definition : \" + ligne + \" (L \" + to_string(l) + \")\");\n\t\t\t}\n\t\t\tMaladie * onreadMaladie = new Maladie();\n\t\t\tonreadMaladie->nom = ligne.substr(0, pos);\n\n\n\n\t\t\t\/\/Recuperation de tous les mots de la maladie\n\t\t\tdo {\n\n\t\t\t\tunsigned int lastpos = pos;\n\t\t\t\tunsigned int pos = ligne.find(';', lastpos + 1);\n\t\t\t\tif (pos == string::npos) {\n\t\t\t\t\tpos = ligne.length;\n\t\t\t\t}\n\t\t\t\tunsigned int length = pos - lastpos - 1; \/\/longeur du mot\n\t\t\t\tif (length) {\n\t\t\t\t\tthrow runtime_error(\"Maladie avec un mot de taille 0 : \" + onreadMaladie->nom);\n\t\t\t\t}\n\n\t\t\t\t\/\/recuperation du mot dans un char *\n\t\t\t\tchar * mot = new char[length + 1];\n\t\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\t\tmot[i] = ligne.at(i + lastpos + 1);\n\t\t\t\t\tswitch (mot[i] != 'A' && mot[i] != 'T' && mot[i] != 'C' && mot[i] != 'G') {\n\t\t\t\t\t\tthrow runtime_error(\"Maladie avec un mot invalide : \" + onreadMaladie->nom + \" contien un mot avec '\" + mot[i] + \"' (L \" + to_string(l) + \")\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmot[length] = '\\0';\n\n\t\t\t\t\/\/indexation du mot\n\t\t\t\tunsigned int indexMot;\n\t\t\t\ttry {\n\t\t\t\t\tindexMot = Mots::ObtenirInstance().ObtenirIndex(mot);\n\t\t\t\t}\n\t\t\t\tcatch (const range_error &e) {\n\t\t\t\t\tindexMot = Mots::ObtenirInstance().InsererMot(mot);\n\t\t\t\t}\n\n\t\t\t\t\/\/Ajout du mot a la definition\n\t\t\t\tif (onreadMaladie->definition.find(indexMot) == onreadMaladie->definition.end()) {\/\/ Si le mot n'est pas dans la definition (filtre doublon)\n\t\t\t\t\tonreadMaladie->definition.insert(indexMot);\n\t\t\t\t}\n\n\t\t\t\tlastpos = pos;\n\t\t\t} while (pos < ligne.length() - 1 || (pos == ligne.length() - 1 && ligne.at(pos) != ';'));\n\n\t\t\t\/\/Multi definition\n\t\t\tunordered_map::iterator it = maladies.find(onreadMaladie->nom);\n\t\t\tif (it != maladies.end()) {\/\/ Si le Maladie est deja referancer\n\t\t\t\tif (!(*(it->second) == *onreadMaladie)) {\n\t\t\t\t\tdelete onreadMaladie;\n\t\t\t\t\tthrow runtime_error(\"Different definition d'une meme maladie : \" + it->first + \" (L \" + to_string(l) + \")\");\n\t\t\t\t}\n\t\t\t\tdelete onreadMaladie;\n\t\t\t}\n\t\t\telse {\/\/Fist definition\n\t\t\t\tmaladies.insert(pair(onreadMaladie->nom, onreadMaladie));\n\t\t\t\tfor (unordered_set::iterator motIt = onreadMaladie->definition.begin; motIt != onreadMaladie->definition.begin.end; motIt++) {\n\t\t\t\t\tmaladiesParMot[*motIt].insert(onreadMaladie);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst Maladie & Dictionnaire::ObtenirMaladie(const string & name) {\n\treturn Maladie();\n}\n\nconst unordered_set Dictionnaire::ObtenirMaladies(const unsigned int indexMot) {\n\t\/\/ TODO\n\treturn unordered_set();\n}\n\nconst unordered_set Dictionnaire::ObtenirNomsMaladies() {\n\t\/\/ TODO\n\treturn unordered_set();\n}\n\n\n\/\/----------------------------------------------------------------- PRIVEE\n\nDictionnaire::Dictionnaire()\n{\n}\n\n\nDictionnaire::~Dictionnaire()\n{\n}\nImplementation de Dictionnaire::ObtenirMaladie\/*************************************************************************\nDictionnaire - Classe de stockage des donnes de maladies\n-------------------\ndbut :\t06\/05\/17\ncopyright :\t(C) 2017 par VOGEL\ne-mail :\thugues.vogel@insa-lyon.fr\n*************************************************************************\/\n\n\/\/- Ralisation de la classe (fichier Dictionnaire.cpp) -\/\/\n\n\/\/---------------------------------------------------------------- INCLUDE\n\n\/\/-------------------------------------------------------- Include systme\n\n\/\/------------------------------------------------------ Include personnel\n\n#include \"Dictionnaire.h\"\n#include \"Mots.h\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/----------------------------------------------------------------- PUBLIC\n\n\nDictionnaire & Dictionnaire::ObtenirInstance()\n{\n\t\/\/ TODO: changer le retour par l'instance du singleton\n\treturn *((Dictionnaire*) nullptr);\n}\n\nvoid Dictionnaire::RafraichirInstance()\n{\n\t\/* EXEMPLE\n\tif (instanceMots != nullptr) {\n\t\tdelete instanceMots;\n\t}\n\n\tinstanceMots = new Mots();\n\t*\/\n}\n\nvoid Dictionnaire::ChargerFichier(const string & fichierDico)\n{\n\t\/\/TODO Destroy Maladies *\n\t\/\/Reinitialisation des attributs\n\tmaladies= unordered_map();\n\tmaladiesParMot = unordered_map>();\n\n\t\/\/Variables local\n\tunsigned int l = 0; \/\/numero de ligne actuel\n\tstring ligne;\n\n\tifstream inDico(fichierDico);\n\n\t\/\/1er ligne\n\tl++;\n\tif (!getline(inDico, ligne)||ligne != \"MA v1.0\") {\/\/Si on n'arrive pas a lire la 1er ligne\n\t\tthrow runtime_error(\"FileTypeINVALIDE\");\n\t}\n\n\t\/\/boucle sur tous les autres ligne (les maladies)\n\twhile (getline(inDico, ligne)) {\n\t\tl++;\n\t\tif (ligne.empty()) {\n\t\t\t\/\/On Ignor les ligne vide\n\t\t}\n\t\t\/*else if (ligne.at(0)=='#') { \/\/ Pour l'implementation de ligne de commentaire\n\t\t\t\/\/On Ignor les ligne de commentaire\n\t\t}*\/\n\t\telse {\n\t\t\t\/\/Recuperation du nom de la maladie\n\t\t\tunsigned int pos = ligne.find(';');\n\t\t\tif (pos = string::npos || pos == ligne.length-1) {\n\t\t\t\tthrow runtime_error(\"Nom de maladie sans definition : \" + ligne + \" (L \" + to_string(l) + \")\");\n\t\t\t}\n\t\t\tMaladie * onreadMaladie = new Maladie();\n\t\t\tonreadMaladie->nom = ligne.substr(0, pos);\n\n\n\n\t\t\t\/\/Recuperation de tous les mots de la maladie\n\t\t\tdo {\n\n\t\t\t\tunsigned int lastpos = pos;\n\t\t\t\tunsigned int pos = ligne.find(';', lastpos + 1);\n\t\t\t\tif (pos == string::npos) {\n\t\t\t\t\tpos = ligne.length;\n\t\t\t\t}\n\t\t\t\tunsigned int length = pos - lastpos - 1; \/\/longeur du mot\n\t\t\t\tif (length) {\n\t\t\t\t\tthrow runtime_error(\"Maladie avec un mot de taille 0 : \" + onreadMaladie->nom);\n\t\t\t\t}\n\n\t\t\t\t\/\/recuperation du mot dans un char *\n\t\t\t\tchar * mot = new char[length + 1];\n\t\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\t\tmot[i] = ligne.at(i + lastpos + 1);\n\t\t\t\t\tswitch (mot[i] != 'A' && mot[i] != 'T' && mot[i] != 'C' && mot[i] != 'G') {\n\t\t\t\t\t\tthrow runtime_error(\"Maladie avec un mot invalide : \" + onreadMaladie->nom + \" contien un mot avec '\" + mot[i] + \"' (L \" + to_string(l) + \")\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmot[length] = '\\0';\n\n\t\t\t\t\/\/indexation du mot\n\t\t\t\tunsigned int indexMot;\n\t\t\t\ttry {\n\t\t\t\t\tindexMot = Mots::ObtenirInstance().ObtenirIndex(mot);\n\t\t\t\t}\n\t\t\t\tcatch (const range_error &e) {\n\t\t\t\t\tindexMot = Mots::ObtenirInstance().InsererMot(mot);\n\t\t\t\t}\n\n\t\t\t\t\/\/Ajout du mot a la definition\n\t\t\t\tif (onreadMaladie->definition.find(indexMot) == onreadMaladie->definition.end()) {\/\/ Si le mot n'est pas dans la definition (filtre doublon)\n\t\t\t\t\tonreadMaladie->definition.insert(indexMot);\n\t\t\t\t}\n\n\t\t\t\tlastpos = pos;\n\t\t\t} while (pos < ligne.length() - 1 || (pos == ligne.length() - 1 && ligne.at(pos) != ';'));\n\n\t\t\t\/\/Multi definition\n\t\t\tunordered_map::iterator it = maladies.find(onreadMaladie->nom);\n\t\t\tif (it != maladies.end()) {\/\/ Si le Maladie est deja referancer\n\t\t\t\tif (!(*(it->second) == *onreadMaladie)) {\n\t\t\t\t\tdelete onreadMaladie;\n\t\t\t\t\tthrow runtime_error(\"Different definition d'une meme maladie : \" + it->first + \" (L \" + to_string(l) + \")\");\n\t\t\t\t}\n\t\t\t\tdelete onreadMaladie;\n\t\t\t}\n\t\t\telse {\/\/Fist definition\n\t\t\t\tmaladies.insert(pair(onreadMaladie->nom, onreadMaladie));\n\t\t\t\tfor (unordered_set::iterator motIt = onreadMaladie->definition.begin; motIt != onreadMaladie->definition.begin.end; motIt++) {\n\t\t\t\t\tmaladiesParMot[*motIt].insert(onreadMaladie);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst Maladie & Dictionnaire::ObtenirMaladie(const string & name) {\n\tunordered_map::iterator it = maladies.find(name);\n\tif (it == maladies.end()) {\n\t\tthrow range_error(\"maladie \" + name + \" non defini\");\n\t}\n\treturn *(it->second);\n}\n\nconst unordered_set Dictionnaire::ObtenirMaladies(const unsigned int indexMot) {\n\t\/\/ TODO\n\treturn unordered_set();\n}\n\nconst unordered_set Dictionnaire::ObtenirNomsMaladies() {\n\t\/\/ TODO\n\treturn unordered_set();\n}\n\n\n\/\/----------------------------------------------------------------- PRIVEE\n\nDictionnaire::Dictionnaire()\n{\n}\n\n\nDictionnaire::~Dictionnaire()\n{\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n\nnamespace But\n{\nnamespace Format\n{\n\ninline auto toString(std::string str) { return str; }\ninline auto toString(char c) { return std::string(1,c); }\ninline auto toString(char* c) { return std::string{c}; }\ninline auto toString(char const* c) { return std::string{c}; }\n\/\/inline auto toString(std::wstring str) { return str; }\n\ninline auto toString(const bool b) { return b ? \"true\" : \"false\"; }\n\n\/\/inline auto toString(const int8_t i) { return std::to_string(i); }\ninline auto toString(const uint8_t ui) { return std::to_string(ui); }\n\ninline auto toString(const int16_t i) { return std::to_string(i); }\ninline auto toString(const uint16_t ui) { return std::to_string(ui); }\n\ninline auto toString(const int32_t i) { return std::to_string(i); }\ninline auto toString(const uint32_t ui) { return std::to_string(ui); }\n\ninline auto toString(const int64_t i) { return std::to_string(i); }\ninline auto toString(const uint64_t ui) { return std::to_string(ui); }\n\ninline auto toString(const long long i) { return std::to_string(i); }\ninline auto toString(const unsigned long long ui) { return std::to_string(ui); }\n\ninline auto toString(const float fp) { return std::to_string(fp); }\ninline auto toString(const long double fp) { return std::to_string(fp); }\ninline auto toString(const double fp) { return std::to_string(fp); }\n\n}\n}\none more file requiring 32-bit fix#pragma once\n#include \n\nnamespace But\n{\nnamespace Format\n{\n\ninline auto toString(std::string str) { return str; }\ninline auto toString(char c) { return std::string(1,c); }\ninline auto toString(char* c) { return std::string{c}; }\ninline auto toString(char const* c) { return std::string{c}; }\n\/\/inline auto toString(std::wstring str) { return str; }\n\ninline auto toString(const bool b) { return b ? \"true\" : \"false\"; }\n\ninline auto toString(const signed char i) { return std::to_string(i); }\ninline auto toString(const unsigned char ui) { return std::to_string(ui); }\n\ninline auto toString(const signed short i) { return std::to_string(i); }\ninline auto toString(const unsigned short ui) { return std::to_string(ui); }\n\ninline auto toString(const signed int i) { return std::to_string(i); }\ninline auto toString(const unsigned int ui) { return std::to_string(ui); }\n\ninline auto toString(const long i) { return std::to_string(i); }\ninline auto toString(const unsigned long ui) { return std::to_string(ui); }\n\ninline auto toString(const long long i) { return std::to_string(i); }\ninline auto toString(const unsigned long long ui) { return std::to_string(ui); }\n\ninline auto toString(const float fp) { return std::to_string(fp); }\ninline auto toString(const long double fp) { return std::to_string(fp); }\ninline auto toString(const double fp) { return std::to_string(fp); }\n\n}\n}\n<|endoftext|>"} {"text":"fix mouse selection for high DPI screens<|endoftext|>"} {"text":"Fixed documentation.<|endoftext|>"} {"text":"Superfluous #endif<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n#include \n#include \n#include \n\n#include \"breakpad_googletest_includes.h\"\n#include \"client\/linux\/handler\/exception_handler.h\"\n#include \"client\/linux\/minidump_writer\/linux_dumper.h\"\n#include \"client\/linux\/minidump_writer\/minidump_writer.h\"\n#include \"common\/linux\/eintr_wrapper.h\"\n#include \"common\/linux\/file_id.h\"\n#include \"google_breakpad\/processor\/minidump.h\"\n\nusing namespace google_breakpad;\n\n#if !defined(__ANDROID__)\n#define TEMPDIR \"\/tmp\"\n#else\n#define TEMPDIR \"\/data\/local\/tmp\"\n#endif\n\n\/\/ Length of a formatted GUID string =\n\/\/ sizeof(MDGUID) * 2 + 4 (for dashes) + 1 (null terminator)\nconst int kGUIDStringSize = 37;\n\nnamespace {\ntypedef testing::Test MinidumpWriterTest;\n}\n\nTEST(MinidumpWriterTest, Setup) {\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n const pid_t child = fork();\n if (child == 0) {\n close(fds[1]);\n char b;\n HANDLE_EINTR(read(fds[0], &b, sizeof(b)));\n close(fds[0]);\n syscall(__NR_exit);\n }\n close(fds[0]);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n\n char templ[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(templ);\n \/\/ Set a non-zero tid to avoid tripping asserts.\n context.tid = 1;\n ASSERT_TRUE(WriteMinidump(templ, child, &context, sizeof(context)));\n struct stat st;\n ASSERT_EQ(stat(templ, &st), 0);\n ASSERT_GT(st.st_size, 0u);\n unlink(templ);\n\n close(fds[1]);\n}\n\n\/\/ Test that mapping info can be specified when writing a minidump,\n\/\/ and that it ends up in the module list of the minidump.\nTEST(MinidumpWriterTest, MappingInfo) {\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n \/\/ These are defined here so the parent can use them to check the\n \/\/ data from the minidump afterwards.\n const u_int32_t kMemorySize = sysconf(_SC_PAGESIZE);\n const char* kMemoryName = \"a fake module\";\n const u_int8_t kModuleGUID[sizeof(MDGUID)] = {\n 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF\n };\n char module_identifier_buffer[kGUIDStringSize];\n FileID::ConvertIdentifierToString(kModuleGUID,\n module_identifier_buffer,\n sizeof(module_identifier_buffer));\n string module_identifier(module_identifier_buffer);\n \/\/ Strip out dashes\n size_t pos;\n while ((pos = module_identifier.find('-')) != string::npos) {\n module_identifier.erase(pos, 1);\n }\n \/\/ And append a zero, because module IDs include an \"age\" field\n \/\/ which is always zero on Linux.\n module_identifier += \"0\";\n \n \/\/ Get some memory.\n char* memory =\n reinterpret_cast(mmap(NULL,\n kMemorySize,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON,\n -1,\n 0));\n const u_int64_t kMemoryAddress = reinterpret_cast(memory);\n ASSERT_TRUE(memory);\n\n const pid_t child = fork();\n if (child == 0) {\n close(fds[1]);\n char b;\n HANDLE_EINTR(read(fds[0], &b, sizeof(b)));\n close(fds[0]);\n syscall(__NR_exit);\n }\n close(fds[0]);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n context.tid = 1;\n\n char templ[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(templ);\n\n \/\/ Add information about the mapped memory.\n MappingInfo info;\n info.start_addr = kMemoryAddress;\n info.size = kMemorySize;\n info.offset = 0;\n strcpy(info.name, kMemoryName);\n \n MappingList mappings;\n MappingEntry mapping;\n mapping.first = info;\n memcpy(mapping.second, kModuleGUID, sizeof(MDGUID));\n mappings.push_back(mapping);\n ASSERT_TRUE(WriteMinidump(templ, child, &context, sizeof(context), mappings));\n\n \/\/ Read the minidump. Load the module list, and ensure that\n \/\/ the mmap'ed |memory| is listed with the given module name\n \/\/ and debug ID.\n Minidump minidump(templ);\n ASSERT_TRUE(minidump.Read());\n\n MinidumpModuleList* module_list = minidump.GetModuleList();\n ASSERT_TRUE(module_list);\n const MinidumpModule* module =\n module_list->GetModuleForAddress(kMemoryAddress);\n ASSERT_TRUE(module);\n\n EXPECT_EQ(kMemoryAddress, module->base_address());\n EXPECT_EQ(kMemorySize, module->size());\n EXPECT_EQ(kMemoryName, module->code_file());\n EXPECT_EQ(module_identifier, module->debug_identifier());\n\n unlink(templ);\n close(fds[1]);\n}\n\n\/\/ Test that mapping info can be specified, and that it overrides\n\/\/ existing mappings that are wholly contained within the specified\n\/\/ range.\nTEST(MinidumpWriterTest, MappingInfoContained) {\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n \/\/ These are defined here so the parent can use them to check the\n \/\/ data from the minidump afterwards.\n const u_int32_t kMemorySize = sysconf(_SC_PAGESIZE);\n const char* kMemoryName = \"a fake module\";\n const u_int8_t kModuleGUID[sizeof(MDGUID)] = {\n 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF\n };\n char module_identifier_buffer[kGUIDStringSize];\n FileID::ConvertIdentifierToString(kModuleGUID,\n module_identifier_buffer,\n sizeof(module_identifier_buffer));\n string module_identifier(module_identifier_buffer);\n \/\/ Strip out dashes\n size_t pos;\n while ((pos = module_identifier.find('-')) != string::npos) {\n module_identifier.erase(pos, 1);\n }\n \/\/ And append a zero, because module IDs include an \"age\" field\n \/\/ which is always zero on Linux.\n module_identifier += \"0\";\n \n \/\/ mmap a file\n char tempfile[] = TEMPDIR \"\/minidump-writer-unittest-temp-XXXXXX\";\n mktemp(tempfile);\n int fd = open(tempfile, O_RDWR | O_CREAT, 0);\n ASSERT_NE(-1, fd);\n unlink(tempfile);\n \/\/ fill with zeros\n char buffer[kMemorySize];\n memset(buffer, 0, kMemorySize);\n ASSERT_EQ(kMemorySize, write(fd, buffer, kMemorySize));\n lseek(fd, 0, SEEK_SET);\n\n char* memory =\n reinterpret_cast(mmap(NULL,\n kMemorySize,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE,\n fd,\n 0));\n const u_int64_t kMemoryAddress = reinterpret_cast(memory);\n ASSERT_TRUE(memory);\n close(fd);\n\n const pid_t child = fork();\n if (child == 0) {\n close(fds[1]);\n char b;\n HANDLE_EINTR(read(fds[0], &b, sizeof(b)));\n close(fds[0]);\n syscall(__NR_exit);\n }\n close(fds[0]);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n context.tid = 1;\n\n char dumpfile[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(dumpfile);\n\n \/\/ Add information about the mapped memory. Report it as being larger than\n \/\/ it actually is.\n MappingInfo info;\n info.start_addr = kMemoryAddress - kMemorySize;\n info.size = kMemorySize * 3;\n info.offset = 0;\n strcpy(info.name, kMemoryName);\n\n MappingList mappings;\n MappingEntry mapping;\n mapping.first = info;\n memcpy(mapping.second, kModuleGUID, sizeof(MDGUID));\n mappings.push_back(mapping);\n ASSERT_TRUE(WriteMinidump(dumpfile, child, &context, sizeof(context), mappings));\n\n \/\/ Read the minidump. Load the module list, and ensure that\n \/\/ the mmap'ed |memory| is listed with the given module name\n \/\/ and debug ID.\n Minidump minidump(dumpfile);\n ASSERT_TRUE(minidump.Read());\n\n MinidumpModuleList* module_list = minidump.GetModuleList();\n ASSERT_TRUE(module_list);\n const MinidumpModule* module =\n module_list->GetModuleForAddress(kMemoryAddress);\n ASSERT_TRUE(module);\n\n EXPECT_EQ(info.start_addr, module->base_address());\n EXPECT_EQ(info.size, module->size());\n EXPECT_EQ(kMemoryName, module->code_file());\n EXPECT_EQ(module_identifier, module->debug_identifier());\n\n unlink(dumpfile);\n close(fds[1]);\n}\n\nTEST(MinidumpWriterTest, DeletedBinary) {\n static const int kNumberOfThreadsInHelperProgram = 1;\n char kNumberOfThreadsArgument[2];\n sprintf(kNumberOfThreadsArgument, \"%d\", kNumberOfThreadsInHelperProgram);\n\n \/\/ Locate helper binary next to the current binary.\n char self_path[PATH_MAX];\n if (readlink(\"\/proc\/self\/exe\", self_path, sizeof(self_path) - 1) == -1) {\n FAIL() << \"readlink failed: \" << strerror(errno);\n exit(1);\n }\n string helper_path(self_path);\n size_t pos = helper_path.rfind('\/');\n if (pos == string::npos) {\n FAIL() << \"no trailing slash in path: \" << helper_path;\n exit(1);\n }\n helper_path.erase(pos + 1);\n helper_path += \"linux_dumper_unittest_helper\";\n\n \/\/ Copy binary to a temp file.\n char binpath[] = TEMPDIR \"\/linux-dumper-unittest-helper-XXXXXX\";\n mktemp(binpath);\n char cmdline[2 * PATH_MAX];\n sprintf(cmdline, \"\/bin\/cp \\\"%s\\\" \\\"%s\\\"\", helper_path.c_str(), binpath);\n ASSERT_EQ(0, system(cmdline));\n ASSERT_EQ(0, chmod(binpath, 0755));\n\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n pid_t child_pid = fork();\n if (child_pid == 0) {\n \/\/ In child process.\n close(fds[0]);\n\n \/\/ Pass the pipe fd and the number of threads as arguments.\n char pipe_fd_string[8];\n sprintf(pipe_fd_string, \"%d\", fds[1]);\n execl(binpath,\n binpath,\n pipe_fd_string,\n kNumberOfThreadsArgument,\n NULL);\n }\n close(fds[1]);\n \/\/ Wait for the child process to signal that it's ready.\n struct pollfd pfd;\n memset(&pfd, 0, sizeof(pfd));\n pfd.fd = fds[0];\n pfd.events = POLLIN | POLLERR;\n\n const int r = HANDLE_EINTR(poll(&pfd, 1, 1000));\n ASSERT_EQ(1, r);\n ASSERT_TRUE(pfd.revents & POLLIN);\n uint8_t junk;\n read(fds[0], &junk, sizeof(junk));\n close(fds[0]);\n\n \/\/ Child is ready now.\n \/\/ Unlink the test binary.\n unlink(binpath);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n\n char templ[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(templ);\n \/\/ Set a non-zero tid to avoid tripping asserts.\n context.tid = 1;\n ASSERT_TRUE(WriteMinidump(templ, child_pid, &context, sizeof(context)));\n kill(child_pid, SIGKILL);\n\n struct stat st;\n ASSERT_EQ(stat(templ, &st), 0);\n ASSERT_GT(st.st_size, 0u);\n\n\n\n Minidump minidump(templ);\n ASSERT_TRUE(minidump.Read());\n\n \/\/ Check that the main module filename is correct.\n MinidumpModuleList* module_list = minidump.GetModuleList();\n ASSERT_TRUE(module_list);\n const MinidumpModule* module = module_list->GetMainModule();\n EXPECT_STREQ(binpath, module->code_file().c_str());\n \/\/ Check that the file ID is correct.\n FileID fileid(helper_path.c_str());\n uint8_t identifier[sizeof(MDGUID)];\n EXPECT_TRUE(fileid.ElfFileIdentifier(identifier));\n char identifier_string[kGUIDStringSize];\n FileID::ConvertIdentifierToString(identifier,\n identifier_string,\n kGUIDStringSize);\n string module_identifier(identifier_string);\n \/\/ Strip out dashes\n while ((pos = module_identifier.find('-')) != string::npos) {\n module_identifier.erase(pos, 1);\n }\n \/\/ And append a zero, because module IDs include an \"age\" field\n \/\/ which is always zero on Linux.\n module_identifier += \"0\";\n EXPECT_EQ(module_identifier, module->debug_identifier());\n\n unlink(templ);\n}\nFix compile by adding needed includes. Review URL: http:\/\/breakpad.appspot.com\/253001\/\/ Copyright (c) 2011 Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"breakpad_googletest_includes.h\"\n#include \"client\/linux\/handler\/exception_handler.h\"\n#include \"client\/linux\/minidump_writer\/linux_dumper.h\"\n#include \"client\/linux\/minidump_writer\/minidump_writer.h\"\n#include \"common\/linux\/eintr_wrapper.h\"\n#include \"common\/linux\/file_id.h\"\n#include \"google_breakpad\/processor\/minidump.h\"\n\nusing namespace google_breakpad;\n\n#if !defined(__ANDROID__)\n#define TEMPDIR \"\/tmp\"\n#else\n#define TEMPDIR \"\/data\/local\/tmp\"\n#endif\n\n\/\/ Length of a formatted GUID string =\n\/\/ sizeof(MDGUID) * 2 + 4 (for dashes) + 1 (null terminator)\nconst int kGUIDStringSize = 37;\n\nnamespace {\ntypedef testing::Test MinidumpWriterTest;\n}\n\nTEST(MinidumpWriterTest, Setup) {\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n const pid_t child = fork();\n if (child == 0) {\n close(fds[1]);\n char b;\n HANDLE_EINTR(read(fds[0], &b, sizeof(b)));\n close(fds[0]);\n syscall(__NR_exit);\n }\n close(fds[0]);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n\n char templ[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(templ);\n \/\/ Set a non-zero tid to avoid tripping asserts.\n context.tid = 1;\n ASSERT_TRUE(WriteMinidump(templ, child, &context, sizeof(context)));\n struct stat st;\n ASSERT_EQ(stat(templ, &st), 0);\n ASSERT_GT(st.st_size, 0u);\n unlink(templ);\n\n close(fds[1]);\n}\n\n\/\/ Test that mapping info can be specified when writing a minidump,\n\/\/ and that it ends up in the module list of the minidump.\nTEST(MinidumpWriterTest, MappingInfo) {\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n \/\/ These are defined here so the parent can use them to check the\n \/\/ data from the minidump afterwards.\n const u_int32_t kMemorySize = sysconf(_SC_PAGESIZE);\n const char* kMemoryName = \"a fake module\";\n const u_int8_t kModuleGUID[sizeof(MDGUID)] = {\n 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF\n };\n char module_identifier_buffer[kGUIDStringSize];\n FileID::ConvertIdentifierToString(kModuleGUID,\n module_identifier_buffer,\n sizeof(module_identifier_buffer));\n string module_identifier(module_identifier_buffer);\n \/\/ Strip out dashes\n size_t pos;\n while ((pos = module_identifier.find('-')) != string::npos) {\n module_identifier.erase(pos, 1);\n }\n \/\/ And append a zero, because module IDs include an \"age\" field\n \/\/ which is always zero on Linux.\n module_identifier += \"0\";\n\n \/\/ Get some memory.\n char* memory =\n reinterpret_cast(mmap(NULL,\n kMemorySize,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE | MAP_ANON,\n -1,\n 0));\n const u_int64_t kMemoryAddress = reinterpret_cast(memory);\n ASSERT_TRUE(memory);\n\n const pid_t child = fork();\n if (child == 0) {\n close(fds[1]);\n char b;\n HANDLE_EINTR(read(fds[0], &b, sizeof(b)));\n close(fds[0]);\n syscall(__NR_exit);\n }\n close(fds[0]);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n context.tid = 1;\n\n char templ[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(templ);\n\n \/\/ Add information about the mapped memory.\n MappingInfo info;\n info.start_addr = kMemoryAddress;\n info.size = kMemorySize;\n info.offset = 0;\n strcpy(info.name, kMemoryName);\n\n MappingList mappings;\n MappingEntry mapping;\n mapping.first = info;\n memcpy(mapping.second, kModuleGUID, sizeof(MDGUID));\n mappings.push_back(mapping);\n ASSERT_TRUE(WriteMinidump(templ, child, &context, sizeof(context), mappings));\n\n \/\/ Read the minidump. Load the module list, and ensure that\n \/\/ the mmap'ed |memory| is listed with the given module name\n \/\/ and debug ID.\n Minidump minidump(templ);\n ASSERT_TRUE(minidump.Read());\n\n MinidumpModuleList* module_list = minidump.GetModuleList();\n ASSERT_TRUE(module_list);\n const MinidumpModule* module =\n module_list->GetModuleForAddress(kMemoryAddress);\n ASSERT_TRUE(module);\n\n EXPECT_EQ(kMemoryAddress, module->base_address());\n EXPECT_EQ(kMemorySize, module->size());\n EXPECT_EQ(kMemoryName, module->code_file());\n EXPECT_EQ(module_identifier, module->debug_identifier());\n\n unlink(templ);\n close(fds[1]);\n}\n\n\/\/ Test that mapping info can be specified, and that it overrides\n\/\/ existing mappings that are wholly contained within the specified\n\/\/ range.\nTEST(MinidumpWriterTest, MappingInfoContained) {\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n \/\/ These are defined here so the parent can use them to check the\n \/\/ data from the minidump afterwards.\n const u_int32_t kMemorySize = sysconf(_SC_PAGESIZE);\n const char* kMemoryName = \"a fake module\";\n const u_int8_t kModuleGUID[sizeof(MDGUID)] = {\n 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF\n };\n char module_identifier_buffer[kGUIDStringSize];\n FileID::ConvertIdentifierToString(kModuleGUID,\n module_identifier_buffer,\n sizeof(module_identifier_buffer));\n string module_identifier(module_identifier_buffer);\n \/\/ Strip out dashes\n size_t pos;\n while ((pos = module_identifier.find('-')) != string::npos) {\n module_identifier.erase(pos, 1);\n }\n \/\/ And append a zero, because module IDs include an \"age\" field\n \/\/ which is always zero on Linux.\n module_identifier += \"0\";\n\n \/\/ mmap a file\n char tempfile[] = TEMPDIR \"\/minidump-writer-unittest-temp-XXXXXX\";\n mktemp(tempfile);\n int fd = open(tempfile, O_RDWR | O_CREAT, 0);\n ASSERT_NE(-1, fd);\n unlink(tempfile);\n \/\/ fill with zeros\n char buffer[kMemorySize];\n memset(buffer, 0, kMemorySize);\n ASSERT_EQ(kMemorySize, write(fd, buffer, kMemorySize));\n lseek(fd, 0, SEEK_SET);\n\n char* memory =\n reinterpret_cast(mmap(NULL,\n kMemorySize,\n PROT_READ | PROT_WRITE,\n MAP_PRIVATE,\n fd,\n 0));\n const u_int64_t kMemoryAddress = reinterpret_cast(memory);\n ASSERT_TRUE(memory);\n close(fd);\n\n const pid_t child = fork();\n if (child == 0) {\n close(fds[1]);\n char b;\n HANDLE_EINTR(read(fds[0], &b, sizeof(b)));\n close(fds[0]);\n syscall(__NR_exit);\n }\n close(fds[0]);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n context.tid = 1;\n\n char dumpfile[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(dumpfile);\n\n \/\/ Add information about the mapped memory. Report it as being larger than\n \/\/ it actually is.\n MappingInfo info;\n info.start_addr = kMemoryAddress - kMemorySize;\n info.size = kMemorySize * 3;\n info.offset = 0;\n strcpy(info.name, kMemoryName);\n\n MappingList mappings;\n MappingEntry mapping;\n mapping.first = info;\n memcpy(mapping.second, kModuleGUID, sizeof(MDGUID));\n mappings.push_back(mapping);\n ASSERT_TRUE(\n WriteMinidump(dumpfile, child, &context, sizeof(context), mappings));\n\n \/\/ Read the minidump. Load the module list, and ensure that\n \/\/ the mmap'ed |memory| is listed with the given module name\n \/\/ and debug ID.\n Minidump minidump(dumpfile);\n ASSERT_TRUE(minidump.Read());\n\n MinidumpModuleList* module_list = minidump.GetModuleList();\n ASSERT_TRUE(module_list);\n const MinidumpModule* module =\n module_list->GetModuleForAddress(kMemoryAddress);\n ASSERT_TRUE(module);\n\n EXPECT_EQ(info.start_addr, module->base_address());\n EXPECT_EQ(info.size, module->size());\n EXPECT_EQ(kMemoryName, module->code_file());\n EXPECT_EQ(module_identifier, module->debug_identifier());\n\n unlink(dumpfile);\n close(fds[1]);\n}\n\nTEST(MinidumpWriterTest, DeletedBinary) {\n static const int kNumberOfThreadsInHelperProgram = 1;\n char kNumberOfThreadsArgument[2];\n sprintf(kNumberOfThreadsArgument, \"%d\", kNumberOfThreadsInHelperProgram);\n\n \/\/ Locate helper binary next to the current binary.\n char self_path[PATH_MAX];\n if (readlink(\"\/proc\/self\/exe\", self_path, sizeof(self_path) - 1) == -1) {\n FAIL() << \"readlink failed: \" << strerror(errno);\n exit(1);\n }\n string helper_path(self_path);\n size_t pos = helper_path.rfind('\/');\n if (pos == string::npos) {\n FAIL() << \"no trailing slash in path: \" << helper_path;\n exit(1);\n }\n helper_path.erase(pos + 1);\n helper_path += \"linux_dumper_unittest_helper\";\n\n \/\/ Copy binary to a temp file.\n char binpath[] = TEMPDIR \"\/linux-dumper-unittest-helper-XXXXXX\";\n mktemp(binpath);\n char cmdline[2 * PATH_MAX];\n sprintf(cmdline, \"\/bin\/cp \\\"%s\\\" \\\"%s\\\"\", helper_path.c_str(), binpath);\n ASSERT_EQ(0, system(cmdline));\n ASSERT_EQ(0, chmod(binpath, 0755));\n\n int fds[2];\n ASSERT_NE(-1, pipe(fds));\n\n pid_t child_pid = fork();\n if (child_pid == 0) {\n \/\/ In child process.\n close(fds[0]);\n\n \/\/ Pass the pipe fd and the number of threads as arguments.\n char pipe_fd_string[8];\n sprintf(pipe_fd_string, \"%d\", fds[1]);\n execl(binpath,\n binpath,\n pipe_fd_string,\n kNumberOfThreadsArgument,\n NULL);\n }\n close(fds[1]);\n \/\/ Wait for the child process to signal that it's ready.\n struct pollfd pfd;\n memset(&pfd, 0, sizeof(pfd));\n pfd.fd = fds[0];\n pfd.events = POLLIN | POLLERR;\n\n const int r = HANDLE_EINTR(poll(&pfd, 1, 1000));\n ASSERT_EQ(1, r);\n ASSERT_TRUE(pfd.revents & POLLIN);\n uint8_t junk;\n read(fds[0], &junk, sizeof(junk));\n close(fds[0]);\n\n \/\/ Child is ready now.\n \/\/ Unlink the test binary.\n unlink(binpath);\n\n ExceptionHandler::CrashContext context;\n memset(&context, 0, sizeof(context));\n\n char templ[] = TEMPDIR \"\/minidump-writer-unittest-XXXXXX\";\n mktemp(templ);\n \/\/ Set a non-zero tid to avoid tripping asserts.\n context.tid = 1;\n ASSERT_TRUE(WriteMinidump(templ, child_pid, &context, sizeof(context)));\n kill(child_pid, SIGKILL);\n\n struct stat st;\n ASSERT_EQ(stat(templ, &st), 0);\n ASSERT_GT(st.st_size, 0u);\n\n\n\n Minidump minidump(templ);\n ASSERT_TRUE(minidump.Read());\n\n \/\/ Check that the main module filename is correct.\n MinidumpModuleList* module_list = minidump.GetModuleList();\n ASSERT_TRUE(module_list);\n const MinidumpModule* module = module_list->GetMainModule();\n EXPECT_STREQ(binpath, module->code_file().c_str());\n \/\/ Check that the file ID is correct.\n FileID fileid(helper_path.c_str());\n uint8_t identifier[sizeof(MDGUID)];\n EXPECT_TRUE(fileid.ElfFileIdentifier(identifier));\n char identifier_string[kGUIDStringSize];\n FileID::ConvertIdentifierToString(identifier,\n identifier_string,\n kGUIDStringSize);\n string module_identifier(identifier_string);\n \/\/ Strip out dashes\n while ((pos = module_identifier.find('-')) != string::npos) {\n module_identifier.erase(pos, 1);\n }\n \/\/ And append a zero, because module IDs include an \"age\" field\n \/\/ which is always zero on Linux.\n module_identifier += \"0\";\n EXPECT_EQ(module_identifier, module->debug_identifier());\n\n unlink(templ);\n}\n<|endoftext|>"} {"text":"\/*\n\n\n*\/\n\n#include\n#include\n#include\n#include\"..\/include\/HashTable.h\"\n\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nint main(int argc, char* argv[])\n{\n\tHashTable* hash = new HashTable(10);\n\n\tstd::ifstream in_file;\t\/\/might actually be useless.\n\tin_file.open(argv[1]);\n\tif (in_file.is_open())\n\t{\n\t\tint rating, year, quantity;\n\t\tstring title, buffer;\n\t\twhile (!in_file.eof())\n\t\t{\n\t\t\tgetline(in_file, buffer, ',');\n\t\t\trating = stoi(buffer);\n\t\t\tgetline(in_file, buffer, ',');\n\t\t\ttitle = buffer;\n\t\t\tgetline(in_file, buffer, ',');\n\t\t\tyear = stoi(buffer);\n\t\t\tgetline(in_file, buffer);\n\t\t\tquantity = stoi(buffer);\n\t\t\t\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/nothing for now.\n\t}\n\n\tint select = 0;\n\n\twhile (select != 6)\n\t{\n\n\t\tcout << \"======Main Menu=====\" << endl\n\t\t\t<< \"1. Insert Movie\" << endl\n\t\t\t<< \"2. Delete Movie\" << endl\n\t\t\t<< \"3. Find Movie\" << endl\n\t\t\t<< \"4. Pritn Table of Contents\" << endl\n\t\t\t<< \"5. Quit\" << endl;\n\n\t\tcin >> select;\n\n\t\tif (select == 1)\t\/\/Insert Movie\n\t\t{\n\n\t\t}\n\n\t\tif (select == 2)\t\/\/Delete Movie\n\t\t{\n\n\t\t}\n\n\t\tif (select == 3)\t\/\/Find Movie\n\t\t{\n\n\t\t}\n\n\t\tif (select == 4)\t\/\/Print Table of Contents\n\t\t{\n\n\t\t}\n\n\t\tif (select == 5)\t\/\/Quit\n\t\t\tcout << \"Goodbye!\" << endl;\n\t\tif (select > 5)\n\t\t\tcout << \"---That was not an option.---\\n\\n\";\n\t}\n\n\treturn 0;\n}refined add, made hash table 53 in size, need to basically rewrite header file because I hate using ones provided. They don't agree with my ideas. Even though someone significantly more qualified made them. Granted, they also made the header file for the lowest common denominator... (-sincerely, my ego)\/*\n\/\/ Derek Prince\n\/\/ Assignment 9\n\/\/ Hashing Movies (Perfectly) \n\/\/ Just kidding.\n\/\/ Still hashing though.\n\/\/ \n*\/\n\n#ifndef H_TABLE_SIZE\n#define H_TABLE_SIZE 53\n#endif\t\/\/H_TABLE_SIZE\n\n\n#include\n#include\n#include\n#include\"..\/include\/HashTable.h\"\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nint main(int argc, char* argv[])\n{\n\tHashTable* hash = new HashTable(10);\n\n\tstd::ifstream in_file;\t\/\/might actually be useless.\n\tin_file.open(argv[1]);\n\tif (in_file.is_open())\n\t{\n\t\tint year;\n\t\tstring title, buffer;\n\t\twhile (!in_file.eof())\n\t\t{\n\t\t\tgetline(in_file, buffer, ',');\t\/\/rating - ditch\n\t\t\tgetline(in_file, buffer, ',');\n\t\t\ttitle = buffer;\n\t\t\tgetline(in_file, buffer, ',');\n\t\t\tyear = stoi(buffer);\n\t\t\tgetline(in_file, buffer);\t\t\/\/quantity - ditch\n\n\t\t\t\/\/add movie or hash then add\n\t\t\t\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/nothing for now.\n\t}\n\t\n\tint select = 0;\n\n\twhile (select != 6)\n\t{\n\n\t\tcout << \"======Main Menu=====\" << endl\n\t\t\t<< \"1. Insert Movie\" << endl\n\t\t\t<< \"2. Delete Movie\" << endl\n\t\t\t<< \"3. Find Movie\" << endl\n\t\t\t<< \"4. Pritn Table of Contents\" << endl\n\t\t\t<< \"5. Quit\" << endl;\n\n\t\tcin >> select;\n\n\t\tif (select == 1)\t\/\/Insert Movie\n\t\t{\n\n\t\t}\n\n\t\tif (select == 2)\t\/\/Delete Movie\n\t\t{\n\n\t\t}\n\n\t\tif (select == 3)\t\/\/Find Movie\n\t\t{\n\n\t\t}\n\n\t\tif (select == 4)\t\/\/Print Table of Contents\n\t\t{\n\n\t\t}\n\n\t\tif (select == 5)\t\/\/Quit\n\t\t\tcout << \"Goodbye!\" << endl;\n\t\tif (select > 5)\n\t\t\tcout << \"---That was not an option.---\\n\\n\";\n\t}\n\n\treturn 0;\n}<|endoftext|>"} {"text":"Use attrtype_t enumerations to Actor::getAttr<|endoftext|>"} {"text":"check json parsing error in binpickingtaskzmq.cpp<|endoftext|>"} {"text":"Connect to the server when you click the button. Added a hardcoded localhost button.<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"SimmIKSolverImpl.h\"\r\n#include \"SimmInverseKinematicsTarget.h\"\r\n\r\n\r\n\r\nusing namespace OpenSim;\r\nusing namespace std;\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * An implementation of the IKSolverInterface specific to simm classes\/dynamicsEngine.\r\n *\r\n * @param aOptimizationTarget The target that IK will minimize\r\n * @param aIKParams Parameters specified in input file to control IK.\r\n *\/\r\nSimmIKSolverImpl::\r\nSimmIKSolverImpl(SimmInverseKinematicsTarget& aOptimizationTarget):\r\nIKSolverInterface(aOptimizationTarget)\r\n{\r\n}\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * This is the heart of the IK solver, this method solves a specific motion trial\r\n * given an input storage object for input, one for output.\r\n\r\n * @param aIKOptions Pass along to the method attributes specified by end-user in input file.\r\n * @param inputData Set of frames to solve packaged as a storage fle.\r\n * @param outputData the frames solved by the solver represented as a storage onbject.\r\n *\/\r\nvoid SimmIKSolverImpl::solveFrames(const SimmIKTrialParams& aIKOptions, Storage& inputData, Storage& outputData)\r\n{\r\n\tint i;\r\n\r\n\t\/\/ Instantiate the optimizer\r\n\trdFSQP *optimizer = new rdFSQP(&_ikTarget);\r\n\r\n\t\/\/ Set optimization convergence criteria\/tolerance\r\n\t\/\/ Enable some Debugging here if needed\r\n\toptimizer->setPrintLevel(0);\r\n\toptimizer->setConvergenceCriterion(1.0E-4);\t\/\/ Error in markers of .01\r\n\toptimizer->setMaxIterations(1000);\r\n\r\n\t\/* Get names for unconstrained Qs (ones that will be solved). *\/\r\n\tArray unconstrainedCoordinateNames(NULL);\r\n _ikTarget.getUnconstrainedCoordinateNames(unconstrainedCoordinateNames);\r\n\r\n\t\/* Get names for prescribed Qs (specified in input file). *\/\r\n\tArray prescribedCoordinateNames(NULL);\r\n _ikTarget.getPrescribedCoordinateNames(prescribedCoordinateNames);\r\n\r\n\t\/* Get names for markers used for solving. *\/\r\n\tArray markerNames(NULL);\r\n\t_ikTarget.getOutputMarkerNames(markerNames);\r\n\r\n\tstring resultsHeader = \"time\\t\";\r\n\tfor (i = 0; i < unconstrainedCoordinateNames.getSize(); i++)\r\n\t{\r\n\t\tresultsHeader += *(unconstrainedCoordinateNames[i]);\r\n\t\tresultsHeader += \"\\t\";\r\n\t}\r\n\r\n\tfor (i = 0; i < prescribedCoordinateNames.getSize(); i++)\r\n\t{\r\n\t\tresultsHeader += *(prescribedCoordinateNames[i]);\r\n\t\tresultsHeader += \"\\t\";\r\n\t}\r\n\r\n\tstring markerComponentNames[] = {\"_px\", \"_py\", \"_pz\"};\r\n\t\/\/ Include markers for visual verification in SIMM\r\n\tif (aIKOptions.getIncludeMarkers())\r\n\t{\r\n\t\tfor (i = 0; i < markerNames.getSize(); i++)\r\n\t\t{\r\n\t\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\t{\r\n\t\t\t\tresultsHeader += *(markerNames[i]);\r\n\t\t\t\tresultsHeader += markerComponentNames[j];\r\n\t\t\t\tresultsHeader += \"\\t\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\/\/ User data (colummns that are in input storage file but not used by IK,\r\n\t\/\/ to be passed along for later processing.\r\n\tconst Array &inputColumnNames\t = inputData.getColumnLabelsArray();\r\n\tArray userDataColumnIndices(0);\r\n\tstring userHeaders;\r\n\tcollectUserData(inputColumnNames, resultsHeader, userHeaders, userDataColumnIndices);\r\n\tresultsHeader += userHeaders;\r\n\r\n\r\n\r\n\toutputData.setColumnLabels(resultsHeader.c_str());\r\n\r\n\t\/\/ Set the lower and upper bounds on the unconstrained Q array\r\n\t\/\/ TODO: shouldn't have to search for coordinates by name\r\n\tSimmKinematicsEngine &eng = (SimmKinematicsEngine&)_ikTarget.getModel().getSimmKinematicsEngine();\r\n\tfor (i = 0; i < unconstrainedCoordinateNames.getSize(); i++)\r\n\t{\r\n\t\tCoordinate* coord = eng.getCoordinate(*(unconstrainedCoordinateNames[i]));\r\n\t\toptimizer->setLowerBound(i, coord->getRangeMin());\r\n\t\toptimizer->setUpperBound(i, coord->getRangeMax());\r\n\t}\r\n\r\n\t\/\/ Main loop to set initial conditions and solve snapshots\r\n\t\/\/ At every step we use experimental data as a starting guess \r\n\tArray unconstrainedQGuess(0.0, unconstrainedCoordinateNames.getSize());\t\/\/ Initial guess and work array\r\n\tArray unconstrainedQSol(0.0, unconstrainedCoordinateNames.getSize());\t\/\/ Solution array\r\n\tArray experimentalMarkerLocations(0.0, markerNames.getSize() * 3);\r\n\r\n\tint startFrame = 0, endFrame = 1;\r\n\tdouble currentTime;\r\n\r\n\t\/* Get the indices of the starting frame and the ending frame,\r\n\t * based on the user-defined start\/end times stored in\r\n\t * the simmIKTrialOptions.\r\n\t *\/\r\n\taIKOptions.findFrameRange(inputData, startFrame, endFrame);\r\n\r\n\tif (endFrame - startFrame > 1)\r\n\t\tcout << \"Solving frames \" << startFrame + 1 << \" to \" << endFrame + 1 << \" (time = \" <<\r\n\t\taIKOptions.getStartTime() << \" to \" << aIKOptions.getEndTime() << \")\" << endl;\r\n\r\n\tfor (int index = startFrame; index <= endFrame; index++)\r\n\t{\r\n\t\t\/\/ Get time associated with index\r\n\t\tdouble timeT = inputData.getStateVector(index)->getTime();\r\n\r\n\t\t\/* This sets the values of the prescribed coordinates, which\r\n\t\t * are coordinates that are:\r\n\t\t * (a) specified in the input data, and\r\n\t\t * (b) locked at that specified value.\r\n\t\t * These coordinates are not variables in the IK solving.\r\n\t\t * If a coordinate is specified in the file but not\r\n\t\t * locked, it is an unconstrained coordinate and it is\r\n\t\t * variable in the IK solving.\r\n\t\t *\/\r\n\t\t_ikTarget.setPrescribedCoordinates(index);\r\n\r\n\t\t\/\/ This sets the guess of unconstrained generalized coordinates \r\n\t\t\/\/ and marker data from recordedDataStorage\r\n\t\t_ikTarget.setIndexToSolve(index, &unconstrainedQGuess[0]);\r\n\r\n\t\t\/\/ Invoke optimization mechanism to solve for Qs\r\n\t\tint optimizerReturn = optimizer->computeOptimalControls(&unconstrainedQGuess[0], &unconstrainedQSol[0]);\r\n\r\n\t\t\/* Output variables include unconstrained (solved) Qs... *\/\r\n\t\tArray qsAndMarkersArray = unconstrainedQSol;\r\n\r\n\t\t\/* ... then prescribed Qs... *\/\r\n\t\tArray prescribedQValues(0.0);\r\n\t\t_ikTarget.getPrescribedQValues(prescribedQValues);\r\n\t\tqsAndMarkersArray.append(prescribedQValues);\r\n\r\n\t\t\/* ... then, optionally, computed marker locations. *\/\r\n\t\tif (aIKOptions.getIncludeMarkers())\r\n\t\t{\r\n\t\t\t_ikTarget.getExperimentalMarkerLocations(experimentalMarkerLocations);\r\n\t\t\tqsAndMarkersArray.append(experimentalMarkerLocations);\r\n\t\t}\r\n\r\n\t\tinputData.getTime(index, currentTime);\r\n\t\tcout << \"Solved frame \" << index + 1 << \" at time \" << currentTime << \", Optimizer returned = \" << optimizerReturn << endl;\r\n\t\t\/\/ Allocate new row (StateVector) and add it to ikStorage\r\n\t\tStateVector *nextDataRow = new StateVector();\r\n\r\n\t\t\/\/ Append user data to qsAndMarkersArray\r\n\t\tArray dataRow(qsAndMarkersArray);\r\n\t\tappendUserData(dataRow, userDataColumnIndices, inputData.getStateVector(index));\r\n\r\n\t\tnextDataRow->setStates(timeT, dataRow.getSize(), &dataRow[0]);\r\n\r\n\t\toutputData.append(*nextDataRow);\r\n\t}\r\n\r\n\tdelete optimizer;\r\n}\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * UserData is the set of columns that are not used directly by the IK problem (for example\r\n * ground reaction forces). This UserData needs to be carried along in IK.\r\n *\/\r\nvoid SimmIKSolverImpl::collectUserData(const Array &inputColumnLabels,\r\n\t\t\t\t\t\t\t\t\t string& resultsHeader, \r\n\t\t\t\t\t\t\t\t\t string& userHeaders, \r\n\t\t\t\t\t\t\t\t\t Array& userDataColumnIndices)\r\n{\r\n\t\/\/ Find columns that are none of the above to append them to the end of the list\r\n\tint i;\r\n\tfor(i=0; i< inputColumnLabels.getSize(); i++){\r\n\t\tstring nextLabel = inputColumnLabels[i];\r\n\t\t\/\/ We'll find out if the column is already there by doing string search for \r\n\t\t\/\/ either \\t$column or $column\\t to account for substrings\r\n\t\tstring searchString1(nextLabel+\"\\t\");\r\n\t\tstring searchString2(\"\\t\"+nextLabel);\r\n\t\tif (strstr(resultsHeader.c_str(), searchString1.c_str())==0 &&\r\n\t\t\tstrstr(resultsHeader.c_str(), searchString2.c_str())==0 ){\r\n\t\t\t\/\/ Append to userHeaders\r\n\t\t\tuserHeaders += nextLabel+\"\\t\";\r\n\t\t\t\/\/ Keep track of indices to match data with labels\r\n\t\t\tuserDataColumnIndices.append(i);\r\n\r\n\t\t\t\/\/ cout << \"Column:\" << nextLabel << \" index\" << i << endl;\r\n\t\t}\r\n\t}\r\n}\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * Companion helper function to (collectUserData) responsible for appending user columns \r\n * to outputRow.\r\n *\/\r\nvoid SimmIKSolverImpl::appendUserData(Array& outputRow, Array& indices, StateVector* inputRow)\r\n{\r\n\tint i;\r\n\tfor(i=0; i< indices.getSize(); i++){\r\n\t\tdouble userValue=rdMath::NAN;\r\n\t\tint index = indices[i]-1;\r\n\t\tinputRow->getDataValue(index, userValue);\r\n\t\toutputRow.append(userValue);\r\n\t}\r\n}\r\nCall IntegCallback and Analysis callbacks after each IK frame is solved.#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"SimmIKSolverImpl.h\"\r\n#include \"SimmInverseKinematicsTarget.h\"\r\n\r\n\r\n\r\nusing namespace OpenSim;\r\nusing namespace std;\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * An implementation of the IKSolverInterface specific to simm classes\/dynamicsEngine.\r\n *\r\n * @param aOptimizationTarget The target that IK will minimize\r\n * @param aIKParams Parameters specified in input file to control IK.\r\n *\/\r\nSimmIKSolverImpl::\r\nSimmIKSolverImpl(SimmInverseKinematicsTarget& aOptimizationTarget):\r\nIKSolverInterface(aOptimizationTarget)\r\n{\r\n}\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * This is the heart of the IK solver, this method solves a specific motion trial\r\n * given an input storage object for input, one for output.\r\n\r\n * @param aIKOptions Pass along to the method attributes specified by end-user in input file.\r\n * @param inputData Set of frames to solve packaged as a storage fle.\r\n * @param outputData the frames solved by the solver represented as a storage onbject.\r\n *\/\r\nvoid SimmIKSolverImpl::solveFrames(const SimmIKTrialParams& aIKOptions, Storage& inputData, Storage& outputData)\r\n{\r\n\tint i;\r\n\r\n\t\/\/ Instantiate the optimizer\r\n\trdFSQP *optimizer = new rdFSQP(&_ikTarget);\r\n\r\n\t\/\/ Set optimization convergence criteria\/tolerance\r\n\t\/\/ Enable some Debugging here if needed\r\n\toptimizer->setPrintLevel(0);\r\n\toptimizer->setConvergenceCriterion(1.0E-4);\t\/\/ Error in markers of .01\r\n\toptimizer->setMaxIterations(1000);\r\n\r\n\t\/* Get names for unconstrained Qs (ones that will be solved). *\/\r\n\tArray unconstrainedCoordinateNames(NULL);\r\n _ikTarget.getUnconstrainedCoordinateNames(unconstrainedCoordinateNames);\r\n\r\n\t\/* Get names for prescribed Qs (specified in input file). *\/\r\n\tArray prescribedCoordinateNames(NULL);\r\n _ikTarget.getPrescribedCoordinateNames(prescribedCoordinateNames);\r\n\r\n\t\/* Get names for markers used for solving. *\/\r\n\tArray markerNames(NULL);\r\n\t_ikTarget.getOutputMarkerNames(markerNames);\r\n\r\n\tstring resultsHeader = \"time\\t\";\r\n\tfor (i = 0; i < unconstrainedCoordinateNames.getSize(); i++)\r\n\t{\r\n\t\tresultsHeader += *(unconstrainedCoordinateNames[i]);\r\n\t\tresultsHeader += \"\\t\";\r\n\t}\r\n\r\n\tfor (i = 0; i < prescribedCoordinateNames.getSize(); i++)\r\n\t{\r\n\t\tresultsHeader += *(prescribedCoordinateNames[i]);\r\n\t\tresultsHeader += \"\\t\";\r\n\t}\r\n\r\n\tstring markerComponentNames[] = {\"_px\", \"_py\", \"_pz\"};\r\n\t\/\/ Include markers for visual verification in SIMM\r\n\tif (aIKOptions.getIncludeMarkers())\r\n\t{\r\n\t\tfor (i = 0; i < markerNames.getSize(); i++)\r\n\t\t{\r\n\t\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\t{\r\n\t\t\t\tresultsHeader += *(markerNames[i]);\r\n\t\t\t\tresultsHeader += markerComponentNames[j];\r\n\t\t\t\tresultsHeader += \"\\t\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\/\/ User data (colummns that are in input storage file but not used by IK,\r\n\t\/\/ to be passed along for later processing.\r\n\tconst Array &inputColumnNames\t = inputData.getColumnLabelsArray();\r\n\tArray userDataColumnIndices(0);\r\n\tstring userHeaders;\r\n\tcollectUserData(inputColumnNames, resultsHeader, userHeaders, userDataColumnIndices);\r\n\tresultsHeader += userHeaders;\r\n\r\n\r\n\r\n\toutputData.setColumnLabels(resultsHeader.c_str());\r\n\r\n\t\/\/ Set the lower and upper bounds on the unconstrained Q array\r\n\t\/\/ TODO: shouldn't have to search for coordinates by name\r\n\tSimmKinematicsEngine &eng = (SimmKinematicsEngine&)_ikTarget.getModel().getSimmKinematicsEngine();\r\n\tfor (i = 0; i < unconstrainedCoordinateNames.getSize(); i++)\r\n\t{\r\n\t\tCoordinate* coord = eng.getCoordinate(*(unconstrainedCoordinateNames[i]));\r\n\t\toptimizer->setLowerBound(i, coord->getRangeMin());\r\n\t\toptimizer->setUpperBound(i, coord->getRangeMax());\r\n\t}\r\n\r\n\t\/\/ Main loop to set initial conditions and solve snapshots\r\n\t\/\/ At every step we use experimental data as a starting guess \r\n\tArray unconstrainedQGuess(0.0, unconstrainedCoordinateNames.getSize());\t\/\/ Initial guess and work array\r\n\tArray unconstrainedQSol(0.0, unconstrainedCoordinateNames.getSize());\t\/\/ Solution array\r\n\tArray experimentalMarkerLocations(0.0, markerNames.getSize() * 3);\r\n\r\n\tint startFrame = 0, endFrame = 1;\r\n\tdouble currentTime;\r\n\r\n\t\/* Get the indices of the starting frame and the ending frame,\r\n\t * based on the user-defined start\/end times stored in\r\n\t * the simmIKTrialOptions.\r\n\t *\/\r\n\taIKOptions.findFrameRange(inputData, startFrame, endFrame);\r\n\r\n\tif (endFrame - startFrame > 1)\r\n\t\tcout << \"Solving frames \" << startFrame + 1 << \" to \" << endFrame + 1 << \" (time = \" <<\r\n\t\taIKOptions.getStartTime() << \" to \" << aIKOptions.getEndTime() << \")\" << endl;\r\n\r\n\tfor (int index = startFrame; index <= endFrame; index++)\r\n\t{\r\n\t\t\/\/ Get time associated with index\r\n\t\tdouble timeT = inputData.getStateVector(index)->getTime();\r\n\r\n\t\t\/* This sets the values of the prescribed coordinates, which\r\n\t\t * are coordinates that are:\r\n\t\t * (a) specified in the input data, and\r\n\t\t * (b) locked at that specified value.\r\n\t\t * These coordinates are not variables in the IK solving.\r\n\t\t * If a coordinate is specified in the file but not\r\n\t\t * locked, it is an unconstrained coordinate and it is\r\n\t\t * variable in the IK solving.\r\n\t\t *\/\r\n\t\t_ikTarget.setPrescribedCoordinates(index);\r\n\r\n\t\t\/\/ This sets the guess of unconstrained generalized coordinates \r\n\t\t\/\/ and marker data from recordedDataStorage\r\n\t\t_ikTarget.setIndexToSolve(index, &unconstrainedQGuess[0]);\r\n\r\n\t\t\/\/ Invoke optimization mechanism to solve for Qs\r\n\t\tint optimizerReturn = optimizer->computeOptimalControls(&unconstrainedQGuess[0], &unconstrainedQSol[0]);\r\n\r\n\t\t\/* Output variables include unconstrained (solved) Qs... *\/\r\n\t\tArray qsAndMarkersArray = unconstrainedQSol;\r\n\r\n\t\t\/* ... then prescribed Qs... *\/\r\n\t\tArray prescribedQValues(0.0);\r\n\t\t_ikTarget.getPrescribedQValues(prescribedQValues);\r\n\t\tqsAndMarkersArray.append(prescribedQValues);\r\n\r\n\t\t\/* ... then, optionally, computed marker locations. *\/\r\n\t\tif (aIKOptions.getIncludeMarkers())\r\n\t\t{\r\n\t\t\t_ikTarget.getExperimentalMarkerLocations(experimentalMarkerLocations);\r\n\t\t\tqsAndMarkersArray.append(experimentalMarkerLocations);\r\n\t\t}\r\n\r\n\t\tinputData.getTime(index, currentTime);\r\n\t\tcout << \"Solved frame \" << index + 1 << \" at time \" << currentTime << \", Optimizer returned = \" << optimizerReturn << endl;\r\n\r\n\t\t\/\/ INTEGRATION CALLBACKS\r\n\t\t\/\/ TODO: pass callback a reasonable \"dt\" value\r\n\t\tdouble emptyX, emptyY;\r\n\t\tIntegCallbackSet *callbackSet = _ikTarget.getModel().getIntegCallbackSet();\r\n\t\tif(callbackSet!=NULL)\r\n\t\t\tcallbackSet->step(&emptyX,&emptyY,index-startFrame-1,0,currentTime,&emptyX,&emptyY);\r\n\r\n\t\t\/\/ ANALYSES\r\n\t\t\/\/ TODO: pass callback a reasonable \"dt\" value\r\n\t\tAnalysisSet *analysisSet = _ikTarget.getModel().getAnalysisSet();\r\n\t\tif(analysisSet!=NULL)\r\n\t\t\tanalysisSet->step(&emptyX,&emptyY,index-startFrame-1,0,currentTime,&emptyX,&emptyY);\r\n\r\n\t\t\/\/ Append user data to qsAndMarkersArray\r\n\t\tArray dataRow(qsAndMarkersArray);\r\n\t\tappendUserData(dataRow, userDataColumnIndices, inputData.getStateVector(index));\r\n\r\n\t\t\/\/ Allocate new row (StateVector) and add it to outputData\r\n\t\tStateVector *nextDataRow = new StateVector();\r\n\t\tnextDataRow->setStates(timeT, dataRow.getSize(), &dataRow[0]);\r\n\t\toutputData.append(*nextDataRow);\r\n\t}\r\n\r\n\tdelete optimizer;\r\n}\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * UserData is the set of columns that are not used directly by the IK problem (for example\r\n * ground reaction forces). This UserData needs to be carried along in IK.\r\n *\/\r\nvoid SimmIKSolverImpl::collectUserData(const Array &inputColumnLabels,\r\n\t\t\t\t\t\t\t\t\t string& resultsHeader, \r\n\t\t\t\t\t\t\t\t\t string& userHeaders, \r\n\t\t\t\t\t\t\t\t\t Array& userDataColumnIndices)\r\n{\r\n\t\/\/ Find columns that are none of the above to append them to the end of the list\r\n\tint i;\r\n\tfor(i=0; i< inputColumnLabels.getSize(); i++){\r\n\t\tstring nextLabel = inputColumnLabels[i];\r\n\t\t\/\/ We'll find out if the column is already there by doing string search for \r\n\t\t\/\/ either \\t$column or $column\\t to account for substrings\r\n\t\tstring searchString1(nextLabel+\"\\t\");\r\n\t\tstring searchString2(\"\\t\"+nextLabel);\r\n\t\tif (strstr(resultsHeader.c_str(), searchString1.c_str())==0 &&\r\n\t\t\tstrstr(resultsHeader.c_str(), searchString2.c_str())==0 ){\r\n\t\t\t\/\/ Append to userHeaders\r\n\t\t\tuserHeaders += nextLabel+\"\\t\";\r\n\t\t\t\/\/ Keep track of indices to match data with labels\r\n\t\t\tuserDataColumnIndices.append(i);\r\n\r\n\t\t\t\/\/ cout << \"Column:\" << nextLabel << \" index\" << i << endl;\r\n\t\t}\r\n\t}\r\n}\r\n\/\/______________________________________________________________________________\r\n\/**\r\n * Companion helper function to (collectUserData) responsible for appending user columns \r\n * to outputRow.\r\n *\/\r\nvoid SimmIKSolverImpl::appendUserData(Array& outputRow, Array& indices, StateVector* inputRow)\r\n{\r\n\tint i;\r\n\tfor(i=0; i< indices.getSize(); i++){\r\n\t\tdouble userValue=rdMath::NAN;\r\n\t\tint index = indices[i]-1;\r\n\t\tinputRow->getDataValue(index, userValue);\r\n\t\toutputRow.append(userValue);\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/\/\n\/\/ CVector_fwd.hpp\n\/\/ ~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_CVECTOR_FWD_HPP\n#define EIGENJS_CVECTOR_FWD_HPP\n\n#include \n\n#include \n\n#include \n\nnamespace EigenJS {\n\nBOOST_CONSTEXPR char cvector_class_name[] = \"CVector\";\n\ntemplate <\n typename ScalarType = double\n, typename ValueType = Eigen::Matrix<\n std::complex\n , Eigen::Dynamic\n , 1\n >\n, const char* ClassName = cvector_class_name\n> class CVector;\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_CVECTOR_FWD_HPP\nsrc: fixed a mistake\/\/\n\/\/ CVector_fwd.hpp\n\/\/ ~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_CVECTOR_FWD_HPP\n#define EIGENJS_CVECTOR_FWD_HPP\n\n#include \n\n#include \n\n#include \n\nnamespace EigenJS {\n\nBOOST_CONSTEXPR char cvector_class_name[] = \"CVector\";\n\ntemplate <\n typename ScalarType = double\n, typename ValueType = Eigen::Matrix<\n std::complex\n , 1\n , Eigen::Dynamic\n >\n, const char* ClassName = cvector_class_name\n> class CVector;\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_CVECTOR_FWD_HPP\n<|endoftext|>"} {"text":"#include \"dispatch_queue.h\"\n\n#include \n#include \n\nstruct dispatch_queue_t::impl\n{\n impl();\n static void dispatch_thread_proc(impl *self);\n\n std::queue< std::function< void() > > queue;\n std::mutex queue_mtx;\n std::condition_variable queue_cond;\n std::atomic< bool > quit;\n std::thread queue_thread;\n\n using queue_lock_t = std::unique_lock< decltype(queue_mtx) >;\n};\n\nvoid dispatch_queue_t::impl::dispatch_thread_proc(dispatch_queue_t::impl *self)\n{\n using queue_size_t = decltype(self->queue)::size_type;\n\n while (self->quit == false)\n {\n queue_lock_t queue_lock(self->queue_mtx);\n queue_size_t n = self->queue.size();\n\n self->queue_cond.wait(queue_lock, [&self] { return self->queue.size() > 0; });\n\n for (queue_size_t i = 0; i < n; ++i) {\n auto dispatch_func = self->queue.front();\n self->queue.pop();\n\n queue_lock.unlock();\n dispatch_func();\n queue_lock.lock();\n }\n }\n}\n\ndispatch_queue_t::impl::impl()\n : quit(false)\n , queue_thread(&dispatch_thread_proc, this)\n{\n}\n\ndispatch_queue_t::dispatch_queue_t()\n : m(new impl)\n{\n}\n\ndispatch_queue_t::~dispatch_queue_t()\n{\n dispatch_async([this] { m->quit = true; });\n m->queue_thread.join();\n}\n\nvoid dispatch_queue_t::dispatch_async(std::function< void() > func)\n{\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue_cond.notify_one();\n}\n\nvoid dispatch_queue_t::dispatch_sync(std::function< void() > func)\n{\n std::mutex sync_mtx;\n impl::queue_lock_t sync_lock(sync_mtx);\n std::condition_variable sync_cond;\n auto completed = false;\n\n {\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue.push([&]() {\n std::unique_lock< decltype(sync_mtx) > sync_cb_lock(sync_mtx);\n completed = true;\n sync_cond.notify_one();\n });\n\n m->queue_cond.notify_one();\n }\n\n sync_cond.wait(sync_lock, [&completed] { return completed; });\n}\n\nvoid dispatch_queue_t::dispatch_flush()\n{\n dispatch_sync([]{});\n}\n\ncalculate n after queue_size > 0, remove parens for empty lambda#include \"dispatch_queue.h\"\n\n#include \n#include \n\nstruct dispatch_queue_t::impl\n{\n impl();\n static void dispatch_thread_proc(impl *self);\n\n std::queue< std::function< void() > > queue;\n std::mutex queue_mtx;\n std::condition_variable queue_cond;\n std::atomic< bool > quit;\n std::thread queue_thread;\n\n using queue_lock_t = std::unique_lock< decltype(queue_mtx) >;\n};\n\nvoid dispatch_queue_t::impl::dispatch_thread_proc(dispatch_queue_t::impl *self)\n{\n using queue_size_t = decltype(self->queue)::size_type;\n\n while (self->quit == false)\n {\n queue_lock_t queue_lock(self->queue_mtx);\n self->queue_cond.wait(queue_lock, [&self] { return self->queue.size() > 0; });\n\n queue_size_t n = self->queue.size();\n\n for (queue_size_t i = 0; i < n; ++i) {\n auto dispatch_func = self->queue.front();\n self->queue.pop();\n\n queue_lock.unlock();\n dispatch_func();\n queue_lock.lock();\n }\n }\n}\n\ndispatch_queue_t::impl::impl()\n : quit(false)\n , queue_thread(&dispatch_thread_proc, this)\n{\n}\n\ndispatch_queue_t::dispatch_queue_t()\n : m(new impl)\n{\n}\n\ndispatch_queue_t::~dispatch_queue_t()\n{\n dispatch_async([this] { m->quit = true; });\n m->queue_thread.join();\n}\n\nvoid dispatch_queue_t::dispatch_async(std::function< void() > func)\n{\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue_cond.notify_one();\n}\n\nvoid dispatch_queue_t::dispatch_sync(std::function< void() > func)\n{\n std::mutex sync_mtx;\n impl::queue_lock_t sync_lock(sync_mtx);\n std::condition_variable sync_cond;\n auto completed = false;\n\n {\n impl::queue_lock_t queue_lock(m->queue_mtx);\n m->queue.push(func);\n m->queue.push([&] {\n std::unique_lock< decltype(sync_mtx) > sync_cb_lock(sync_mtx);\n completed = true;\n sync_cond.notify_one();\n });\n\n m->queue_cond.notify_one();\n }\n\n sync_cond.wait(sync_lock, [&completed] { return completed; });\n}\n\nvoid dispatch_queue_t::dispatch_flush()\n{\n dispatch_sync([]{});\n}\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"ImageStackDialog.h\"\n\n#include \"ui_ImageStackDialog.h\"\n\n#include \"LoadStackReaction.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nextern \"C\" {\n#include \"vtk_tiff.h\"\n}\n\nnamespace tomviz {\n\nImageStackDialog::ImageStackDialog(QWidget* parent)\n : QDialog(parent), m_ui(new Ui::ImageStackDialog)\n{\n m_ui->setupUi(this);\n m_ui->tableView->setModel(&m_tableModel);\n QObject::connect(this, &ImageStackDialog::summaryChanged, &m_tableModel,\n &ImageStackModel::onFilesInfoChanged);\n\n QObject::connect(this, &ImageStackDialog::stackTypeChanged, &m_tableModel,\n &ImageStackModel::onStackTypeChanged);\n\n QObject::connect(m_ui->openFile, &QPushButton::clicked, this,\n &ImageStackDialog::onOpenFileClick);\n\n QObject::connect(m_ui->openFolder, &QPushButton::clicked, this,\n &ImageStackDialog::onOpenFolderClick);\n\n QObject::connect(&m_tableModel, &ImageStackModel::toggledSelected, this,\n &ImageStackDialog::onImageToggled);\n\n m_ui->loadedContainer->hide();\n m_ui->stackTypeCombo->setDisabled(true);\n m_ui->stackTypeCombo->insertItem(DataSource::DataSourceType::Volume,\n QString(\"Volume\"));\n m_ui->stackTypeCombo->insertItem(DataSource::DataSourceType::TiltSeries,\n QString(\"Tilt Series\"));\n\n \/\/ Due to an overloaded signal I am force to use static_cast here.\n QObject::connect(m_ui->stackTypeCombo, static_cast(\n &QComboBox::currentIndexChanged),\n this, &ImageStackDialog::onStackTypeChanged);\n\n setAcceptDrops(true);\n}\n\nImageStackDialog::~ImageStackDialog() = default;\n\nvoid ImageStackDialog::setStackSummary(const QList& summary,\n bool sort)\n{\n m_summary = summary;\n if (sort) {\n std::sort(m_summary.begin(), m_summary.end(),\n [](const ImageInfo& a, const ImageInfo& b) -> bool {\n \/\/ Place the inconsistent images at the top, so the user will\n \/\/ notice them.\n if (a.consistent == b.consistent) {\n return a.pos < b.pos;\n } else {\n return !a.consistent;\n }\n });\n }\n emit summaryChanged(m_summary);\n m_ui->emptyContainer->hide();\n m_ui->loadedContainer->show();\n m_ui->stackTypeCombo->setEnabled(true);\n m_ui->tableView->resizeColumnsToContents();\n m_ui->tableView->horizontalHeader()->setSectionResizeMode(\n 1, QHeaderView::Stretch);\n setAcceptDrops(false);\n}\n\nvoid ImageStackDialog::setStackType(const DataSource::DataSourceType& stackType)\n{\n if (m_stackType != stackType) {\n m_stackType = stackType;\n emit stackTypeChanged(m_stackType);\n m_ui->stackTypeCombo->setCurrentIndex(m_stackType);\n }\n}\n\nvoid ImageStackDialog::onOpenFileClick()\n{\n openFileDialog(QFileDialog::ExistingFiles);\n}\n\nvoid ImageStackDialog::onOpenFolderClick()\n{\n openFileDialog(QFileDialog::Directory);\n}\n\nvoid ImageStackDialog::openFileDialog(int mode)\n{\n QStringList filters;\n filters << \"TIFF Image files (*.tiff *.tif)\";\n\n QFileDialog dialog(nullptr);\n if (mode == QFileDialog::ExistingFiles) {\n dialog.setFileMode(QFileDialog::ExistingFiles);\n dialog.setNameFilters(filters);\n } else if (mode == QFileDialog::Directory) {\n dialog.setFileMode(QFileDialog::Directory);\n dialog.setOption(QFileDialog::ShowDirsOnly, true);\n }\n\n if (dialog.exec()) {\n QStringList fileNames;\n if (mode == QFileDialog::ExistingFiles) {\n processFiles(dialog.selectedFiles());\n } else if (mode == QFileDialog::Directory) {\n processDirectory(dialog.selectedFiles()[0]);\n }\n }\n}\n\nvoid ImageStackDialog::processDirectory(const QString& path)\n{\n QStringList fileNames;\n QDir directory(path);\n foreach (auto file, directory.entryList(QDir::Files)) {\n fileNames << directory.absolutePath() + QDir::separator() + file;\n }\n processFiles(fileNames);\n}\n\nvoid ImageStackDialog::processFiles(const QStringList& fileNames)\n{\n QStringList fNames;\n foreach (auto file, fileNames) {\n if (file.endsWith(\".tif\") || file.endsWith(\".tiff\")) {\n fNames << file;\n }\n }\n QList summary = initStackSummary(fNames);\n\n bool isVolume = false;\n bool isTilt = false;\n bool isNumbered = false;\n DataSource::DataSourceType stackType = DataSource::DataSourceType::Volume;\n\n isVolume = detectVolume(fNames, summary);\n if (!isVolume) {\n isTilt = detectTilt(fNames, summary);\n if (isTilt) {\n stackType = DataSource::DataSourceType::TiltSeries;\n } else {\n isNumbered = detectVolume(fNames, summary, false);\n if (!isNumbered) {\n defaultOrder(fNames, summary);\n }\n }\n }\n setStackType(stackType);\n\n auto readImage = [this](QStringList files, int me, int n,\n QList* s) {\n for (auto i = me; i < files.size(); i += n) {\n uint32_t w;\n uint32_t h;\n TIFF* tif = TIFFOpen(files[i].toLatin1().data(), \"r\");\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n TIFFClose(tif);\n (*s)[i].m = w;\n (*s)[i].n = h;\n }\n };\n\n const unsigned int minCores = 1;\n const unsigned int nCores =\n std::max(std::thread::hardware_concurrency(), minCores);\n const unsigned int maxThreads = 8;\n const unsigned int nThreads = std::min(nCores, maxThreads);\n std::vector threads(nThreads);\n\n for (unsigned int i = 0; i < nThreads; ++i) {\n threads[i] = std::thread(readImage, fNames, i, nThreads, &summary);\n }\n\n for (unsigned int i = 0; i < nThreads; ++i) {\n threads[i].join();\n }\n\n \/\/ check consistency\n if (summary.size() > 0) {\n const auto m = summary[0].m;\n const auto n = summary[1].n;\n for (auto i = 0; i < summary.size(); ++i) {\n if (summary[i].m == m && summary[i].n == n) {\n summary[i].consistent = true;\n summary[i].selected = true;\n }\n }\n }\n\n setStackSummary(summary, true);\n}\n\nbool ImageStackDialog::detectVolume(QStringList fileNames,\n QList& summary, bool matchPrefix)\n{\n if (fileNames.size() < 1) {\n return false;\n }\n QString thePrefix;\n QString prefix;\n int num;\n QRegExp volRegExp(\"^(.*[^\\\\d]{1})(\\\\d+)(\\\\.(tif|tiff))$\");\n\n for (int i = 0; i < fileNames.size(); ++i) {\n if (volRegExp.exactMatch(fileNames[i])) {\n prefix = volRegExp.cap(1);\n if (i == 0) {\n thePrefix = prefix;\n }\n if (prefix == thePrefix || !matchPrefix) {\n num = volRegExp.cap(2).toInt();\n summary[i].pos = num;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n}\n\nbool ImageStackDialog::detectTilt(QStringList fileNames,\n QList& summary, bool matchPrefix)\n{\n if (fileNames.size() < 1) {\n return false;\n }\n QString thePrefix;\n QString prefix;\n int num;\n QString sign;\n QString numStr;\n QString ext;\n\n QRegExp tiltRegExp(\"^.*([p+]|[n-])?(\\\\d+)(\\\\.(tif|tiff))$\");\n\n for (int i = 0; i < fileNames.size(); ++i) {\n if (tiltRegExp.exactMatch(fileNames[i])) {\n sign = tiltRegExp.cap(1);\n numStr = tiltRegExp.cap(2);\n ext = tiltRegExp.cap(3);\n prefix = fileNames[i];\n prefix.replace(sign + numStr + ext, QString());\n if (i == 0) {\n thePrefix = prefix;\n }\n if (prefix == thePrefix || !matchPrefix) {\n if (sign == \"p\") {\n sign = \"+\";\n } else if (sign == \"n\") {\n sign = \"-\";\n }\n num = (sign + numStr).toInt();\n summary[i].pos = num;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n}\n\nvoid ImageStackDialog::defaultOrder(QStringList fileNames,\n QList& summary)\n{\n if (fileNames.size() != summary.size()) {\n return;\n }\n for (int i = 0; i < fileNames.size(); ++i) {\n summary[i].pos = i;\n }\n}\n\nvoid ImageStackDialog::dragEnterEvent(QDragEnterEvent* event)\n{\n if (event->mimeData()->hasUrls()) {\n event->acceptProposedAction();\n }\n}\n\nvoid ImageStackDialog::dropEvent(QDropEvent* event)\n{\n if (event->mimeData()->hasUrls()) {\n QStringList pathList;\n QString path;\n QList urlList = event->mimeData()->urls();\n bool openDirs = true;\n for (int i = 0; i < urlList.size(); ++i) {\n path = urlList.at(i).toLocalFile();\n QFileInfo fileInfo(path);\n if (fileInfo.exists()) {\n if (fileInfo.isDir() && openDirs) {\n processDirectory(path);\n return;\n } else if (fileInfo.isFile()) {\n pathList.append(path);\n }\n \/\/ only open the first directory being dropped\n openDirs = false;\n }\n }\n processFiles(pathList);\n }\n}\n\nQList ImageStackDialog::initStackSummary(\n const QStringList& fileNames)\n{\n QList summary;\n int n = -1;\n int m = -1;\n bool consistent = false;\n foreach (QString file, fileNames) {\n summary.push_back(ImageInfo(file, 0, m, n, consistent));\n }\n return summary;\n}\n\nQList ImageStackDialog::getStackSummary() const\n{\n return m_summary;\n}\n\nDataSource::DataSourceType ImageStackDialog::getStackType() const\n{\n return m_stackType;\n}\n\nvoid ImageStackDialog::onImageToggled(int row, bool value)\n{\n m_summary[row].selected = value;\n emit summaryChanged(m_summary);\n}\n\nvoid ImageStackDialog::onStackTypeChanged(int stackType)\n{\n if (stackType == DataSource::DataSourceType::Volume) {\n setStackType(DataSource::DataSourceType::Volume);\n } else if (stackType == DataSource::DataSourceType::TiltSeries) {\n setStackType(DataSource::DataSourceType::TiltSeries);\n }\n}\n\n} \/\/ namespace tomviz\nSuppress libTiff warning output\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"ImageStackDialog.h\"\n\n#include \"ui_ImageStackDialog.h\"\n\n#include \"LoadStackReaction.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nextern \"C\" {\n#include \"vtk_tiff.h\"\n}\n\nnamespace tomviz {\n\nImageStackDialog::ImageStackDialog(QWidget* parent)\n : QDialog(parent), m_ui(new Ui::ImageStackDialog)\n{\n m_ui->setupUi(this);\n m_ui->tableView->setModel(&m_tableModel);\n QObject::connect(this, &ImageStackDialog::summaryChanged, &m_tableModel,\n &ImageStackModel::onFilesInfoChanged);\n\n QObject::connect(this, &ImageStackDialog::stackTypeChanged, &m_tableModel,\n &ImageStackModel::onStackTypeChanged);\n\n QObject::connect(m_ui->openFile, &QPushButton::clicked, this,\n &ImageStackDialog::onOpenFileClick);\n\n QObject::connect(m_ui->openFolder, &QPushButton::clicked, this,\n &ImageStackDialog::onOpenFolderClick);\n\n QObject::connect(&m_tableModel, &ImageStackModel::toggledSelected, this,\n &ImageStackDialog::onImageToggled);\n\n m_ui->loadedContainer->hide();\n m_ui->stackTypeCombo->setDisabled(true);\n m_ui->stackTypeCombo->insertItem(DataSource::DataSourceType::Volume,\n QString(\"Volume\"));\n m_ui->stackTypeCombo->insertItem(DataSource::DataSourceType::TiltSeries,\n QString(\"Tilt Series\"));\n\n \/\/ Due to an overloaded signal I am force to use static_cast here.\n QObject::connect(m_ui->stackTypeCombo, static_cast(\n &QComboBox::currentIndexChanged),\n this, &ImageStackDialog::onStackTypeChanged);\n\n setAcceptDrops(true);\n}\n\nImageStackDialog::~ImageStackDialog() = default;\n\nvoid ImageStackDialog::setStackSummary(const QList& summary,\n bool sort)\n{\n m_summary = summary;\n if (sort) {\n std::sort(m_summary.begin(), m_summary.end(),\n [](const ImageInfo& a, const ImageInfo& b) -> bool {\n \/\/ Place the inconsistent images at the top, so the user will\n \/\/ notice them.\n if (a.consistent == b.consistent) {\n return a.pos < b.pos;\n } else {\n return !a.consistent;\n }\n });\n }\n emit summaryChanged(m_summary);\n m_ui->emptyContainer->hide();\n m_ui->loadedContainer->show();\n m_ui->stackTypeCombo->setEnabled(true);\n m_ui->tableView->resizeColumnsToContents();\n m_ui->tableView->horizontalHeader()->setSectionResizeMode(\n 1, QHeaderView::Stretch);\n setAcceptDrops(false);\n}\n\nvoid ImageStackDialog::setStackType(const DataSource::DataSourceType& stackType)\n{\n if (m_stackType != stackType) {\n m_stackType = stackType;\n emit stackTypeChanged(m_stackType);\n m_ui->stackTypeCombo->setCurrentIndex(m_stackType);\n }\n}\n\nvoid ImageStackDialog::onOpenFileClick()\n{\n openFileDialog(QFileDialog::ExistingFiles);\n}\n\nvoid ImageStackDialog::onOpenFolderClick()\n{\n openFileDialog(QFileDialog::Directory);\n}\n\nvoid ImageStackDialog::openFileDialog(int mode)\n{\n QStringList filters;\n filters << \"TIFF Image files (*.tiff *.tif)\";\n\n QFileDialog dialog(nullptr);\n if (mode == QFileDialog::ExistingFiles) {\n dialog.setFileMode(QFileDialog::ExistingFiles);\n dialog.setNameFilters(filters);\n } else if (mode == QFileDialog::Directory) {\n dialog.setFileMode(QFileDialog::Directory);\n dialog.setOption(QFileDialog::ShowDirsOnly, true);\n }\n\n if (dialog.exec()) {\n QStringList fileNames;\n if (mode == QFileDialog::ExistingFiles) {\n processFiles(dialog.selectedFiles());\n } else if (mode == QFileDialog::Directory) {\n processDirectory(dialog.selectedFiles()[0]);\n }\n }\n}\n\nvoid ImageStackDialog::processDirectory(const QString& path)\n{\n QStringList fileNames;\n QDir directory(path);\n foreach (auto file, directory.entryList(QDir::Files)) {\n fileNames << directory.absolutePath() + QDir::separator() + file;\n }\n processFiles(fileNames);\n}\n\nvoid ImageStackDialog::processFiles(const QStringList& fileNames)\n{\n QStringList fNames;\n foreach (auto file, fileNames) {\n if (file.endsWith(\".tif\") || file.endsWith(\".tiff\")) {\n fNames << file;\n }\n }\n QList summary = initStackSummary(fNames);\n\n bool isVolume = false;\n bool isTilt = false;\n bool isNumbered = false;\n DataSource::DataSourceType stackType = DataSource::DataSourceType::Volume;\n\n isVolume = detectVolume(fNames, summary);\n if (!isVolume) {\n isTilt = detectTilt(fNames, summary);\n if (isTilt) {\n stackType = DataSource::DataSourceType::TiltSeries;\n } else {\n isNumbered = detectVolume(fNames, summary, false);\n if (!isNumbered) {\n defaultOrder(fNames, summary);\n }\n }\n }\n setStackType(stackType);\n\n auto readImage = [this](QStringList files, int me, int n,\n QList* s) {\n TIFFSetWarningHandler(nullptr);\n for (auto i = me; i < files.size(); i += n) {\n uint32_t w = -1;\n uint32_t h = -1;\n TIFF* tif = TIFFOpen(files[i].toLatin1().data(), \"r\");\n if (tif) {\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);\n TIFFClose(tif);\n }\n (*s)[i].m = w;\n (*s)[i].n = h;\n }\n };\n\n const unsigned int minCores = 1;\n const unsigned int nCores =\n std::max(std::thread::hardware_concurrency(), minCores);\n const unsigned int maxThreads = 4;\n const unsigned int nThreads = std::min(nCores, maxThreads);\n std::vector threads(nThreads);\n\n for (unsigned int i = 0; i < nThreads; ++i) {\n threads[i] = std::thread(readImage, fNames, i, nThreads, &summary);\n }\n\n for (unsigned int i = 0; i < nThreads; ++i) {\n threads[i].join();\n }\n\n \/\/ check consistency\n if (summary.size() > 0) {\n const auto m = summary[0].m;\n const auto n = summary[1].n;\n for (auto i = 0; i < summary.size(); ++i) {\n if (summary[i].m == m && summary[i].n == n) {\n summary[i].consistent = true;\n summary[i].selected = true;\n }\n }\n }\n\n setStackSummary(summary, true);\n}\n\nbool ImageStackDialog::detectVolume(QStringList fileNames,\n QList& summary, bool matchPrefix)\n{\n if (fileNames.size() < 1) {\n return false;\n }\n QString thePrefix;\n QString prefix;\n int num;\n QRegExp volRegExp(\"^(.*[^\\\\d]{1})(\\\\d+)(\\\\.(tif|tiff))$\");\n\n for (int i = 0; i < fileNames.size(); ++i) {\n if (volRegExp.exactMatch(fileNames[i])) {\n prefix = volRegExp.cap(1);\n if (i == 0) {\n thePrefix = prefix;\n }\n if (prefix == thePrefix || !matchPrefix) {\n num = volRegExp.cap(2).toInt();\n summary[i].pos = num;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n}\n\nbool ImageStackDialog::detectTilt(QStringList fileNames,\n QList& summary, bool matchPrefix)\n{\n if (fileNames.size() < 1) {\n return false;\n }\n QString thePrefix;\n QString prefix;\n int num;\n QString sign;\n QString numStr;\n QString ext;\n\n QRegExp tiltRegExp(\"^.*([p+]|[n-])?(\\\\d+)(\\\\.(tif|tiff))$\");\n\n for (int i = 0; i < fileNames.size(); ++i) {\n if (tiltRegExp.exactMatch(fileNames[i])) {\n sign = tiltRegExp.cap(1);\n numStr = tiltRegExp.cap(2);\n ext = tiltRegExp.cap(3);\n prefix = fileNames[i];\n prefix.replace(sign + numStr + ext, QString());\n if (i == 0) {\n thePrefix = prefix;\n }\n if (prefix == thePrefix || !matchPrefix) {\n if (sign == \"p\") {\n sign = \"+\";\n } else if (sign == \"n\") {\n sign = \"-\";\n }\n num = (sign + numStr).toInt();\n summary[i].pos = num;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n}\n\nvoid ImageStackDialog::defaultOrder(QStringList fileNames,\n QList& summary)\n{\n if (fileNames.size() != summary.size()) {\n return;\n }\n for (int i = 0; i < fileNames.size(); ++i) {\n summary[i].pos = i;\n }\n}\n\nvoid ImageStackDialog::dragEnterEvent(QDragEnterEvent* event)\n{\n if (event->mimeData()->hasUrls()) {\n event->acceptProposedAction();\n }\n}\n\nvoid ImageStackDialog::dropEvent(QDropEvent* event)\n{\n if (event->mimeData()->hasUrls()) {\n QStringList pathList;\n QString path;\n QList urlList = event->mimeData()->urls();\n bool openDirs = true;\n for (int i = 0; i < urlList.size(); ++i) {\n path = urlList.at(i).toLocalFile();\n QFileInfo fileInfo(path);\n if (fileInfo.exists()) {\n if (fileInfo.isDir() && openDirs) {\n processDirectory(path);\n return;\n } else if (fileInfo.isFile()) {\n pathList.append(path);\n }\n \/\/ only open the first directory being dropped\n openDirs = false;\n }\n }\n processFiles(pathList);\n }\n}\n\nQList ImageStackDialog::initStackSummary(\n const QStringList& fileNames)\n{\n QList summary;\n int n = -1;\n int m = -1;\n bool consistent = false;\n foreach (QString file, fileNames) {\n summary.push_back(ImageInfo(file, 0, m, n, consistent));\n }\n return summary;\n}\n\nQList ImageStackDialog::getStackSummary() const\n{\n return m_summary;\n}\n\nDataSource::DataSourceType ImageStackDialog::getStackType() const\n{\n return m_stackType;\n}\n\nvoid ImageStackDialog::onImageToggled(int row, bool value)\n{\n m_summary[row].selected = value;\n emit summaryChanged(m_summary);\n}\n\nvoid ImageStackDialog::onStackTypeChanged(int stackType)\n{\n if (stackType == DataSource::DataSourceType::Volume) {\n setStackType(DataSource::DataSourceType::Volume);\n } else if (stackType == DataSource::DataSourceType::TiltSeries) {\n setStackType(DataSource::DataSourceType::TiltSeries);\n }\n}\n\n} \/\/ namespace tomviz\n<|endoftext|>"} {"text":"\/\/\/ Simple sockets buffer output client test\n\/\/\/ This test cover if simple socket client can send message to a boost based\n\/\/\/ server application.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::asio::ip::tcp;\n\nsize_t bytesReaded;\nstd::string message;\nstd::string expectedMessage = \"I'm here!\";\nboost::system::error_code error;\n\n\/\/\/ Server side, boost pure implementation\n\/**\n * Open port listening for a connection,\n * when someone connects waits for a message.\n *\/\nvoid server(void) {\n\tboost::asio::io_service io_service;\n\n\tconst unsigned short port = 12345;\n\ttcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port));\n\n\ttcp::socket socket(io_service);\n\tacceptor.accept(socket);\n\n\tstd::array buffer;\n\n\tbytesReaded = socket.read_some(\n\t\t\tboost::asio::buffer(buffer.data(), buffer.size()),\n\t\t\terror);\n\tmessage = std::string(buffer.begin(), buffer.begin() + bytesReaded);\n}\n\n#include \"..\/..\/src\/Socket.hpp\"\n#include \n\n\/\/\/ Client side using simple sockets\n\/**\n * Connect to server and send a message.\n *\/\nvoid client(void) {\n\tusing namespace simple;\n\n\tSocketBuffer buffer(\"localhost\", 12345);\n\tstd::ostream out(&buffer);\n\n\tout << expectedMessage << std::endl;\n}\n\n#include \n\n\/\/\/ Main test\n\/**\n * Start server take a while and start client.\n * Then test if communication is ok.\n *\/\nint main(void) {\n\tstd::thread serverRun(server);\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\tclient();\n\tserverRun.join();\n\t\n\tassert(error == 0);\n\tassert(bytesReaded == expectedMessage.size() + 1);\n\tassert(message == expectedMessage + \"\\n\");\n\n\treturn 0;\n}\nFix output client test\/\/\/ Simple sockets buffer output client test\n\/\/\/ This test cover if simple socket client can send message to a boost based\n\/\/\/ server application.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::asio::ip::tcp;\n\nsize_t bytesReaded;\nstd::string message;\nstd::string expectedMessage = \"I'm here!\";\nboost::system::error_code error;\n\n\/\/\/ Server side, boost pure implementation\n\/**\n * Open port listening for a connection,\n * when someone connects waits for a message.\n *\/\nvoid server(void) {\n\tboost::asio::io_service io_service;\n\n\tconst unsigned short port = 12345;\n\ttcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port));\n\n\ttcp::socket socket(io_service);\n\tacceptor.accept(socket);\n\n\tstd::array buffer;\n\n\tbytesReaded = socket.read_some(\n\t\t\tboost::asio::buffer(buffer.data(), buffer.size()),\n\t\t\terror);\n\tmessage = std::string(buffer.begin(), buffer.begin() + bytesReaded);\n}\n\n#include \"..\/..\/src\/SocketBuffer.hpp\"\n#include \n\n\/\/\/ Client side using simple sockets\n\/**\n * Connect to server and send a message.\n *\/\nvoid client(void) {\n\tusing namespace simple;\n\n\tSocketBuffer buffer(\"localhost\", 12345);\n\tstd::ostream out(&buffer);\n\n\tout << expectedMessage << std::endl;\n}\n\n#include \n\n\/\/\/ Main test\n\/**\n * Start server take a while and start client.\n * Then test if communication is ok.\n *\/\nint main(void) {\n\tstd::thread serverRun(server);\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\tclient();\n\tserverRun.join();\n\n\tassert(error == 0);\n\tassert(bytesReaded == expectedMessage.size() + 1);\n\tassert(message == expectedMessage + \"\\n\");\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/ Copyright 2017 Netherlands eScience Center\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\nvoid processCommandLineOptions(isa::utils::ArgumentList & argumentList, Options & options, DeviceOptions & deviceOptions, DataOptions & dataOptions, KernelConfigurations & kernelConfigurations, GeneratorOptions & generatorOptions, AstroData::Observation & observation) {\n try {\n options.debug = argumentList.getSwitch(\"-debug\");\n options.print = argumentList.getSwitch(\"-print\");\n options.splitBatchesDedispersion = argumentList.getSwitch(\"-splitbatches_dedispersion\");\n options.subbandDedispersion = argumentList.getSwitch(\"-subband_dedispersion\");\n options.compactResults = argumentList.getSwitch(\"-compact_results\");\n options.threshold = argumentList.getSwitchArgument(\"-threshold\");\n deviceOptions.platformID = argumentList.getSwitchArgument(\"-opencl_platform\");\n deviceOptions.deviceID = argumentList.getSwitchArgument(\"-opencl_device\");\n deviceOptions.deviceName = argumentList.getSwitchArgument(\"-device_name\");\n deviceOptions.synchronized = argumentList.getSwitch(\"-sync\");\n AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument(\"-padding_file\"));\n dataOptions.dataLOFAR = argumentList.getSwitch(\"-lofar\");\n#ifndef HAVE_HDF5\n if (dataOptions.dataLOFAR) {\n std::cerr << \"Not compiled with HDF5 support.\" << std::endl;\n throw std::exception();\n };\n#endif \/\/ HAVE_HDF5\n dataOptions.dataPSRDADA = argumentList.getSwitch(\"-dada\");\n#ifndef HAVE_PSRDADA\n if (dataOptions.dataPSRDADA) {\n std::cerr << \"Not compiled with PSRDADA support.\" << std::endl;\n throw std::exception();\n };\n#endif \/\/ HAVE_PSRDADA\n dataOptions.dataSIGPROC = argumentList.getSwitch(\"-sigproc\");\n if ( !((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA)\n || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC))\n || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR))\n || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)) ) {\n std::cerr << \"-lofar -sigproc and -dada are mutually exclusive.\" << std::endl;\n throw std::exception();\n }\n dataOptions.channelsFile = argumentList.getSwitchArgument(\"-zapped_channels\");\n dataOptions.integrationFile = argumentList.getSwitchArgument(\"-integration_steps\");\n if ( !options.subbandDedispersion ) {\n Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters,\n argumentList.getSwitchArgument(\"-dedispersion_file\"));\n } else {\n Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters,\n argumentList.getSwitchArgument(\"-dedispersion_stepone_file\"));\n Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters,\n argumentList.getSwitchArgument(\"-dedispersion_steptwo_file\"));\n }\n Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters,\n argumentList.getSwitchArgument(\"-integration_file\"));\n SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument(\"-snr_file\"));\n if ( dataOptions.dataLOFAR ) {\n#ifdef HAVE_HDF5\n observation.setNrBeams(1);\n observation.setNrSynthesizedBeams(1);\n dataOptions.headerFile = argumentList.getSwitchArgument(\"-header\");\n dataOptions.dataFile = argumentList.getSwitchArgument(\"-data\");\n dataOptions.limit = argumentList.getSwitch(\"-limit\");\n if ( dataOptions.limit ) {\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n }\n#endif \/\/ HAVE_HDF5\n } else if ( dataOptions.dataSIGPROC ) {\n observation.setNrBeams(1);\n observation.setNrSynthesizedBeams(1);\n dataOptions.streamingMode = argumentList.getSwitch(\"-stream\");\n dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument(\"-header\");\n dataOptions.dataFile = argumentList.getSwitchArgument(\"-data\");\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n if ( options.subbandDedispersion ) {\n observation.setFrequencyRange(argumentList.getSwitchArgument(\"-subbands\"),\n argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n } else {\n observation.setFrequencyRange(1, argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n }\n observation.setNrSamplesPerBatch(argumentList.getSwitchArgument(\"-samples\"));\n observation.setSamplingTime(argumentList.getSwitchArgument(\"-sampling_time\"));\n } else if ( dataOptions.dataPSRDADA ) {\n#ifdef HAVE_PSRDADA\n dataOptions.dadaKey = std::stoi(\"0x\" + argumentList.getSwitchArgument(\"-dada_key\"), 0, 16);\n if ( options.subbandDedispersion ) {\n observation.setFrequencyRange(argumentList.getSwitchArgument(\"-subbands\"), 1, 1.0f, 1.0f);\n } else {\n observation.setFrequencyRange(1, 1, 1.0f, 1.0f);\n }\n observation.setNrBeams(argumentList.getSwitchArgument(\"-beams\"));\n observation.setNrSynthesizedBeams(argumentList.getSwitchArgument(\"-synthesized_beams\"));\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n#endif \/\/ HAVE_PSRDADA\n } else {\n observation.setNrBeams(argumentList.getSwitchArgument(\"-beams\"));\n observation.setNrSynthesizedBeams(argumentList.getSwitchArgument(\"-synthesized_beams\"));\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n if ( options.subbandDedispersion ) {\n observation.setFrequencyRange(argumentList.getSwitchArgument(\"-subbands\"),\n argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n } else {\n observation.setFrequencyRange(1, argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n }\n observation.setNrSamplesPerBatch(argumentList.getSwitchArgument(\"-samples\"));\n observation.setSamplingTime(argumentList.getSwitchArgument(\"-sampling_time\"));\n generatorOptions.random = argumentList.getSwitch(\"-random\");\n generatorOptions.width = argumentList.getSwitchArgument(\"-width\");\n generatorOptions.DM = argumentList.getSwitchArgument(\"-dm\");\n }\n dataOptions.outputFile = argumentList.getSwitchArgument(\"-output\");\n if ( options.subbandDedispersion ) {\n observation.setDMRange(argumentList.getSwitchArgument(\"-subbanding_dms\"),\n argumentList.getSwitchArgument(\"-subbanding_dm_first\"),\n argumentList.getSwitchArgument(\"-subbanding_dm_step\"), true);\n }\n observation.setDMRange(argumentList.getSwitchArgument(\"-dms\"),\n argumentList.getSwitchArgument(\"-dm_first\"),\n argumentList.getSwitchArgument(\"-dm_step\"));\n } catch ( isa::utils::EmptyCommandLine & err ) {\n usage(argumentList.getName());\n throw;\n } catch ( isa::utils::SwitchNotFound & err ) {\n std::cerr << err.what() << std::endl;\n throw;\n } catch ( std::exception & err ) {\n std::cerr << err.what() << std::endl;\n throw;\n }\n}\n\nvoid usage(std::string & program) {\n std::cerr << program << \" -opencl_platform ... -opencl_device ... -device_name ... [-sync] -padding_file ...\";\n std::cerr << \"-zapped_channels ... -integration_steps ... -integration_file ... -snr_file ...\";\n std::cerr << \"[-splitbatches_dedispersion] [-subband_dedispersion] [-debug] [-print] [-compact_results] -output ...\";\n std::cerr << \"-dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]\";\n#ifdef HAVE_HDF5\n std::cerr << \" [-lofar]\";\n#endif \/\/ HAVE_HDF5\n#ifdef HAVE_PSRDADA\n std::cerr << \" [-dada]\";\n#endif \/\/ HAVE_PSRDADA\n std::cerr << std::endl;\n std::cerr << \"\\tDedispersion: -dedispersion_file ...\" << std::endl;\n std::cerr << \"\\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...\";\n std::cerr << \"-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...\";\n std::cerr << \"-subbanding_dm_step ...\" << std::endl;\n#ifdef HAVE_HDF5\n std::cerr << \"\\tLOFAR: -lofar -header ... -data ... [-limit]\" << std::endl;\n std::cerr << \"\\t\\t -limit -batches ...\" << std::endl;\n#endif \/\/ HAVE_HDF5\n std::cerr << \"\\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...\";\n std::cerr << \"-channel_bandwidth ... -samples ... -sampling_time ...\" << std::endl;\n#ifdef HAVE_PSRDADA\n std::cerr << \"\\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ...\" << std::endl;\n#endif \/\/ HAVE_PSRDADA\n std::cerr << \"\\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...\";\n std::cerr << \"-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ...\" << std::endl;\n}\nconst qualifier in declarations and definitions.\/\/ Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/ Copyright 2017 Netherlands eScience Center\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\nvoid processCommandLineOptions(const isa::utils::ArgumentList & argumentList, const Options & options, const DeviceOptions & deviceOptions, const DataOptions & dataOptions, const KernelConfigurations & kernelConfigurations, const GeneratorOptions & generatorOptions, const AstroData::Observation & observation) {\n try {\n options.debug = argumentList.getSwitch(\"-debug\");\n options.print = argumentList.getSwitch(\"-print\");\n options.splitBatchesDedispersion = argumentList.getSwitch(\"-splitbatches_dedispersion\");\n options.subbandDedispersion = argumentList.getSwitch(\"-subband_dedispersion\");\n options.compactResults = argumentList.getSwitch(\"-compact_results\");\n options.threshold = argumentList.getSwitchArgument(\"-threshold\");\n deviceOptions.platformID = argumentList.getSwitchArgument(\"-opencl_platform\");\n deviceOptions.deviceID = argumentList.getSwitchArgument(\"-opencl_device\");\n deviceOptions.deviceName = argumentList.getSwitchArgument(\"-device_name\");\n deviceOptions.synchronized = argumentList.getSwitch(\"-sync\");\n AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument(\"-padding_file\"));\n dataOptions.dataLOFAR = argumentList.getSwitch(\"-lofar\");\n#ifndef HAVE_HDF5\n if (dataOptions.dataLOFAR) {\n std::cerr << \"Not compiled with HDF5 support.\" << std::endl;\n throw std::exception();\n };\n#endif \/\/ HAVE_HDF5\n dataOptions.dataPSRDADA = argumentList.getSwitch(\"-dada\");\n#ifndef HAVE_PSRDADA\n if (dataOptions.dataPSRDADA) {\n std::cerr << \"Not compiled with PSRDADA support.\" << std::endl;\n throw std::exception();\n };\n#endif \/\/ HAVE_PSRDADA\n dataOptions.dataSIGPROC = argumentList.getSwitch(\"-sigproc\");\n if ( !((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA)\n || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC))\n || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR))\n || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)) ) {\n std::cerr << \"-lofar -sigproc and -dada are mutually exclusive.\" << std::endl;\n throw std::exception();\n }\n dataOptions.channelsFile = argumentList.getSwitchArgument(\"-zapped_channels\");\n dataOptions.integrationFile = argumentList.getSwitchArgument(\"-integration_steps\");\n if ( !options.subbandDedispersion ) {\n Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters,\n argumentList.getSwitchArgument(\"-dedispersion_file\"));\n } else {\n Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters,\n argumentList.getSwitchArgument(\"-dedispersion_stepone_file\"));\n Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters,\n argumentList.getSwitchArgument(\"-dedispersion_steptwo_file\"));\n }\n Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters,\n argumentList.getSwitchArgument(\"-integration_file\"));\n SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument(\"-snr_file\"));\n if ( dataOptions.dataLOFAR ) {\n#ifdef HAVE_HDF5\n observation.setNrBeams(1);\n observation.setNrSynthesizedBeams(1);\n dataOptions.headerFile = argumentList.getSwitchArgument(\"-header\");\n dataOptions.dataFile = argumentList.getSwitchArgument(\"-data\");\n dataOptions.limit = argumentList.getSwitch(\"-limit\");\n if ( dataOptions.limit ) {\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n }\n#endif \/\/ HAVE_HDF5\n } else if ( dataOptions.dataSIGPROC ) {\n observation.setNrBeams(1);\n observation.setNrSynthesizedBeams(1);\n dataOptions.streamingMode = argumentList.getSwitch(\"-stream\");\n dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument(\"-header\");\n dataOptions.dataFile = argumentList.getSwitchArgument(\"-data\");\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n if ( options.subbandDedispersion ) {\n observation.setFrequencyRange(argumentList.getSwitchArgument(\"-subbands\"),\n argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n } else {\n observation.setFrequencyRange(1, argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n }\n observation.setNrSamplesPerBatch(argumentList.getSwitchArgument(\"-samples\"));\n observation.setSamplingTime(argumentList.getSwitchArgument(\"-sampling_time\"));\n } else if ( dataOptions.dataPSRDADA ) {\n#ifdef HAVE_PSRDADA\n dataOptions.dadaKey = std::stoi(\"0x\" + argumentList.getSwitchArgument(\"-dada_key\"), 0, 16);\n if ( options.subbandDedispersion ) {\n observation.setFrequencyRange(argumentList.getSwitchArgument(\"-subbands\"), 1, 1.0f, 1.0f);\n } else {\n observation.setFrequencyRange(1, 1, 1.0f, 1.0f);\n }\n observation.setNrBeams(argumentList.getSwitchArgument(\"-beams\"));\n observation.setNrSynthesizedBeams(argumentList.getSwitchArgument(\"-synthesized_beams\"));\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n#endif \/\/ HAVE_PSRDADA\n } else {\n observation.setNrBeams(argumentList.getSwitchArgument(\"-beams\"));\n observation.setNrSynthesizedBeams(argumentList.getSwitchArgument(\"-synthesized_beams\"));\n observation.setNrBatches(argumentList.getSwitchArgument(\"-batches\"));\n if ( options.subbandDedispersion ) {\n observation.setFrequencyRange(argumentList.getSwitchArgument(\"-subbands\"),\n argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n } else {\n observation.setFrequencyRange(1, argumentList.getSwitchArgument(\"-channels\"),\n argumentList.getSwitchArgument(\"-min_freq\"),\n argumentList.getSwitchArgument(\"-channel_bandwidth\"));\n }\n observation.setNrSamplesPerBatch(argumentList.getSwitchArgument(\"-samples\"));\n observation.setSamplingTime(argumentList.getSwitchArgument(\"-sampling_time\"));\n generatorOptions.random = argumentList.getSwitch(\"-random\");\n generatorOptions.width = argumentList.getSwitchArgument(\"-width\");\n generatorOptions.DM = argumentList.getSwitchArgument(\"-dm\");\n }\n dataOptions.outputFile = argumentList.getSwitchArgument(\"-output\");\n if ( options.subbandDedispersion ) {\n observation.setDMRange(argumentList.getSwitchArgument(\"-subbanding_dms\"),\n argumentList.getSwitchArgument(\"-subbanding_dm_first\"),\n argumentList.getSwitchArgument(\"-subbanding_dm_step\"), true);\n }\n observation.setDMRange(argumentList.getSwitchArgument(\"-dms\"),\n argumentList.getSwitchArgument(\"-dm_first\"),\n argumentList.getSwitchArgument(\"-dm_step\"));\n } catch ( isa::utils::EmptyCommandLine & err ) {\n usage(argumentList.getName());\n throw;\n } catch ( isa::utils::SwitchNotFound & err ) {\n std::cerr << err.what() << std::endl;\n throw;\n } catch ( std::exception & err ) {\n std::cerr << err.what() << std::endl;\n throw;\n }\n}\n\nvoid usage(const std::string & program) {\n std::cerr << program << \" -opencl_platform ... -opencl_device ... -device_name ... [-sync] -padding_file ...\";\n std::cerr << \"-zapped_channels ... -integration_steps ... -integration_file ... -snr_file ...\";\n std::cerr << \"[-splitbatches_dedispersion] [-subband_dedispersion] [-debug] [-print] [-compact_results] -output ...\";\n std::cerr << \"-dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]\";\n#ifdef HAVE_HDF5\n std::cerr << \" [-lofar]\";\n#endif \/\/ HAVE_HDF5\n#ifdef HAVE_PSRDADA\n std::cerr << \" [-dada]\";\n#endif \/\/ HAVE_PSRDADA\n std::cerr << std::endl;\n std::cerr << \"\\tDedispersion: -dedispersion_file ...\" << std::endl;\n std::cerr << \"\\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...\";\n std::cerr << \"-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...\";\n std::cerr << \"-subbanding_dm_step ...\" << std::endl;\n#ifdef HAVE_HDF5\n std::cerr << \"\\tLOFAR: -lofar -header ... -data ... [-limit]\" << std::endl;\n std::cerr << \"\\t\\t -limit -batches ...\" << std::endl;\n#endif \/\/ HAVE_HDF5\n std::cerr << \"\\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...\";\n std::cerr << \"-channel_bandwidth ... -samples ... -sampling_time ...\" << std::endl;\n#ifdef HAVE_PSRDADA\n std::cerr << \"\\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ...\" << std::endl;\n#endif \/\/ HAVE_PSRDADA\n std::cerr << \"\\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...\";\n std::cerr << \"-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ...\" << std::endl;\n}\n<|endoftext|>"} {"text":"#include \"Convolution.hpp\"\n#include \"mlo_internal.hpp\"\n\nmlopenConvolutionDescriptor::mlopenConvolutionDescriptor() : _pad_h(0), _pad_w(0), _u(1), _v(1), _upscalex(0), _upscaley(0) {\n\tprintf(\"In convolution Ctor\\n\");\n\t_mode = mlopenConvolution;\n}\n\nmlopenStatus_t mlopenConvolutionDescriptor::GetForwardOutputDim(const mlopenTensorDescriptor_t inputTensorDesc,\n\t\t\tconst mlopenTensorDescriptor_t filterDesc,\n\t\t\tint *n,\n\t\t\tint *c,\n\t\t\tint *h, \n\t\t\tint *w) {\n\t\n\tprintf(\"To be implemented (GetForwardOutputDim)\\n\");\n\n\treturn mlopenStatusSuccess;\n}\n\nmlopenStatus_t mlopenConvolutionDescriptor::FindConvFwdAlgorithm(mlopenHandle_t handle,\n\t\tconst mlopenTensorDescriptor_t\txDesc,\n\t\tconst void\t\t\t\t\t\t*x,\n\t\tconst mlopenTensorDescriptor_t\twDesc,\n\t\tconst void\t\t\t\t\t\t*w,\n\t\tconst mlopenTensorDescriptor_t\tyDesc,\n\t\tconst void\t\t\t\t\t\t*y,\n\t\tconst int\t\t\t\t\t\trequestAlgoCount,\n\t\tint\t\t\t\t\t\t\t\t*returnedAlgoCount,\n\t\tmlopenConvAlgoPerf_t\t\t\t*perfResults,\n\t\tmlopenConvPreference_t\t\t\tpreference,\n\t\tvoid\t\t\t\t\t\t\t*workSpace,\n\t\tsize_t\t\t\t\t\t\t\tworkSpaceSize) {\n\t\n\tprintf(\"To be implemented (FindConvFwdAlgo) \\n\");\n\n#if 0\n\tif(handle == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(x == nullptr || w == nullptr || y == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(returnedAlgoCount == nullptr || perfResults == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(requestAlgoCount < 1) {\n\t\treturn mlopenStatusBadParm;\n\t}\n#endif \n\n\t\/\/ Generate kernels if OpenCL\n\t\/\/ Compile, cache kernels, etc.\n\t\/\/ Launch all kernels and store the perf, workspace limits, etc.\n\n\tmlo_construct_direct2D construct_params(1); \/\/ forward, no bias\n\t{\n\n\t\tconstruct_params.setTimerIter(100);\n\/\/ HOW TO DEFINE???\n\t\tconstruct_params.doSearch(false);\n\/\/\n\t\tconstruct_params.saveSearchRequest(true);\n\n\n\/\/ TO DO WHERE IS THE PATH ?\n\t\tstd::string kernel_path = \"..\/src\";\n\n\t\tconstruct_params.setKernelPath(kernel_path);\n\n\t\tstd::string generic_comp_otions = std::string(\" -I \") + kernel_path + \" \";\n\/\/\t\tif (debug)\n\t\t{\n\t\t\tgeneric_comp_otions += std::string(\" -cl-std=CL2.0 \");\n\n\t\t}\n\n\t\tconstruct_params.setGeneralCompOptions(generic_comp_otions);\n\n\t\tmlopenStream_t queue;\n\t\thandle->GetStream(&queue);\n\n\t\tconstruct_params.setStream(queue);\n\n\t\tint nOut;\n\t\tint cOut;\n\t\tint hOut;\n\t\tint wOut;\n\t\tint nOutStride;\n\t\tint cOutStride;\n\t\tint hOutStride;\n\t\tint wOutStride;\n\n\t\tyDesc->Get4Dims(&nOut, &cOut, &hOut, &wOut);\n\n\t\tyDesc->Get4Strides(&nOutStride,\n\t\t\t&cOutStride,\n\t\t\t&hOutStride,\n\t\t\t&wOutStride);\n\n\n\t\tconstruct_params.setOutputDescr(\n\t\t\t\"NCHW\",\n\t\t\t\"FP32\",\n\t\t\tnOut,\n\t\t\tcOut,\n\t\t\thOut,\n\t\t\twOut,\n\t\t\tnOutStride,\n\t\t\tcOutStride,\n\t\t\thOutStride,\n\t\t\twOutStride);\n\n\t\tint nIn;\n\t\tint cIn;\n\t\tint hIn;\n\t\tint wIn;\n\t\tint nInStride;\n\t\tint cInStride;\n\t\tint hInStride;\n\t\tint wInStride;\n\n\t\txDesc->Get4Dims(&nIn, &cIn, &hIn, &wIn);\n\n\t\tyDesc->Get4Strides(&nInStride,\n\t\t\t&cInStride,\n\t\t\t&hInStride,\n\t\t\t&wInStride);\n\n\t\tconstruct_params.setInputDescr(\n\t\t\t\"NCHW\",\n\t\t\t\"FP32\",\n\t\t\tnIn,\n\t\t\tcIn,\n\t\t\thIn,\n\t\t\twIn,\n\t\t\tnInStride,\n\t\t\tcInStride,\n\t\t\thInStride,\n\t\t\twInStride);\n\n\t\tint nWei;\n\t\tint cWei;\n\t\tint hWei;\n\t\tint wWei;\n\t\tint nWeiStride;\n\t\tint cWeiStride;\n\t\tint hWeiStride;\n\t\tint wWeiStride;\n\n\t\twDesc->Get4Dims(&nWei, &cWei, &hWei, &wWei);\n\n\t\twDesc->Get4Strides(&nWeiStride,\n\t\t\t&cWeiStride,\n\t\t\t&hWeiStride,\n\t\t\t&wWeiStride);\n\n\n\t\tconstruct_params.setWeightsDescr(\n\t\t\t\"NCHW\",\n\t\t\t\"FP32\",\n\t\t\tnWei,\n\t\t\tcWei,\n\t\t\thWei,\n\t\t\twWei,\n\t\t\tnWeiStride,\n\t\t\tcWeiStride,\n\t\t\thWeiStride,\n\t\t\twWeiStride\n\t\t\t);\n\n\t\tconstruct_params.setConvDescr(_pad_h, _pad_w, _u, _v, _upscalex, _upscaley);\n\n\n\t\tconstruct_params.mloConstructDirect2D();\n\n\t}\n\n\n\n\tstd::string program_name = std::string(\"..\/src\") + construct_params.getKernelFile(); \"..\/src\/Hello.cl\"; \/\/ CL kernel filename\n\tstd::string kernel_name = construct_params.getKernelFile(); \/\/ \"hello_world_kernel\"; \/\/ kernel name\n\tstd::string parms = construct_params.getCompilerOptions(); \/\/ kernel parameters\n\n\t\/\/ Get the queue associated with this handle\n\tmlopenStream_t queue;\n\thandle->GetStream(&queue);\n\n\t\/\/ Compile the kernel if not aleady compiled\n\tOCLKernel obj = KernelCache::get(queue, program_name, kernel_name);\n\tcl_int status;\n\n\tstd::string kernName;\n\tobj.GetKernelName(kernName);\n\n\tprintf(\"kname: %s\\n\", kernName.c_str());\n\n#if 0 \/\/ Test to see if we can launch the kernel and get the results back\n\tfloat *a = new float[1024];\n\tfloat *b = new float[1024];\n\tfloat *c = new float[1024];\n\n\tfor(int i = 0; i < 1024; i++) {\n\t\ta[i] = 1.0;\n\t\tb[i] = 7.0;\n\t\tc[i] = 0.0;\n\t}\n\tint sz = 1024;\n\n\tcl_context ctx;\n\tclGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);\n\n\tcl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status);\n\tif(status != CL_SUCCESS) {\n\t\tprintf(\"error %d\\n\", status);\n\t}\n\tcl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL);\n\tcl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL);\n\n\tstatus = clEnqueueWriteBuffer(queue, adev, CL_TRUE, 0, 4*sz, a, 0, NULL, NULL);\n\tstatus |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL);\n\tstatus |= clEnqueueWriteBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL);\n#endif \/\/ Test\n\n\t\/\/ Set kernel arguments\n\t\/\/ Use proper arguments\n\t\n\t\/\/obj.SetArgs(0, adev, bdev, cdev, sz);\n\n\tsize_t gd = 1024;\n\tsize_t ld = 256;\n\n\t\/\/ Run the kernel\n\tobj.run(queue, 1, 0, gd, ld);\n\n\tclFinish(queue);\n\n#if 0 \/\/ Read results back\n\tclEnqueueReadBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL);\n\n\tfloat sum = 0.0;\n\tfor(int i = 0; i < 1024; i++) {\n\t\tb[i] = 6;\n\t\tsum += c[i];\n\t}\n\n\tprintf(\"\\nsum %f\\n, \", sum);\n\tsum = 0.0;\n\tstatus |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL);\n\n\tgetchar();\n#endif \/\/Results\n\n\treturn mlopenStatusSuccess;\n\n}\n\nmlopenStatus_t mlopenConvolutionDescriptor::ConvolutionForward(mlopenHandle_t handle,\n\t\tconst void\t\t\t\t\t\t\t*alpha,\n\t\tconst mlopenTensorDescriptor_t\t\txDesc,\n\t\tconst void\t\t\t\t\t\t\t*x,\n\t\tconst mlopenTensorDescriptor_t\t\twDesc,\n\t\tconst void\t\t\t\t\t\t\t*w,\n\t\tmlopenConvFwdAlgorithm_t\t\t\talgo,\n\t\tconst void\t\t\t\t\t\t\t*beta,\n\t\tconst mlopenTensorDescriptor_t\t\t yDesc,\n\t\tvoid\t\t\t\t\t\t\t\t*y) {\n\n\tprintf(\"To be implemented (ConvolutionForward) \\n\");\n\n\tif(handle == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(x == nullptr || w == nullptr || y == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_CheckTensorDims(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDims(wDesc) != mlopenStatusSuccess) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_CheckTensorDataTypes(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDataTypes(wDesc) != mlopenStatusSuccess) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_dimA[0] != wDesc->_dimA[0]) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_dims < 3) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\n\tstd::string program_name; \/\/ CL kernel filename\n\tstd::string kernel_name; \/\/ kernel name\n\tstd::string parms; \/\/ kernel parameters\n\n\tmlopenStream_t queue;\n\thandle->GetStream(&queue);\n\n#if MLOpen_BACKEND_OPENCL\n\/\/\tOCLKernel kernel = KernelCache::get(queue, program_name, kernel_name);\n#endif\n\n\treturn mlopenStatusSuccess;\n\n}\n\ninor Conv.cpp fix#include \"Convolution.hpp\"\n#include \"mlo_internal.hpp\"\n\nmlopenConvolutionDescriptor::mlopenConvolutionDescriptor() : _pad_h(0), _pad_w(0), _u(1), _v(1), _upscalex(0), _upscaley(0) {\n\tprintf(\"In convolution Ctor\\n\");\n\t_mode = mlopenConvolution;\n}\n\nmlopenStatus_t mlopenConvolutionDescriptor::GetForwardOutputDim(const mlopenTensorDescriptor_t inputTensorDesc,\n\t\t\tconst mlopenTensorDescriptor_t filterDesc,\n\t\t\tint *n,\n\t\t\tint *c,\n\t\t\tint *h, \n\t\t\tint *w) {\n\t\n\tprintf(\"To be implemented (GetForwardOutputDim)\\n\");\n\n\treturn mlopenStatusSuccess;\n}\n\nmlopenStatus_t mlopenConvolutionDescriptor::FindConvFwdAlgorithm(mlopenHandle_t handle,\n\t\tconst mlopenTensorDescriptor_t\txDesc,\n\t\tconst void\t\t\t\t\t\t*x,\n\t\tconst mlopenTensorDescriptor_t\twDesc,\n\t\tconst void\t\t\t\t\t\t*w,\n\t\tconst mlopenTensorDescriptor_t\tyDesc,\n\t\tconst void\t\t\t\t\t\t*y,\n\t\tconst int\t\t\t\t\t\trequestAlgoCount,\n\t\tint\t\t\t\t\t\t\t\t*returnedAlgoCount,\n\t\tmlopenConvAlgoPerf_t\t\t\t*perfResults,\n\t\tmlopenConvPreference_t\t\t\tpreference,\n\t\tvoid\t\t\t\t\t\t\t*workSpace,\n\t\tsize_t\t\t\t\t\t\t\tworkSpaceSize) {\n\t\n\tprintf(\"To be implemented (FindConvFwdAlgo) \\n\");\n\n#if 0\n\tif(handle == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(x == nullptr || w == nullptr || y == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(returnedAlgoCount == nullptr || perfResults == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(requestAlgoCount < 1) {\n\t\treturn mlopenStatusBadParm;\n\t}\n#endif \n\n\t\/\/ Generate kernels if OpenCL\n\t\/\/ Compile, cache kernels, etc.\n\t\/\/ Launch all kernels and store the perf, workspace limits, etc.\n\n\tmlo_construct_direct2D construct_params(1); \/\/ forward, no bias\n\t{\n\n\t\tconstruct_params.setTimerIter(100);\n\/\/ HOW TO DEFINE???\n\t\tconstruct_params.doSearch(false);\n\/\/\n\t\tconstruct_params.saveSearchRequest(true);\n\n\n\/\/ TO DO WHERE IS THE PATH ?\n\t\tstd::string kernel_path = \"..\/src\";\n\n\t\tconstruct_params.setKernelPath(kernel_path);\n\n\t\tstd::string generic_comp_otions = std::string(\" -I \") + kernel_path + \" \";\n\/\/\t\tif (debug)\n\t\t{\n\t\t\tgeneric_comp_otions += std::string(\" -cl-std=CL2.0 \");\n\n\t\t}\n\n\t\tconstruct_params.setGeneralCompOptions(generic_comp_otions);\n\n\t\tmlopenStream_t queue;\n\t\thandle->GetStream(&queue);\n\n\t\tconstruct_params.setStream(queue);\n\n\t\tint nOut;\n\t\tint cOut;\n\t\tint hOut;\n\t\tint wOut;\n\t\tint nOutStride;\n\t\tint cOutStride;\n\t\tint hOutStride;\n\t\tint wOutStride;\n\n\t\tyDesc->Get4Dims(&nOut, &cOut, &hOut, &wOut);\n\n\t\tyDesc->Get4Strides(&nOutStride,\n\t\t\t&cOutStride,\n\t\t\t&hOutStride,\n\t\t\t&wOutStride);\n\n\n\t\tconstruct_params.setOutputDescr(\n\t\t\t\"NCHW\",\n\t\t\t\"FP32\",\n\t\t\tnOut,\n\t\t\tcOut,\n\t\t\thOut,\n\t\t\twOut,\n\t\t\tnOutStride,\n\t\t\tcOutStride,\n\t\t\thOutStride,\n\t\t\twOutStride);\n\n\t\tint nIn;\n\t\tint cIn;\n\t\tint hIn;\n\t\tint wIn;\n\t\tint nInStride;\n\t\tint cInStride;\n\t\tint hInStride;\n\t\tint wInStride;\n\n\t\txDesc->Get4Dims(&nIn, &cIn, &hIn, &wIn);\n\n\t\tyDesc->Get4Strides(&nInStride,\n\t\t\t&cInStride,\n\t\t\t&hInStride,\n\t\t\t&wInStride);\n\n\t\tconstruct_params.setInputDescr(\n\t\t\t\"NCHW\",\n\t\t\t\"FP32\",\n\t\t\tnIn,\n\t\t\tcIn,\n\t\t\thIn,\n\t\t\twIn,\n\t\t\tnInStride,\n\t\t\tcInStride,\n\t\t\thInStride,\n\t\t\twInStride);\n\n\t\tint nWei;\n\t\tint cWei;\n\t\tint hWei;\n\t\tint wWei;\n\t\tint nWeiStride;\n\t\tint cWeiStride;\n\t\tint hWeiStride;\n\t\tint wWeiStride;\n\n\t\twDesc->Get4Dims(&nWei, &cWei, &hWei, &wWei);\n\n\t\twDesc->Get4Strides(&nWeiStride,\n\t\t\t&cWeiStride,\n\t\t\t&hWeiStride,\n\t\t\t&wWeiStride);\n\n\n\t\tconstruct_params.setWeightsDescr(\n\t\t\t\"NCHW\",\n\t\t\t\"FP32\",\n\t\t\tnWei,\n\t\t\tcWei,\n\t\t\thWei,\n\t\t\twWei,\n\t\t\tnWeiStride,\n\t\t\tcWeiStride,\n\t\t\thWeiStride,\n\t\t\twWeiStride\n\t\t\t);\n\n\t\tconstruct_params.setConvDescr(_pad_h, _pad_w, _u, _v, _upscalex, _upscaley);\n\n\n\t\tconstruct_params.mloConstructDirect2D();\n\n\t}\n\n\n\n\tstd::string program_name = std::string(\"..\/src\/\") + construct_params.getKernelFile(); \/\/\"..\/src\/Hello.cl\"; \/\/ CL kernel filename\n\tstd::string kernel_name = construct_params.getKernelFile(); \/\/ \"hello_world_kernel\"; \/\/ kernel name\n\tstd::string parms = construct_params.getCompilerOptions(); \/\/ kernel parameters\n\n\t\/\/ Get the queue associated with this handle\n\tmlopenStream_t queue;\n\thandle->GetStream(&queue);\n\n\t\/\/ Compile the kernel if not aleady compiled\n\tOCLKernel obj = KernelCache::get(queue, program_name, kernel_name);\n\tcl_int status;\n\n\tstd::string kernName;\n\tobj.GetKernelName(kernName);\n\n\tprintf(\"kname: %s\\n\", kernName.c_str());\n\n#if 0 \/\/ Test to see if we can launch the kernel and get the results back\n\tfloat *a = new float[1024];\n\tfloat *b = new float[1024];\n\tfloat *c = new float[1024];\n\n\tfor(int i = 0; i < 1024; i++) {\n\t\ta[i] = 1.0;\n\t\tb[i] = 7.0;\n\t\tc[i] = 0.0;\n\t}\n\tint sz = 1024;\n\n\tcl_context ctx;\n\tclGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL);\n\n\tcl_mem adev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, &status);\n\tif(status != CL_SUCCESS) {\n\t\tprintf(\"error %d\\n\", status);\n\t}\n\tcl_mem bdev = clCreateBuffer(ctx, CL_MEM_READ_ONLY, 4*sz,NULL, NULL);\n\tcl_mem cdev = clCreateBuffer(ctx, CL_MEM_READ_WRITE, 4*sz,NULL, NULL);\n\n\tstatus = clEnqueueWriteBuffer(queue, adev, CL_TRUE, 0, 4*sz, a, 0, NULL, NULL);\n\tstatus |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL);\n\tstatus |= clEnqueueWriteBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL);\n#endif \/\/ Test\n\n\t\/\/ Set kernel arguments\n\t\/\/ Use proper arguments\n\t\n\t\/\/obj.SetArgs(0, adev, bdev, cdev, sz);\n\n\tsize_t gd = 1024;\n\tsize_t ld = 256;\n\n\t\/\/ Run the kernel\n\tobj.run(queue, 1, 0, gd, ld);\n\n\tclFinish(queue);\n\n#if 0 \/\/ Read results back\n\tclEnqueueReadBuffer(queue, cdev, CL_TRUE, 0, 4*sz, c, 0, NULL, NULL);\n\n\tfloat sum = 0.0;\n\tfor(int i = 0; i < 1024; i++) {\n\t\tb[i] = 6;\n\t\tsum += c[i];\n\t}\n\n\tprintf(\"\\nsum %f\\n, \", sum);\n\tsum = 0.0;\n\tstatus |= clEnqueueWriteBuffer(queue, bdev, CL_TRUE, 0, 4*sz, b, 0, NULL, NULL);\n\n\tgetchar();\n#endif \/\/Results\n\n\treturn mlopenStatusSuccess;\n\n}\n\nmlopenStatus_t mlopenConvolutionDescriptor::ConvolutionForward(mlopenHandle_t handle,\n\t\tconst void\t\t\t\t\t\t\t*alpha,\n\t\tconst mlopenTensorDescriptor_t\t\txDesc,\n\t\tconst void\t\t\t\t\t\t\t*x,\n\t\tconst mlopenTensorDescriptor_t\t\twDesc,\n\t\tconst void\t\t\t\t\t\t\t*w,\n\t\tmlopenConvFwdAlgorithm_t\t\t\talgo,\n\t\tconst void\t\t\t\t\t\t\t*beta,\n\t\tconst mlopenTensorDescriptor_t\t\t yDesc,\n\t\tvoid\t\t\t\t\t\t\t\t*y) {\n\n\tprintf(\"To be implemented (ConvolutionForward) \\n\");\n\n\tif(handle == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc == nullptr || wDesc == nullptr || yDesc == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(x == nullptr || w == nullptr || y == nullptr) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_CheckTensorDims(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDims(wDesc) != mlopenStatusSuccess) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_CheckTensorDataTypes(yDesc) != mlopenStatusSuccess || xDesc->_CheckTensorDataTypes(wDesc) != mlopenStatusSuccess) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_dimA[0] != wDesc->_dimA[0]) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\tif(xDesc->_dims < 3) {\n\t\treturn mlopenStatusBadParm;\n\t}\n\n\tstd::string program_name; \/\/ CL kernel filename\n\tstd::string kernel_name; \/\/ kernel name\n\tstd::string parms; \/\/ kernel parameters\n\n\tmlopenStream_t queue;\n\thandle->GetStream(&queue);\n\n#if MLOpen_BACKEND_OPENCL\n\/\/\tOCLKernel kernel = KernelCache::get(queue, program_name, kernel_name);\n#endif\n\n\treturn mlopenStatusSuccess;\n\n}\n\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/alloc.h\"\n#include \"grpc\/support\/log.h\"\n#include \"grpc\/support\/time.h\"\n\n\/\/ TODO(murgatroid99): Remove this when the endpoint API becomes public\nextern \"C\" {\n#include \"src\/core\/lib\/iomgr\/pollset_uv.h\"\n}\n\n#include \"call.h\"\n#include \"call_credentials.h\"\n#include \"channel.h\"\n#include \"channel_credentials.h\"\n#include \"completion_queue.h\"\n#include \"server.h\"\n#include \"server_credentials.h\"\n#include \"slice.h\"\n#include \"timeval.h\"\n\nusing grpc::node::CreateSliceFromString;\n\nusing v8::FunctionTemplate;\nusing v8::Local;\nusing v8::Value;\nusing v8::Number;\nusing v8::Object;\nusing v8::Uint32;\nusing v8::String;\n\ntypedef struct log_args {\n gpr_log_func_args core_args;\n gpr_timespec timestamp;\n} log_args;\n\ntypedef struct logger_state {\n Nan::Callback *callback;\n std::queue *pending_args;\n uv_mutex_t mutex;\n uv_async_t async;\n \/\/ Indicates that a logger has been set\n bool logger_set;\n} logger_state;\n\nlogger_state grpc_logger_state;\n\nstatic char *pem_root_certs = NULL;\n\nvoid InitOpTypeConstants(Local exports) {\n Nan::HandleScope scope;\n Local op_type = Nan::New();\n Nan::Set(exports, Nan::New(\"opType\").ToLocalChecked(), op_type);\n Local SEND_INITIAL_METADATA(\n Nan::New(GRPC_OP_SEND_INITIAL_METADATA));\n Nan::Set(op_type, Nan::New(\"SEND_INITIAL_METADATA\").ToLocalChecked(),\n SEND_INITIAL_METADATA);\n Local SEND_MESSAGE(Nan::New(GRPC_OP_SEND_MESSAGE));\n Nan::Set(op_type, Nan::New(\"SEND_MESSAGE\").ToLocalChecked(), SEND_MESSAGE);\n Local SEND_CLOSE_FROM_CLIENT(\n Nan::New(GRPC_OP_SEND_CLOSE_FROM_CLIENT));\n Nan::Set(op_type, Nan::New(\"SEND_CLOSE_FROM_CLIENT\").ToLocalChecked(),\n SEND_CLOSE_FROM_CLIENT);\n Local SEND_STATUS_FROM_SERVER(\n Nan::New(GRPC_OP_SEND_STATUS_FROM_SERVER));\n Nan::Set(op_type, Nan::New(\"SEND_STATUS_FROM_SERVER\").ToLocalChecked(),\n SEND_STATUS_FROM_SERVER);\n Local RECV_INITIAL_METADATA(\n Nan::New(GRPC_OP_RECV_INITIAL_METADATA));\n Nan::Set(op_type, Nan::New(\"RECV_INITIAL_METADATA\").ToLocalChecked(),\n RECV_INITIAL_METADATA);\n Local RECV_MESSAGE(Nan::New(GRPC_OP_RECV_MESSAGE));\n Nan::Set(op_type, Nan::New(\"RECV_MESSAGE\").ToLocalChecked(), RECV_MESSAGE);\n Local RECV_STATUS_ON_CLIENT(\n Nan::New(GRPC_OP_RECV_STATUS_ON_CLIENT));\n Nan::Set(op_type, Nan::New(\"RECV_STATUS_ON_CLIENT\").ToLocalChecked(),\n RECV_STATUS_ON_CLIENT);\n Local RECV_CLOSE_ON_SERVER(\n Nan::New(GRPC_OP_RECV_CLOSE_ON_SERVER));\n Nan::Set(op_type, Nan::New(\"RECV_CLOSE_ON_SERVER\").ToLocalChecked(),\n RECV_CLOSE_ON_SERVER);\n}\n\nvoid InitConnectivityStateConstants(Local exports) {\n Nan::HandleScope scope;\n Local channel_state = Nan::New();\n Nan::Set(exports, Nan::New(\"connectivityState\").ToLocalChecked(),\n channel_state);\n Local IDLE(Nan::New(GRPC_CHANNEL_IDLE));\n Nan::Set(channel_state, Nan::New(\"IDLE\").ToLocalChecked(), IDLE);\n Local CONNECTING(Nan::New(GRPC_CHANNEL_CONNECTING));\n Nan::Set(channel_state, Nan::New(\"CONNECTING\").ToLocalChecked(), CONNECTING);\n Local READY(Nan::New(GRPC_CHANNEL_READY));\n Nan::Set(channel_state, Nan::New(\"READY\").ToLocalChecked(), READY);\n Local TRANSIENT_FAILURE(\n Nan::New(GRPC_CHANNEL_TRANSIENT_FAILURE));\n Nan::Set(channel_state, Nan::New(\"TRANSIENT_FAILURE\").ToLocalChecked(),\n TRANSIENT_FAILURE);\n Local FATAL_FAILURE(Nan::New(GRPC_CHANNEL_SHUTDOWN));\n Nan::Set(channel_state, Nan::New(\"FATAL_FAILURE\").ToLocalChecked(),\n FATAL_FAILURE);\n}\n\nNAN_METHOD(MetadataKeyIsLegal) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\"headerKeyIsLegal's argument must be a string\");\n }\n Local key = Nan::To(info[0]).ToLocalChecked();\n grpc_slice slice = CreateSliceFromString(key);\n info.GetReturnValue().Set(static_cast(grpc_header_key_is_legal(slice)));\n grpc_slice_unref(slice);\n}\n\nNAN_METHOD(MetadataNonbinValueIsLegal) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\n \"metadataNonbinValueIsLegal's argument must be a string\");\n }\n Local value = Nan::To(info[0]).ToLocalChecked();\n grpc_slice slice = CreateSliceFromString(value);\n info.GetReturnValue().Set(\n static_cast(grpc_header_nonbin_value_is_legal(slice)));\n grpc_slice_unref(slice);\n}\n\nNAN_METHOD(MetadataKeyIsBinary) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\n \"metadataKeyIsLegal's argument must be a string\");\n }\n Local key = Nan::To(info[0]).ToLocalChecked();\n grpc_slice slice = CreateSliceFromString(key);\n info.GetReturnValue().Set(static_cast(grpc_is_binary_header(slice)));\n grpc_slice_unref(slice);\n}\n\nstatic grpc_ssl_roots_override_result get_ssl_roots_override(\n char **pem_root_certs_ptr) {\n *pem_root_certs_ptr = pem_root_certs;\n if (pem_root_certs == NULL) {\n return GRPC_SSL_ROOTS_OVERRIDE_FAIL;\n } else {\n return GRPC_SSL_ROOTS_OVERRIDE_OK;\n }\n}\n\n\/* This should only be called once, and only before creating any\n *ServerCredentials *\/\nNAN_METHOD(SetDefaultRootsPem) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\n \"setDefaultRootsPem's argument must be a string\");\n }\n Nan::Utf8String utf8_roots(info[0]);\n size_t length = static_cast(utf8_roots.length());\n if (length > 0) {\n const char *data = *utf8_roots;\n pem_root_certs = (char *)gpr_malloc((length + 1) * sizeof(char));\n memcpy(pem_root_certs, data, length + 1);\n }\n}\n\nNAUV_WORK_CB(LogMessagesCallback) {\n Nan::HandleScope scope;\n std::queue args;\n uv_mutex_lock(&grpc_logger_state.mutex);\n grpc_logger_state.pending_args->swap(args);\n uv_mutex_unlock(&grpc_logger_state.mutex);\n \/* Call the callback with each log message *\/\n while (!args.empty()) {\n log_args *arg = args.front();\n args.pop();\n Local file = Nan::New(arg->core_args.file).ToLocalChecked();\n Local line = Nan::New(arg->core_args.line);\n Local severity =\n Nan::New(gpr_log_severity_string(arg->core_args.severity))\n .ToLocalChecked();\n Local message = Nan::New(arg->core_args.message).ToLocalChecked();\n Local timestamp =\n Nan::New(grpc::node::TimespecToMilliseconds(arg->timestamp))\n .ToLocalChecked();\n const int argc = 5;\n Local argv[argc] = {file, line, severity, message, timestamp};\n grpc_logger_state.callback->Call(argc, argv);\n delete[] arg->core_args.message;\n delete arg;\n }\n}\n\nvoid node_log_func(gpr_log_func_args *args) {\n \/\/ TODO(mlumish): Use the core's log formatter when it becomes available\n log_args *args_copy = new log_args;\n size_t message_len = strlen(args->message) + 1;\n char *message = new char[message_len];\n memcpy(message, args->message, message_len);\n memcpy(&args_copy->core_args, args, sizeof(gpr_log_func_args));\n args_copy->core_args.message = message;\n args_copy->timestamp = gpr_now(GPR_CLOCK_REALTIME);\n\n uv_mutex_lock(&grpc_logger_state.mutex);\n grpc_logger_state.pending_args->push(args_copy);\n uv_mutex_unlock(&grpc_logger_state.mutex);\n\n uv_async_send(&grpc_logger_state.async);\n}\n\nvoid init_logger() {\n memset(&grpc_logger_state, 0, sizeof(logger_state));\n grpc_logger_state.pending_args = new std::queue();\n uv_mutex_init(&grpc_logger_state.mutex);\n uv_async_init(uv_default_loop(), &grpc_logger_state.async,\n LogMessagesCallback);\n uv_unref((uv_handle_t *)&grpc_logger_state.async);\n grpc_logger_state.logger_set = false;\n\n gpr_log_verbosity_init();\n}\n\n\/* This registers a JavaScript logger for messages from the gRPC core. Because\n that handler has to be run in the context of the JavaScript event loop, it\n will be run asynchronously. To minimize the problems that could cause for\n debugging, we leave core to do its default synchronous logging until a\n JavaScript logger is set *\/\nNAN_METHOD(SetDefaultLoggerCallback) {\n if (!info[0]->IsFunction()) {\n return Nan::ThrowTypeError(\n \"setDefaultLoggerCallback's argument must be a function\");\n }\n if (!grpc_logger_state.logger_set) {\n gpr_set_log_function(node_log_func);\n grpc_logger_state.logger_set = true;\n }\n grpc_logger_state.callback = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SetLogVerbosity) {\n if (!info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"setLogVerbosity's argument must be a number\");\n }\n gpr_log_severity severity =\n static_cast(Nan::To(info[0]).FromJust());\n gpr_set_log_verbosity(severity);\n}\n\nNAN_METHOD(ForcePoll) {\n grpc::node::CompletionQueueForcePoll();\n}\n\nvoid init(Local exports) {\n Nan::HandleScope scope;\n grpc_init();\n grpc_set_ssl_roots_override_callback(get_ssl_roots_override);\n init_logger();\n\n InitOpTypeConstants(exports);\n InitConnectivityStateConstants(exports);\n\n grpc_pollset_work_run_loop = 0;\n\n grpc::node::Call::Init(exports);\n grpc::node::CallCredentials::Init(exports);\n grpc::node::Channel::Init(exports);\n grpc::node::ChannelCredentials::Init(exports);\n grpc::node::Server::Init(exports);\n grpc::node::ServerCredentials::Init(exports);\n\n grpc::node::CompletionQueueInit(exports);\n\n \/\/ Attach a few utility functions directly to the module\n Nan::Set(exports, Nan::New(\"metadataKeyIsLegal\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(MetadataKeyIsLegal))\n .ToLocalChecked());\n Nan::Set(\n exports, Nan::New(\"metadataNonbinValueIsLegal\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(MetadataNonbinValueIsLegal))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"metadataKeyIsBinary\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(MetadataKeyIsBinary))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"setDefaultRootsPem\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(SetDefaultRootsPem))\n .ToLocalChecked());\n Nan::Set(\n exports, Nan::New(\"setDefaultLoggerCallback\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(SetDefaultLoggerCallback))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"setLogVerbosity\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(SetLogVerbosity))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"forcePoll\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(ForcePoll))\n .ToLocalChecked());\n}\n\nNODE_MODULE(grpc_node, init)\nUpdate a core header inclusion to stop using extern C\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/alloc.h\"\n#include \"grpc\/support\/log.h\"\n#include \"grpc\/support\/time.h\"\n\n\/\/ TODO(murgatroid99): Remove this when the endpoint API becomes public\n#include \"src\/core\/lib\/iomgr\/pollset_uv.h\"\n\n#include \"call.h\"\n#include \"call_credentials.h\"\n#include \"channel.h\"\n#include \"channel_credentials.h\"\n#include \"completion_queue.h\"\n#include \"server.h\"\n#include \"server_credentials.h\"\n#include \"slice.h\"\n#include \"timeval.h\"\n\nusing grpc::node::CreateSliceFromString;\n\nusing v8::FunctionTemplate;\nusing v8::Local;\nusing v8::Value;\nusing v8::Number;\nusing v8::Object;\nusing v8::Uint32;\nusing v8::String;\n\ntypedef struct log_args {\n gpr_log_func_args core_args;\n gpr_timespec timestamp;\n} log_args;\n\ntypedef struct logger_state {\n Nan::Callback *callback;\n std::queue *pending_args;\n uv_mutex_t mutex;\n uv_async_t async;\n \/\/ Indicates that a logger has been set\n bool logger_set;\n} logger_state;\n\nlogger_state grpc_logger_state;\n\nstatic char *pem_root_certs = NULL;\n\nvoid InitOpTypeConstants(Local exports) {\n Nan::HandleScope scope;\n Local op_type = Nan::New();\n Nan::Set(exports, Nan::New(\"opType\").ToLocalChecked(), op_type);\n Local SEND_INITIAL_METADATA(\n Nan::New(GRPC_OP_SEND_INITIAL_METADATA));\n Nan::Set(op_type, Nan::New(\"SEND_INITIAL_METADATA\").ToLocalChecked(),\n SEND_INITIAL_METADATA);\n Local SEND_MESSAGE(Nan::New(GRPC_OP_SEND_MESSAGE));\n Nan::Set(op_type, Nan::New(\"SEND_MESSAGE\").ToLocalChecked(), SEND_MESSAGE);\n Local SEND_CLOSE_FROM_CLIENT(\n Nan::New(GRPC_OP_SEND_CLOSE_FROM_CLIENT));\n Nan::Set(op_type, Nan::New(\"SEND_CLOSE_FROM_CLIENT\").ToLocalChecked(),\n SEND_CLOSE_FROM_CLIENT);\n Local SEND_STATUS_FROM_SERVER(\n Nan::New(GRPC_OP_SEND_STATUS_FROM_SERVER));\n Nan::Set(op_type, Nan::New(\"SEND_STATUS_FROM_SERVER\").ToLocalChecked(),\n SEND_STATUS_FROM_SERVER);\n Local RECV_INITIAL_METADATA(\n Nan::New(GRPC_OP_RECV_INITIAL_METADATA));\n Nan::Set(op_type, Nan::New(\"RECV_INITIAL_METADATA\").ToLocalChecked(),\n RECV_INITIAL_METADATA);\n Local RECV_MESSAGE(Nan::New(GRPC_OP_RECV_MESSAGE));\n Nan::Set(op_type, Nan::New(\"RECV_MESSAGE\").ToLocalChecked(), RECV_MESSAGE);\n Local RECV_STATUS_ON_CLIENT(\n Nan::New(GRPC_OP_RECV_STATUS_ON_CLIENT));\n Nan::Set(op_type, Nan::New(\"RECV_STATUS_ON_CLIENT\").ToLocalChecked(),\n RECV_STATUS_ON_CLIENT);\n Local RECV_CLOSE_ON_SERVER(\n Nan::New(GRPC_OP_RECV_CLOSE_ON_SERVER));\n Nan::Set(op_type, Nan::New(\"RECV_CLOSE_ON_SERVER\").ToLocalChecked(),\n RECV_CLOSE_ON_SERVER);\n}\n\nvoid InitConnectivityStateConstants(Local exports) {\n Nan::HandleScope scope;\n Local channel_state = Nan::New();\n Nan::Set(exports, Nan::New(\"connectivityState\").ToLocalChecked(),\n channel_state);\n Local IDLE(Nan::New(GRPC_CHANNEL_IDLE));\n Nan::Set(channel_state, Nan::New(\"IDLE\").ToLocalChecked(), IDLE);\n Local CONNECTING(Nan::New(GRPC_CHANNEL_CONNECTING));\n Nan::Set(channel_state, Nan::New(\"CONNECTING\").ToLocalChecked(), CONNECTING);\n Local READY(Nan::New(GRPC_CHANNEL_READY));\n Nan::Set(channel_state, Nan::New(\"READY\").ToLocalChecked(), READY);\n Local TRANSIENT_FAILURE(\n Nan::New(GRPC_CHANNEL_TRANSIENT_FAILURE));\n Nan::Set(channel_state, Nan::New(\"TRANSIENT_FAILURE\").ToLocalChecked(),\n TRANSIENT_FAILURE);\n Local FATAL_FAILURE(Nan::New(GRPC_CHANNEL_SHUTDOWN));\n Nan::Set(channel_state, Nan::New(\"FATAL_FAILURE\").ToLocalChecked(),\n FATAL_FAILURE);\n}\n\nNAN_METHOD(MetadataKeyIsLegal) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\"headerKeyIsLegal's argument must be a string\");\n }\n Local key = Nan::To(info[0]).ToLocalChecked();\n grpc_slice slice = CreateSliceFromString(key);\n info.GetReturnValue().Set(static_cast(grpc_header_key_is_legal(slice)));\n grpc_slice_unref(slice);\n}\n\nNAN_METHOD(MetadataNonbinValueIsLegal) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\n \"metadataNonbinValueIsLegal's argument must be a string\");\n }\n Local value = Nan::To(info[0]).ToLocalChecked();\n grpc_slice slice = CreateSliceFromString(value);\n info.GetReturnValue().Set(\n static_cast(grpc_header_nonbin_value_is_legal(slice)));\n grpc_slice_unref(slice);\n}\n\nNAN_METHOD(MetadataKeyIsBinary) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\n \"metadataKeyIsLegal's argument must be a string\");\n }\n Local key = Nan::To(info[0]).ToLocalChecked();\n grpc_slice slice = CreateSliceFromString(key);\n info.GetReturnValue().Set(static_cast(grpc_is_binary_header(slice)));\n grpc_slice_unref(slice);\n}\n\nstatic grpc_ssl_roots_override_result get_ssl_roots_override(\n char **pem_root_certs_ptr) {\n *pem_root_certs_ptr = pem_root_certs;\n if (pem_root_certs == NULL) {\n return GRPC_SSL_ROOTS_OVERRIDE_FAIL;\n } else {\n return GRPC_SSL_ROOTS_OVERRIDE_OK;\n }\n}\n\n\/* This should only be called once, and only before creating any\n *ServerCredentials *\/\nNAN_METHOD(SetDefaultRootsPem) {\n if (!info[0]->IsString()) {\n return Nan::ThrowTypeError(\n \"setDefaultRootsPem's argument must be a string\");\n }\n Nan::Utf8String utf8_roots(info[0]);\n size_t length = static_cast(utf8_roots.length());\n if (length > 0) {\n const char *data = *utf8_roots;\n pem_root_certs = (char *)gpr_malloc((length + 1) * sizeof(char));\n memcpy(pem_root_certs, data, length + 1);\n }\n}\n\nNAUV_WORK_CB(LogMessagesCallback) {\n Nan::HandleScope scope;\n std::queue args;\n uv_mutex_lock(&grpc_logger_state.mutex);\n grpc_logger_state.pending_args->swap(args);\n uv_mutex_unlock(&grpc_logger_state.mutex);\n \/* Call the callback with each log message *\/\n while (!args.empty()) {\n log_args *arg = args.front();\n args.pop();\n Local file = Nan::New(arg->core_args.file).ToLocalChecked();\n Local line = Nan::New(arg->core_args.line);\n Local severity =\n Nan::New(gpr_log_severity_string(arg->core_args.severity))\n .ToLocalChecked();\n Local message = Nan::New(arg->core_args.message).ToLocalChecked();\n Local timestamp =\n Nan::New(grpc::node::TimespecToMilliseconds(arg->timestamp))\n .ToLocalChecked();\n const int argc = 5;\n Local argv[argc] = {file, line, severity, message, timestamp};\n grpc_logger_state.callback->Call(argc, argv);\n delete[] arg->core_args.message;\n delete arg;\n }\n}\n\nvoid node_log_func(gpr_log_func_args *args) {\n \/\/ TODO(mlumish): Use the core's log formatter when it becomes available\n log_args *args_copy = new log_args;\n size_t message_len = strlen(args->message) + 1;\n char *message = new char[message_len];\n memcpy(message, args->message, message_len);\n memcpy(&args_copy->core_args, args, sizeof(gpr_log_func_args));\n args_copy->core_args.message = message;\n args_copy->timestamp = gpr_now(GPR_CLOCK_REALTIME);\n\n uv_mutex_lock(&grpc_logger_state.mutex);\n grpc_logger_state.pending_args->push(args_copy);\n uv_mutex_unlock(&grpc_logger_state.mutex);\n\n uv_async_send(&grpc_logger_state.async);\n}\n\nvoid init_logger() {\n memset(&grpc_logger_state, 0, sizeof(logger_state));\n grpc_logger_state.pending_args = new std::queue();\n uv_mutex_init(&grpc_logger_state.mutex);\n uv_async_init(uv_default_loop(), &grpc_logger_state.async,\n LogMessagesCallback);\n uv_unref((uv_handle_t *)&grpc_logger_state.async);\n grpc_logger_state.logger_set = false;\n\n gpr_log_verbosity_init();\n}\n\n\/* This registers a JavaScript logger for messages from the gRPC core. Because\n that handler has to be run in the context of the JavaScript event loop, it\n will be run asynchronously. To minimize the problems that could cause for\n debugging, we leave core to do its default synchronous logging until a\n JavaScript logger is set *\/\nNAN_METHOD(SetDefaultLoggerCallback) {\n if (!info[0]->IsFunction()) {\n return Nan::ThrowTypeError(\n \"setDefaultLoggerCallback's argument must be a function\");\n }\n if (!grpc_logger_state.logger_set) {\n gpr_set_log_function(node_log_func);\n grpc_logger_state.logger_set = true;\n }\n grpc_logger_state.callback = new Nan::Callback(info[0].As());\n}\n\nNAN_METHOD(SetLogVerbosity) {\n if (!info[0]->IsUint32()) {\n return Nan::ThrowTypeError(\"setLogVerbosity's argument must be a number\");\n }\n gpr_log_severity severity =\n static_cast(Nan::To(info[0]).FromJust());\n gpr_set_log_verbosity(severity);\n}\n\nNAN_METHOD(ForcePoll) {\n grpc::node::CompletionQueueForcePoll();\n}\n\nvoid init(Local exports) {\n Nan::HandleScope scope;\n grpc_init();\n grpc_set_ssl_roots_override_callback(get_ssl_roots_override);\n init_logger();\n\n InitOpTypeConstants(exports);\n InitConnectivityStateConstants(exports);\n\n grpc_pollset_work_run_loop = 0;\n\n grpc::node::Call::Init(exports);\n grpc::node::CallCredentials::Init(exports);\n grpc::node::Channel::Init(exports);\n grpc::node::ChannelCredentials::Init(exports);\n grpc::node::Server::Init(exports);\n grpc::node::ServerCredentials::Init(exports);\n\n grpc::node::CompletionQueueInit(exports);\n\n \/\/ Attach a few utility functions directly to the module\n Nan::Set(exports, Nan::New(\"metadataKeyIsLegal\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(MetadataKeyIsLegal))\n .ToLocalChecked());\n Nan::Set(\n exports, Nan::New(\"metadataNonbinValueIsLegal\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(MetadataNonbinValueIsLegal))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"metadataKeyIsBinary\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(MetadataKeyIsBinary))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"setDefaultRootsPem\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(SetDefaultRootsPem))\n .ToLocalChecked());\n Nan::Set(\n exports, Nan::New(\"setDefaultLoggerCallback\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(SetDefaultLoggerCallback))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"setLogVerbosity\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(SetLogVerbosity))\n .ToLocalChecked());\n Nan::Set(exports, Nan::New(\"forcePoll\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(ForcePoll))\n .ToLocalChecked());\n}\n\nNODE_MODULE(grpc_node, init)\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \n\n#include \"ProducerSideServiceImpl.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"grpcpp\/grpcpp.h\"\n\nnamespace orbit_service {\n\nnamespace {\n\n\/\/ This class fakes a client of ProducerSideService for use in tests.\nclass FakeProducer {\n public:\n void RunRpc(const std::shared_ptr& channel) {\n ASSERT_NE(channel, nullptr);\n\n std::unique_ptr stub =\n orbit_grpc_protos::ProducerSideService::NewStub(channel);\n ASSERT_NE(stub, nullptr);\n\n EXPECT_EQ(context_, nullptr);\n EXPECT_EQ(stream_, nullptr);\n context_ = std::make_unique();\n stream_ = stub->ReceiveCommandsAndSendEvents(context_.get());\n ASSERT_NE(stream_, nullptr);\n\n read_thread_ = std::thread([this] {\n orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse response;\n while (stream_->Read(&response)) {\n EXPECT_NE(response.command_case(),\n orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::COMMAND_NOT_SET);\n switch (response.command_case()) {\n case orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::kStartCaptureCommand:\n OnStartCaptureCommandReceived();\n break;\n case orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::kStopCaptureCommand:\n OnStopCaptureCommandReceived();\n break;\n case orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::COMMAND_NOT_SET:\n break;\n }\n }\n });\n }\n\n void SendBufferedCaptureEvents(int32_t num_to_send) {\n ASSERT_NE(stream_, nullptr);\n orbit_grpc_protos::ReceiveCommandsAndSendEventsRequest request;\n request.mutable_buffered_capture_events();\n for (int32_t i = 0; i < num_to_send; ++i) {\n request.mutable_buffered_capture_events()->mutable_capture_events()->Add();\n }\n bool written = stream_->Write(request);\n EXPECT_TRUE(written);\n }\n\n void SendAllEventsSent() {\n ASSERT_NE(stream_, nullptr);\n orbit_grpc_protos::ReceiveCommandsAndSendEventsRequest request;\n request.mutable_all_events_sent();\n bool written = stream_->Write(request);\n EXPECT_TRUE(written);\n }\n\n void FinishRpc() {\n if (context_ != nullptr) {\n context_->TryCancel();\n context_ = nullptr;\n EXPECT_NE(stream_, nullptr);\n EXPECT_TRUE(read_thread_.joinable());\n }\n stream_ = nullptr;\n if (read_thread_.joinable()) {\n read_thread_.join();\n }\n }\n\n MOCK_METHOD(void, OnStartCaptureCommandReceived, (), ());\n MOCK_METHOD(void, OnStopCaptureCommandReceived, (), ());\n\n private:\n std::unique_ptr context_;\n std::unique_ptr>\n stream_;\n std::thread read_thread_;\n};\n\nclass MockCaptureEventBuffer : public CaptureEventBuffer {\n public:\n MOCK_METHOD(void, AddEvent, (orbit_grpc_protos::CaptureEvent && event), (override));\n};\n\nclass ProducerSideServiceImplTest : public ::testing::Test {\n protected:\n void SetUp() override {\n service.emplace();\n\n grpc::ServerBuilder builder;\n builder.RegisterService(&*service);\n fake_server = builder.BuildAndStart();\n\n std::shared_ptr channel =\n fake_server->InProcessChannel(grpc::ChannelArguments{});\n\n fake_producer.emplace();\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n fake_producer->SendAllEventsSent();\n });\n fake_producer->RunRpc(channel);\n\n \/\/ Leave some time for the ReceiveCommandsAndSendEvents RPC to actually happen.\n std::this_thread::sleep_for(std::chrono::milliseconds(50));\n }\n\n void TearDown() override {\n \/\/ Leave some time for all pending communication to finish.\n std::this_thread::sleep_for(std::chrono::milliseconds(50));\n\n fake_producer->FinishRpc();\n fake_producer.reset();\n\n service->OnExitRequest();\n fake_server->Shutdown();\n fake_server->Wait();\n\n service.reset();\n fake_server.reset();\n }\n\n std::optional service;\n std::unique_ptr fake_server;\n std::optional fake_producer;\n};\n\nconstexpr std::chrono::duration kWaitMessagesSentDuration = std::chrono::milliseconds(10);\n\n} \/\/ namespace\n\nTEST_F(ProducerSideServiceImplTest, OneCapture) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n service->OnCaptureStopRequested();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n}\n\nTEST_F(ProducerSideServiceImplTest, TwoCaptures) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n service->OnCaptureStopRequested();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(1);\n fake_producer->SendBufferedCaptureEvents(2);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n service->OnCaptureStopRequested();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n}\n\nTEST_F(ProducerSideServiceImplTest, MultipleOnCaptureStartStop) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(0);\n \/\/ This should *not* cause StartCaptureCommand to be sent again.\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n service->OnCaptureStopRequested();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(0);\n \/\/ This should *not* cause StopCaptureCommand to be sent again.\n service->OnCaptureStopRequested();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n}\n\n} \/\/ namespace orbit_service\nAdd more test to ProducerSideServiceImplTest\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \n\n#include \"ProducerSideServiceImpl.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"grpcpp\/grpcpp.h\"\n\nnamespace orbit_service {\n\nnamespace {\n\n\/\/ This class fakes a client of ProducerSideService for use in tests.\nclass FakeProducer {\n public:\n void RunRpc(const std::shared_ptr& channel) {\n ASSERT_NE(channel, nullptr);\n\n std::unique_ptr stub =\n orbit_grpc_protos::ProducerSideService::NewStub(channel);\n ASSERT_NE(stub, nullptr);\n\n EXPECT_EQ(context_, nullptr);\n EXPECT_EQ(stream_, nullptr);\n context_ = std::make_unique();\n stream_ = stub->ReceiveCommandsAndSendEvents(context_.get());\n ASSERT_NE(stream_, nullptr);\n\n read_thread_ = std::thread([this] {\n orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse response;\n while (stream_->Read(&response)) {\n EXPECT_NE(response.command_case(),\n orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::COMMAND_NOT_SET);\n switch (response.command_case()) {\n case orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::kStartCaptureCommand:\n OnStartCaptureCommandReceived();\n break;\n case orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::kStopCaptureCommand:\n OnStopCaptureCommandReceived();\n break;\n case orbit_grpc_protos::ReceiveCommandsAndSendEventsResponse::COMMAND_NOT_SET:\n break;\n }\n }\n });\n }\n\n void SendBufferedCaptureEvents(int32_t num_to_send) {\n ASSERT_NE(stream_, nullptr);\n orbit_grpc_protos::ReceiveCommandsAndSendEventsRequest request;\n request.mutable_buffered_capture_events();\n for (int32_t i = 0; i < num_to_send; ++i) {\n request.mutable_buffered_capture_events()->mutable_capture_events()->Add();\n }\n bool written = stream_->Write(request);\n EXPECT_TRUE(written);\n }\n\n void SendAllEventsSent() {\n ASSERT_NE(stream_, nullptr);\n orbit_grpc_protos::ReceiveCommandsAndSendEventsRequest request;\n request.mutable_all_events_sent();\n bool written = stream_->Write(request);\n EXPECT_TRUE(written);\n }\n\n void FinishRpc() {\n if (context_ != nullptr) {\n context_->TryCancel();\n context_ = nullptr;\n EXPECT_NE(stream_, nullptr);\n EXPECT_TRUE(read_thread_.joinable());\n }\n stream_ = nullptr;\n if (read_thread_.joinable()) {\n read_thread_.join();\n }\n }\n\n MOCK_METHOD(void, OnStartCaptureCommandReceived, (), ());\n MOCK_METHOD(void, OnStopCaptureCommandReceived, (), ());\n\n private:\n std::unique_ptr context_;\n std::unique_ptr>\n stream_;\n std::thread read_thread_;\n};\n\nclass MockCaptureEventBuffer : public CaptureEventBuffer {\n public:\n MOCK_METHOD(void, AddEvent, (orbit_grpc_protos::CaptureEvent && event), (override));\n};\n\nclass ProducerSideServiceImplTest : public ::testing::Test {\n protected:\n void SetUp() override {\n service.emplace();\n\n grpc::ServerBuilder builder;\n builder.RegisterService(&*service);\n fake_server = builder.BuildAndStart();\n\n std::shared_ptr channel =\n fake_server->InProcessChannel(grpc::ChannelArguments{});\n\n fake_producer.emplace();\n fake_producer->RunRpc(channel);\n\n \/\/ Leave some time for the ReceiveCommandsAndSendEvents RPC to actually happen.\n std::this_thread::sleep_for(std::chrono::milliseconds(50));\n }\n\n void TearDown() override {\n \/\/ Leave some time for all pending communication to finish.\n std::this_thread::sleep_for(std::chrono::milliseconds(50));\n\n fake_producer->FinishRpc();\n fake_producer.reset();\n\n service->OnExitRequest();\n fake_server->Shutdown();\n fake_server->Wait();\n\n service.reset();\n fake_server.reset();\n }\n\n std::optional service;\n std::unique_ptr fake_server;\n std::optional fake_producer;\n};\n\nconstexpr std::chrono::duration kWaitMessagesSentDuration = std::chrono::milliseconds(25);\n\nvoid ExpectDurationBetweenMs(const std::function& action, uint64_t min_ms,\n uint64_t max_ms) {\n auto begin = std::chrono::steady_clock::now();\n action();\n auto end = std::chrono::steady_clock::now();\n EXPECT_GE(end - begin, std::chrono::milliseconds{min_ms});\n EXPECT_LE(end - begin, std::chrono::milliseconds{max_ms});\n}\n\n} \/\/ namespace\n\nTEST_F(ProducerSideServiceImplTest, OneCapture) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n static constexpr uint64_t kSendAllEventsDelayMs = 25;\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n std::this_thread::sleep_for(std::chrono::milliseconds{kSendAllEventsDelayMs});\n fake_producer->SendAllEventsSent();\n });\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, kSendAllEventsDelayMs,\n 2 * kSendAllEventsDelayMs);\n}\n\nTEST_F(ProducerSideServiceImplTest, TwoCaptures) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n fake_producer->SendAllEventsSent();\n });\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, 0,\n kWaitMessagesSentDuration.count());\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(1);\n fake_producer->SendBufferedCaptureEvents(2);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n static constexpr uint64_t kSendAllEventsDelayMs = 25;\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n std::this_thread::sleep_for(std::chrono::milliseconds{kSendAllEventsDelayMs});\n fake_producer->SendAllEventsSent();\n });\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, kSendAllEventsDelayMs,\n 2 * kSendAllEventsDelayMs);\n}\n\nTEST_F(ProducerSideServiceImplTest, NoCaptureEvents) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(0);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n static constexpr uint64_t kSendAllEventsDelayMs = 25;\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n std::this_thread::sleep_for(std::chrono::milliseconds{kSendAllEventsDelayMs});\n fake_producer->SendAllEventsSent();\n });\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, kSendAllEventsDelayMs,\n 2 * kSendAllEventsDelayMs);\n}\n\nTEST_F(ProducerSideServiceImplTest, NoAllEventsSent) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n static constexpr uint64_t kMaxWaitForAllCaptureEventsMs = 50;\n service->SetMaxWaitForAllCaptureEvents(absl::Milliseconds(kMaxWaitForAllCaptureEventsMs));\n \/\/ As the AllEventsSent is not sent by the producer, OnCaptureStopRequested\n \/\/ this should take the time specified with SetMaxWaitForAllCaptureEvents.\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); },\n kMaxWaitForAllCaptureEventsMs, 2 * kMaxWaitForAllCaptureEventsMs);\n}\n\nTEST_F(ProducerSideServiceImplTest, RedundantAllEventsSent) {\n MockCaptureEventBuffer mock_buffer;\n\n fake_producer->SendAllEventsSent();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n static constexpr uint64_t kSendAllEventsDelayMs = 25;\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n std::this_thread::sleep_for(std::chrono::milliseconds{kSendAllEventsDelayMs});\n fake_producer->SendAllEventsSent();\n });\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, kSendAllEventsDelayMs,\n 2 * kSendAllEventsDelayMs);\n\n fake_producer->SendAllEventsSent();\n}\n\nTEST_F(ProducerSideServiceImplTest, AllEventsSentBeforeStopCaptureCommand) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n fake_producer->SendAllEventsSent();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n \/\/ As the producer has already sent AllEventsSent, this should be immediate.\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, 0, 5);\n}\n\nTEST_F(ProducerSideServiceImplTest, MultipleOnCaptureStartStop) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(0);\n \/\/ This should *not* cause StartCaptureCommand to be sent again.\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n static constexpr uint64_t kSendAllEventsDelayMs = 25;\n ON_CALL(*fake_producer, OnStopCaptureCommandReceived).WillByDefault([this] {\n std::this_thread::sleep_for(std::chrono::milliseconds{kSendAllEventsDelayMs});\n fake_producer->SendAllEventsSent();\n });\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(1);\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, kSendAllEventsDelayMs,\n 2 * kSendAllEventsDelayMs);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(0);\n \/\/ This should *not* cause StopCaptureCommand to be sent again and should be immediate.\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, 0,\n kSendAllEventsDelayMs \/ 2);\n}\n\nTEST_F(ProducerSideServiceImplTest, NoOnCaptureStartRequested) {\n \/\/ As we are not waiting for any producer, this should be immediate.\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, 0, 5);\n}\n\nTEST_F(ProducerSideServiceImplTest, NoOnCaptureStopRequested) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(6);\n fake_producer->SendBufferedCaptureEvents(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n EXPECT_CALL(*fake_producer, OnStopCaptureCommandReceived).Times(0);\n}\n\nTEST_F(ProducerSideServiceImplTest, ProducerDisconnectsMidCapture) {\n MockCaptureEventBuffer mock_buffer;\n\n EXPECT_CALL(*fake_producer, OnStartCaptureCommandReceived).Times(1);\n service->OnCaptureStartRequested(&mock_buffer);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&*fake_producer);\n\n EXPECT_CALL(mock_buffer, AddEvent).Times(3);\n fake_producer->SendBufferedCaptureEvents(3);\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n fake_producer->FinishRpc();\n std::this_thread::sleep_for(kWaitMessagesSentDuration);\n\n ::testing::Mock::VerifyAndClearExpectations(&mock_buffer);\n\n \/\/ As the producer has disconnected, this should be immediate.\n ExpectDurationBetweenMs([this] { service->OnCaptureStopRequested(); }, 0, 5);\n}\n\n} \/\/ namespace orbit_service\n<|endoftext|>"} {"text":"#include \"..\/preproc.hh\"\n\n#include \n\n#ifdef MIMOSA_WIN\n# include \n# include \n\n\/\/ Link with ws2_32.lib\n# pragma comment(lib, \"Ws2_32.lib\")\n#endif\n\n#ifdef MIMOSA_UNIX\n# include \n# include \n# include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"io.hh\"\n#include \"connect.hh\"\n\nnamespace mimosa\n{\n namespace net\n {\n int connect(int socket, const struct sockaddr *address,\n socklen_t address_len, Time timeout)\n {\n if (!waitForFdReady(socket, POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI, timeout))\n return -1;\n return ::connect(socket, address, address_len);\n }\n\n int connectToHost(const std::string &host, uint16_t port, Time timeout)\n {\n ::hostent * host_entry = gethostbyname(host.c_str());\n if (!host_entry)\n return -1;\n\n int fd = ::socket(host_entry->h_addrtype, SOCK_STREAM, 0);\n if (fd < 0)\n return -1;\n\n if (host_entry->h_addrtype == AF_INET)\n {\n sockaddr_in addr;\n ::memset(&addr, 0, sizeof (addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n ::memcpy(&addr.sin_addr, host_entry->h_addr_list[0], host_entry->h_length);\n if (connect(fd, (const sockaddr*)&addr, sizeof (addr), timeout))\n {\n ::close(fd);\n return -1;\n }\n return fd;\n }\n if (host_entry->h_addrtype == AF_INET6)\n {\n sockaddr_in6 addr;\n ::memset(&addr, 0, sizeof (addr));\n addr.sin6_family = AF_INET6;\n addr.sin6_port = htons(port);\n ::memcpy(&addr.sin6_addr, host_entry->h_addr_list[0], host_entry->h_length);\n if (connect(fd, (const sockaddr*)&addr, sizeof (addr), timeout))\n {\n ::close(fd);\n return -1;\n }\n return fd;\n }\n ::close(fd);\n return -1;\n }\n\n int connectToUnixSocket(const std::string & path,\n Time timeout)\n {\n size_t addr_len = ((size_t) (((::sockaddr_un *) 0)->sun_path)) + path.size() + 1;\n std::unique_ptr data(new char[addr_len]);\n ::sockaddr_un & addr = *(::sockaddr_un*)data.get();\n addr.sun_family = AF_UNIX;\n ::memcpy(addr.sun_path, path.c_str(), path.size() + 1);\n\n int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);\n if (fd < 0)\n return -1;\n\n if (connect(fd, (const sockaddr*)&addr, addr_len, timeout))\n {\n ::close(fd);\n return -1;\n }\n return fd;\n }\n }\n}\nMore checks#include \"..\/preproc.hh\"\n\n#include \n\n#ifdef MIMOSA_WIN\n# include \n# include \n\n\/\/ Link with ws2_32.lib\n# pragma comment(lib, \"Ws2_32.lib\")\n#endif\n\n#ifdef MIMOSA_UNIX\n# include \n# include \n# include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"io.hh\"\n#include \"connect.hh\"\n\nnamespace mimosa\n{\n namespace net\n {\n int connect(int socket, const struct sockaddr *address,\n socklen_t address_len, Time timeout)\n {\n if (!waitForFdReady(socket, POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI, timeout))\n return -1;\n return ::connect(socket, address, address_len);\n }\n\n int connectToHost(const std::string &host, uint16_t port, Time timeout)\n {\n ::hostent * host_entry = gethostbyname(host.c_str());\n if (!host_entry || !host_entry->h_addr_list[0])\n return -1;\n\n int fd = ::socket(host_entry->h_addrtype, SOCK_STREAM, 0);\n if (fd < 0)\n return -1;\n\n if (host_entry->h_addrtype == AF_INET)\n {\n sockaddr_in addr;\n ::memset(&addr, 0, sizeof (addr));\n addr.sin_family = AF_INET;\n addr.sin_port = htons(port);\n ::memcpy(&addr.sin_addr, host_entry->h_addr_list[0], host_entry->h_length);\n if (connect(fd, (const sockaddr*)&addr, sizeof (addr), timeout))\n {\n ::close(fd);\n return -1;\n }\n return fd;\n }\n if (host_entry->h_addrtype == AF_INET6)\n {\n sockaddr_in6 addr;\n ::memset(&addr, 0, sizeof (addr));\n addr.sin6_family = AF_INET6;\n addr.sin6_port = htons(port);\n ::memcpy(&addr.sin6_addr, host_entry->h_addr_list[0], host_entry->h_length);\n if (connect(fd, (const sockaddr*)&addr, sizeof (addr), timeout))\n {\n ::close(fd);\n return -1;\n }\n return fd;\n }\n ::close(fd);\n return -1;\n }\n\n int connectToUnixSocket(const std::string & path,\n Time timeout)\n {\n size_t addr_len = ((size_t) (((::sockaddr_un *) 0)->sun_path)) + path.size() + 1;\n std::unique_ptr data(new char[addr_len]);\n ::sockaddr_un & addr = *(::sockaddr_un*)data.get();\n addr.sun_family = AF_UNIX;\n ::memcpy(addr.sun_path, path.c_str(), path.size() + 1);\n\n int fd = ::socket(AF_UNIX, SOCK_STREAM, 0);\n if (fd < 0)\n return -1;\n\n if (connect(fd, (const sockaddr*)&addr, addr_len, timeout))\n {\n ::close(fd);\n return -1;\n }\n return fd;\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/\n\/\/ Task to propagate AOD tracks to EMCAL surface.\n\/\/\n\/\/ Author: C.Loizides\n\n#include \n#include \"AliAnalysisManager.h\"\n#include \"AliEMCALRecoUtils.h\"\n#include \"AliAODEvent.h\"\n#include \"AliAODTrack.h\"\n#include \"AliExternalTrackParam.h\"\n#include \"AliEmcalTrackPropagatorTaskAOD.h\"\n\nClassImp(AliEmcalTrackPropagatorTaskAOD)\n\n\/\/________________________________________________________________________\nAliEmcalTrackPropagatorTaskAOD::AliEmcalTrackPropagatorTaskAOD() : \n AliAnalysisTaskSE(\"AliEmcalTrackPropagatorTaskAOD\"),\n fRecoUtils(0),\n fTracksName(),\n fDist(430),\n fMinPtCut(0.35),\n fAodEv(0),\n fTracks(0)\n{\n \/\/ Constructor.\n}\n\n\/\/________________________________________________________________________\nAliEmcalTrackPropagatorTaskAOD::AliEmcalTrackPropagatorTaskAOD(const char *name) : \n AliAnalysisTaskSE(\"AliEmcalTrackPropagatorTaskAOD\"),\n fRecoUtils(0),\n fTracksName(\"TpcSpdVertexConstrainedTracks\"),\n fDist(430),\n fMinPtCut(0.35),\n fAodEv(0),\n fTracks(0)\n{\n \/\/ Constructor.\n\n if (!name)\n return;\n\n SetName(name);\n\n \/\/ fBranchNames = \"ESD:AliESDHeader.,Tracks\";\n}\n\n\/\/________________________________________________________________________\nAliEmcalTrackPropagatorTaskAOD::~AliEmcalTrackPropagatorTaskAOD()\n{\n \/\/ Destructor.\n\n delete fRecoUtils;\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalTrackPropagatorTaskAOD::UserCreateOutputObjects()\n{\n \/\/ Create histograms.\n\n if (!fRecoUtils) {\n fRecoUtils = new AliEMCALRecoUtils;\n fRecoUtils->SetStep(20);\n AliInfo(\"No reco utils given, creating default utils\");\n }\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalTrackPropagatorTaskAOD::UserExec(Option_t *) \n{\n \/\/ Main loop, called for each event.\n\n fAodEv = dynamic_cast(InputEvent());\n if (!fAodEv) {\n AliError(\"Task works only on AOD events, returning\");\n return;\n }\n\n AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();\n if (!am) {\n AliError(\"Manager zero, returning\");\n return;\n }\n\n \/\/ get tracks from event if not yet there\n if (fTracksName == \"tracks\")\n am->LoadBranch(\"tracks\");\n fTracks = dynamic_cast((InputEvent()->FindListObject(fTracksName)));\n if (!fTracks) {\n AliError(Form(\"Could not get tracks %s, returning\", fTracksName.Data()));\n return;\n }\n\n \/\/ Loop over all tracks\n const Int_t ntr = fTracks->GetEntries();\n for (Int_t i=0; i(fTracks->At(i));\n if (!aodTrack)\n continue;\n aodTrack->ResetStatus(AliVTrack::kEMCALmatch); \/\/MV: necessary?\n if(aodTrack->Pt()GetTrackPtOnEMCal()>0) \n continue;\n\n Double_t phi = aodTrack->Phi()*TMath::RadToDeg();\n if (TMath::Abs(aodTrack->Eta())>0.9 || phi <= 10 || phi >= 250) \n continue;\n\n Double_t xyz[3], pxpypz[3], cv[21];\n aodTrack->PxPyPz(pxpypz); \n aodTrack->XvYvZv(xyz);\n aodTrack->GetCovarianceXYZPxPyPz(cv); \n AliExternalTrackParam *trackParam = new AliExternalTrackParam(xyz,pxpypz,cv,aodTrack->Charge());\n \/\/ AliExternalTrackParam *trackParam = const_cast(eTrack->GetInnerParam()); MV: note, not taking InnerParam in AOD, not available\n if(!trackParam) \n continue;\n\n \/\/ Extrapolate the track to EMCal surface\n AliExternalTrackParam emcalParam(*trackParam);\n Float_t etaout=-999, phiout=-999, ptout=-999;\n Bool_t ret = fRecoUtils->ExtrapolateTrackToEMCalSurface(&emcalParam, \n fDist, \n aodTrack->M(), \n fRecoUtils->GetStepSurface(), \n etaout, \n phiout,\n\t\t\t\t\t\t\t ptout);\n if (!ret)\n continue;\n if (TMath::Abs(etaout)>0.75 || (phiout<70*TMath::DegToRad()) || (phiout>190*TMath::DegToRad()))\n continue;\n aodTrack->SetTrackPhiEtaPtOnEMCal(phiout, etaout, ptout);\n aodTrack->SetStatus(AliVTrack::kEMCALmatch);\n\n delete trackParam;\n }\n}\nUse AliEMCALRecoUtils for propagation including use of pion mass for all tracks\/\/ $Id$\n\/\/\n\/\/ Task to propagate AOD tracks to EMCAL surface.\n\/\/\n\/\/ Author: C.Loizides\n\n#include \n#include \"AliAnalysisManager.h\"\n#include \"AliEMCALRecoUtils.h\"\n#include \"AliAODEvent.h\"\n#include \"AliAODTrack.h\"\n#include \"AliExternalTrackParam.h\"\n#include \n#include \n#include \n\n#include \"AliEmcalTrackPropagatorTaskAOD.h\"\n\nClassImp(AliEmcalTrackPropagatorTaskAOD)\n\n\/\/________________________________________________________________________\nAliEmcalTrackPropagatorTaskAOD::AliEmcalTrackPropagatorTaskAOD() : \n AliAnalysisTaskSE(\"AliEmcalTrackPropagatorTaskAOD\"),\n fRecoUtils(0),\n fTracksName(),\n fDist(430),\n fMinPtCut(0.35),\n fAodEv(0),\n fTracks(0)\n{\n \/\/ Constructor.\n}\n\n\/\/________________________________________________________________________\nAliEmcalTrackPropagatorTaskAOD::AliEmcalTrackPropagatorTaskAOD(const char *name) : \n AliAnalysisTaskSE(\"AliEmcalTrackPropagatorTaskAOD\"),\n fRecoUtils(0),\n fTracksName(\"TpcSpdVertexConstrainedTracks\"),\n fDist(430),\n fMinPtCut(0.35),\n fAodEv(0),\n fTracks(0)\n{\n \/\/ Constructor.\n\n if (!name)\n return;\n\n SetName(name);\n\n \/\/ fBranchNames = \"ESD:AliESDHeader.,Tracks\";\n}\n\n\/\/________________________________________________________________________\nAliEmcalTrackPropagatorTaskAOD::~AliEmcalTrackPropagatorTaskAOD()\n{\n \/\/ Destructor.\n\n delete fRecoUtils;\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalTrackPropagatorTaskAOD::UserCreateOutputObjects()\n{\n \/\/ Create histograms.\n\n if (!fRecoUtils) {\n fRecoUtils = new AliEMCALRecoUtils;\n fRecoUtils->SetStep(20);\n AliInfo(\"No reco utils given, creating default utils\");\n }\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalTrackPropagatorTaskAOD::UserExec(Option_t *) \n{\n \/\/ Main loop, called for each event.\n\n fAodEv = dynamic_cast(InputEvent());\n if (!fAodEv) {\n AliError(\"Task works only on AOD events, returning\");\n return;\n }\n\n AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();\n if (!am) {\n AliError(\"Manager zero, returning\");\n return;\n }\n\n \/\/ get tracks from event if not yet there\n if (fTracksName == \"tracks\")\n am->LoadBranch(\"tracks\");\n\n fTracks = dynamic_cast((InputEvent()->FindListObject(fTracksName)));\n if (!fTracks) {\n AliError(Form(\"Could not get tracks %s, returning\", fTracksName.Data()));\n return;\n }\n\n \/\/ Loop over all tracks\n const Int_t ntr = fTracks->GetEntries();\n for (Int_t i=0; i(fTracks->At(i));\n if (!aodTrack)\n continue;\n if(aodTrack->Pt()GetTrackPtOnEMCal()>0) \n continue;\n\n AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(aodTrack,fDist);\n }\n}\n<|endoftext|>"} {"text":"\/\/ CuttingTool.cpp\n\/*\n * Copyright (c) 2009, Dan Heeks, Perttu Ahola\n * This program is released under the BSD license. See the file COPYING for\n * details.\n *\/\n\n#include \"stdafx.h\"\n#include \"CuttingTool.h\"\n#include \"CNCConfig.h\"\n#include \"ProgramCanvas.h\"\n#include \"interface\/HeeksObj.h\"\n#include \"interface\/PropertyInt.h\"\n#include \"interface\/PropertyDouble.h\"\n#include \"interface\/PropertyLength.h\"\n#include \"interface\/PropertyChoice.h\"\n#include \"interface\/PropertyString.h\"\n#include \"tinyxml\/tinyxml.h\"\n\n#include \n\nextern CHeeksCADInterface* heeksCAD;\n\n\n\nvoid CCuttingToolParams::set_initial_values()\n{\n\tCNCConfig config;\n\tconfig.Read(_T(\"m_diameter\"), &m_diameter, 12.7);\n\tconfig.Read(_T(\"m_x_offset\"), &m_x_offset, 0);\n\tconfig.Read(_T(\"m_tool_length_offset\"), &m_tool_length_offset, 0);\n\tconfig.Read(_T(\"m_orientation\"), &m_orientation, 9);\n}\n\nvoid CCuttingToolParams::write_values_to_config()\n{\n\tCNCConfig config;\n\n\t\/\/ We ALWAYS write the parameters into the configuration file in mm (for consistency).\n\t\/\/ If we're now in inches then convert the values.\n\t\/\/ We're in mm already.\n\tconfig.Write(_T(\"m_diameter\"), m_diameter);\n\tconfig.Write(_T(\"m_x_offset\"), m_x_offset);\n\tconfig.Write(_T(\"m_tool_length_offset\"), m_tool_length_offset);\n\tconfig.Write(_T(\"m_orientation\"), m_orientation);\n}\n\nstatic void on_set_diameter(double value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_diameter = value;}\nstatic void on_set_x_offset(double value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_x_offset = value;}\nstatic void on_set_tool_length_offset(double value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_tool_length_offset = value;}\nstatic void on_set_orientation(int value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_orientation = value;}\n\nvoid CCuttingToolParams::GetProperties(CCuttingTool* parent, std::list *list)\n{\n\tlist->push_back(new PropertyLength(_(\"diameter\"), m_diameter, parent, on_set_diameter));\n\tlist->push_back(new PropertyLength(_(\"x_offset\"), m_x_offset, parent, on_set_x_offset));\n\tlist->push_back(new PropertyLength(_(\"tool_length_offset\"), m_x_offset, parent, on_set_tool_length_offset));\n\tlist->push_back(new PropertyInt(_(\"orientation\"), m_orientation, parent, on_set_orientation));\n}\n\nvoid CCuttingToolParams::WriteXMLAttributes(TiXmlNode *root)\n{\n\tTiXmlElement * element;\n\telement = new TiXmlElement( \"params\" );\n\troot->LinkEndChild( element ); \n\n\n\telement->SetDoubleAttribute(\"diameter\", m_diameter);\n\telement->SetDoubleAttribute(\"x_offset\", m_x_offset);\n\telement->SetDoubleAttribute(\"tool_length_offset\", m_tool_length_offset);\n\t\n\tstd::ostringstream l_ossValue;\n\tl_ossValue.str(\"\"); l_ossValue << m_orientation;\n\telement->SetAttribute(\"orientation\", l_ossValue.str().c_str() );\n}\n\nvoid CCuttingToolParams::ReadParametersFromXMLElement(TiXmlElement* pElem)\n{\n\tif (pElem->Attribute(\"diameter\")) m_diameter = atof(pElem->Attribute(\"diameter\"));\n\tif (pElem->Attribute(\"x_offset\")) m_x_offset = atof(pElem->Attribute(\"x_offset\"));\n\tif (pElem->Attribute(\"tool_length_offset\")) m_tool_length_offset = atof(pElem->Attribute(\"tool_length_offset\"));\n\tif (pElem->Attribute(\"orientation\")) m_orientation = atoi(pElem->Attribute(\"orientation\"));\n}\n\n\/**\n\tThis method is called when the CAD operator presses the Python button. This method generates\n\tPython source code whose job will be to generate RS-274 GCode. It's done in two steps so that\n\tthe Python code can be configured to generate GCode suitable for various CNC interpreters.\n *\/\nvoid CCuttingTool::AppendTextToProgram()\n{\n\n#ifdef UNICODE\n\tstd::wostringstream ss;\n#else\n std::ostringstream ss;\n#endif\n ss.imbue(std::locale(\"C\"));\n\n\t\/\/ The G10 command can be used (within EMC2) to add a tool to the tool\n \/\/ table from within a program.\n \/\/ G10 L1 P[tool number] R[radius] X[offset] Z[offset] Q[orientation]\n\n\tif (m_title.size() > 0)\n\t{\n\t\tss << \"#(\" << m_title.c_str() << \")\\n\";\n\t} \/\/ End if - then\n\n\tss << \"tool_defn( id=\" << m_tool_number << \", \"\n\t\t<< \"name=None, \";\n\tif (m_params.m_diameter > 0)\n\t{\n\t\tss << \"radius=\" << m_params.m_diameter \/ 2 << \", \";\n\t} \/\/ End if - then\n\telse\n\t{\n\t\tss << \"radius=None, \";\n\t} \/\/ End if - else\n\n\tif (m_params.m_tool_length_offset > 0)\n\t{\n\t\tss << \"length=\" << m_params.m_tool_length_offset;\n\t} \/\/ End if - then\n\telse\n\t{\n\t\tss << \"length=None\";\n\t} \/\/ End if - else\n\t\n\tss << \")\\n\";\n\n\ttheApp.m_program_canvas->m_textCtrl->AppendText(ss.str().c_str());\n}\n\n\nstatic void on_set_tool_number(const int value, HeeksObj* object){((CCuttingTool*)object)->m_tool_number = value;}\n\n\/**\n\tNOTE: The m_title member is a special case. The HeeksObj code looks for a 'GetShortDesc()' method. If found, it\n\tadds a Property called 'Object Title'. If the value is changed, it tries to call the 'OnEditString()' method.\n\tThat's why the m_title value is not defined here\n *\/\nvoid CCuttingTool::GetProperties(std::list *list)\n{\n\tlist->push_back(new PropertyInt(_(\"tool_number\"), m_tool_number, this, on_set_tool_number));\n\n\tm_params.GetProperties(this, list);\n\tHeeksObj::GetProperties(list);\n}\n\n\nHeeksObj *CCuttingTool::MakeACopy(void)const\n{\n\treturn new CCuttingTool(*this);\n}\n\nvoid CCuttingTool::CopyFrom(const HeeksObj* object)\n{\n\toperator=(*((CCuttingTool*)object));\n}\n\nbool CCuttingTool::CanAddTo(HeeksObj* owner)\n{\n\treturn owner->GetType() == ToolsType;\n}\n\nvoid CCuttingTool::WriteXML(TiXmlNode *root)\n{\n\tTiXmlElement * element = new TiXmlElement( \"CuttingTool\" );\n\troot->LinkEndChild( element ); \n\telement->SetAttribute(\"title\", Ttc(m_title.c_str()));\n\n\tstd::ostringstream l_ossValue;\n\tl_ossValue.str(\"\"); l_ossValue << m_tool_number;\n\telement->SetAttribute(\"tool_number\", l_ossValue.str().c_str() );\n\n\tm_params.WriteXMLAttributes(element);\n\tWriteBaseXML(element);\n}\n\n\/\/ static member function\nHeeksObj* CCuttingTool::ReadFromXMLElement(TiXmlElement* element)\n{\n\n\tint tool_number = 0;\n\tif (element->Attribute(\"tool_number\")) tool_number = atoi(element->Attribute(\"tool_number\"));\n\n\twxString title(Ctt(element->Attribute(\"title\")));\n\tCCuttingTool* new_object = new CCuttingTool( title.c_str(), tool_number);\n\n\t\/\/ read point and circle ids\n\tfor(TiXmlElement* pElem = TiXmlHandle(element).FirstChildElement().Element(); pElem; pElem = pElem->NextSiblingElement())\n\t{\n\t\tstd::string name(pElem->Value());\n\t\tif(name == \"params\"){\n\t\t\tnew_object->m_params.ReadParametersFromXMLElement(pElem);\n\t\t}\n\t}\n\n\tnew_object->ReadBaseXML(element);\n\n\treturn new_object;\n}\n\n\nvoid CCuttingTool::OnEditString(const wxChar* str){\n m_title.assign(str);\n\theeksCAD->WasModified(this);\n}\n\n\/**\n * Find the CuttingTool object whose tool number matches that passed in.\n *\/\nint CCuttingTool::FindCuttingTool( const int tool_number )\n{\n \/* Can't make this work. Need to figure out why *\/\n for (HeeksObj *ob = heeksCAD->GetFirstObject(); ob != NULL; ob = heeksCAD->GetNextObject())\n {\n if (ob->GetType() != CuttingToolType) continue;\n\n if (((CCuttingTool *) ob)->m_tool_number == tool_number)\n {\n return(ob->m_id);\n } \/\/ End if - then\n } \/\/ End for\n\n \/\/ This is a hack but it works. As long as we don't get more than 100 tools in the holder.\n for (int id=1; id<100; id++)\n {\n HeeksObj *ob = heeksCAD->GetIDObject( CuttingToolType, id );\n if (! ob) continue;\n\n if (((CCuttingTool *) ob)->m_tool_number == tool_number)\n {\n return(ob->m_id);\n } \/\/ End if - then\n } \/\/ End for\n\n return(-1);\n\n} \/\/ End FindCuttingTool() method\n\nadded units\/\/ CuttingTool.cpp\n\/*\n * Copyright (c) 2009, Dan Heeks, Perttu Ahola\n * This program is released under the BSD license. See the file COPYING for\n * details.\n *\/\n\n#include \"stdafx.h\"\n#include \"CuttingTool.h\"\n#include \"CNCConfig.h\"\n#include \"ProgramCanvas.h\"\n#include \"interface\/HeeksObj.h\"\n#include \"interface\/PropertyInt.h\"\n#include \"interface\/PropertyDouble.h\"\n#include \"interface\/PropertyLength.h\"\n#include \"interface\/PropertyChoice.h\"\n#include \"interface\/PropertyString.h\"\n#include \"tinyxml\/tinyxml.h\"\n\n#include \n\nextern CHeeksCADInterface* heeksCAD;\n\n\n\nvoid CCuttingToolParams::set_initial_values()\n{\n\tCNCConfig config;\n\tconfig.Read(_T(\"m_diameter\"), &m_diameter, 12.7);\n\tconfig.Read(_T(\"m_x_offset\"), &m_x_offset, 0);\n\tconfig.Read(_T(\"m_tool_length_offset\"), &m_tool_length_offset, 0);\n\tconfig.Read(_T(\"m_orientation\"), &m_orientation, 9);\n}\n\nvoid CCuttingToolParams::write_values_to_config()\n{\n\tCNCConfig config;\n\n\t\/\/ We ALWAYS write the parameters into the configuration file in mm (for consistency).\n\t\/\/ If we're now in inches then convert the values.\n\t\/\/ We're in mm already.\n\tconfig.Write(_T(\"m_diameter\"), m_diameter);\n\tconfig.Write(_T(\"m_x_offset\"), m_x_offset);\n\tconfig.Write(_T(\"m_tool_length_offset\"), m_tool_length_offset);\n\tconfig.Write(_T(\"m_orientation\"), m_orientation);\n}\n\nstatic void on_set_diameter(double value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_diameter = value;}\nstatic void on_set_x_offset(double value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_x_offset = value;}\nstatic void on_set_tool_length_offset(double value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_tool_length_offset = value;}\nstatic void on_set_orientation(int value, HeeksObj* object){((CCuttingTool*)object)->m_params.m_orientation = value;}\n\nvoid CCuttingToolParams::GetProperties(CCuttingTool* parent, std::list *list)\n{\n\tlist->push_back(new PropertyLength(_(\"diameter\"), m_diameter, parent, on_set_diameter));\n\tlist->push_back(new PropertyLength(_(\"x_offset\"), m_x_offset, parent, on_set_x_offset));\n\tlist->push_back(new PropertyLength(_(\"tool_length_offset\"), m_x_offset, parent, on_set_tool_length_offset));\n\tlist->push_back(new PropertyInt(_(\"orientation\"), m_orientation, parent, on_set_orientation));\n}\n\nvoid CCuttingToolParams::WriteXMLAttributes(TiXmlNode *root)\n{\n\tTiXmlElement * element;\n\telement = new TiXmlElement( \"params\" );\n\troot->LinkEndChild( element ); \n\n\n\telement->SetDoubleAttribute(\"diameter\", m_diameter);\n\telement->SetDoubleAttribute(\"x_offset\", m_x_offset);\n\telement->SetDoubleAttribute(\"tool_length_offset\", m_tool_length_offset);\n\t\n\tstd::ostringstream l_ossValue;\n\tl_ossValue.str(\"\"); l_ossValue << m_orientation;\n\telement->SetAttribute(\"orientation\", l_ossValue.str().c_str() );\n}\n\nvoid CCuttingToolParams::ReadParametersFromXMLElement(TiXmlElement* pElem)\n{\n\tif (pElem->Attribute(\"diameter\")) m_diameter = atof(pElem->Attribute(\"diameter\"));\n\tif (pElem->Attribute(\"x_offset\")) m_x_offset = atof(pElem->Attribute(\"x_offset\"));\n\tif (pElem->Attribute(\"tool_length_offset\")) m_tool_length_offset = atof(pElem->Attribute(\"tool_length_offset\"));\n\tif (pElem->Attribute(\"orientation\")) m_orientation = atoi(pElem->Attribute(\"orientation\"));\n}\n\n\/**\n\tThis method is called when the CAD operator presses the Python button. This method generates\n\tPython source code whose job will be to generate RS-274 GCode. It's done in two steps so that\n\tthe Python code can be configured to generate GCode suitable for various CNC interpreters.\n *\/\nvoid CCuttingTool::AppendTextToProgram()\n{\n\n#ifdef UNICODE\n\tstd::wostringstream ss;\n#else\n std::ostringstream ss;\n#endif\n ss.imbue(std::locale(\"C\"));\n\n\t\/\/ The G10 command can be used (within EMC2) to add a tool to the tool\n \/\/ table from within a program.\n \/\/ G10 L1 P[tool number] R[radius] X[offset] Z[offset] Q[orientation]\n\n\tif (m_title.size() > 0)\n\t{\n\t\tss << \"#(\" << m_title.c_str() << \")\\n\";\n\t} \/\/ End if - then\n\n\tss << \"tool_defn( id=\" << m_tool_number << \", \"\n\t\t<< \"name=None, \";\n\tif (m_params.m_diameter > 0)\n\t{\n\t\tss << \"radius=\" << m_params.m_diameter \/ 2 \/theApp.m_program->m_units << \", \";\n\t} \/\/ End if - then\n\telse\n\t{\n\t\tss << \"radius=None, \";\n\t} \/\/ End if - else\n\n\tif (m_params.m_tool_length_offset > 0)\n\t{\n\t\tss << \"length=\" << m_params.m_tool_length_offset \/theApp.m_program->m_units;\n\t} \/\/ End if - then\n\telse\n\t{\n\t\tss << \"length=None\";\n\t} \/\/ End if - else\n\t\n\tss << \")\\n\";\n\n\ttheApp.m_program_canvas->m_textCtrl->AppendText(ss.str().c_str());\n}\n\n\nstatic void on_set_tool_number(const int value, HeeksObj* object){((CCuttingTool*)object)->m_tool_number = value;}\n\n\/**\n\tNOTE: The m_title member is a special case. The HeeksObj code looks for a 'GetShortDesc()' method. If found, it\n\tadds a Property called 'Object Title'. If the value is changed, it tries to call the 'OnEditString()' method.\n\tThat's why the m_title value is not defined here\n *\/\nvoid CCuttingTool::GetProperties(std::list *list)\n{\n\tlist->push_back(new PropertyInt(_(\"tool_number\"), m_tool_number, this, on_set_tool_number));\n\n\tm_params.GetProperties(this, list);\n\tHeeksObj::GetProperties(list);\n}\n\n\nHeeksObj *CCuttingTool::MakeACopy(void)const\n{\n\treturn new CCuttingTool(*this);\n}\n\nvoid CCuttingTool::CopyFrom(const HeeksObj* object)\n{\n\toperator=(*((CCuttingTool*)object));\n}\n\nbool CCuttingTool::CanAddTo(HeeksObj* owner)\n{\n\treturn owner->GetType() == ToolsType;\n}\n\nvoid CCuttingTool::WriteXML(TiXmlNode *root)\n{\n\tTiXmlElement * element = new TiXmlElement( \"CuttingTool\" );\n\troot->LinkEndChild( element ); \n\telement->SetAttribute(\"title\", Ttc(m_title.c_str()));\n\n\tstd::ostringstream l_ossValue;\n\tl_ossValue.str(\"\"); l_ossValue << m_tool_number;\n\telement->SetAttribute(\"tool_number\", l_ossValue.str().c_str() );\n\n\tm_params.WriteXMLAttributes(element);\n\tWriteBaseXML(element);\n}\n\n\/\/ static member function\nHeeksObj* CCuttingTool::ReadFromXMLElement(TiXmlElement* element)\n{\n\n\tint tool_number = 0;\n\tif (element->Attribute(\"tool_number\")) tool_number = atoi(element->Attribute(\"tool_number\"));\n\n\twxString title(Ctt(element->Attribute(\"title\")));\n\tCCuttingTool* new_object = new CCuttingTool( title.c_str(), tool_number);\n\n\t\/\/ read point and circle ids\n\tfor(TiXmlElement* pElem = TiXmlHandle(element).FirstChildElement().Element(); pElem; pElem = pElem->NextSiblingElement())\n\t{\n\t\tstd::string name(pElem->Value());\n\t\tif(name == \"params\"){\n\t\t\tnew_object->m_params.ReadParametersFromXMLElement(pElem);\n\t\t}\n\t}\n\n\tnew_object->ReadBaseXML(element);\n\n\treturn new_object;\n}\n\n\nvoid CCuttingTool::OnEditString(const wxChar* str){\n m_title.assign(str);\n\theeksCAD->WasModified(this);\n}\n\n\/**\n * Find the CuttingTool object whose tool number matches that passed in.\n *\/\nint CCuttingTool::FindCuttingTool( const int tool_number )\n{\n \/* Can't make this work. Need to figure out why *\/\n for (HeeksObj *ob = heeksCAD->GetFirstObject(); ob != NULL; ob = heeksCAD->GetNextObject())\n {\n if (ob->GetType() != CuttingToolType) continue;\n\n if (((CCuttingTool *) ob)->m_tool_number == tool_number)\n {\n return(ob->m_id);\n } \/\/ End if - then\n } \/\/ End for\n\n \/\/ This is a hack but it works. As long as we don't get more than 100 tools in the holder.\n for (int id=1; id<100; id++)\n {\n HeeksObj *ob = heeksCAD->GetIDObject( CuttingToolType, id );\n if (! ob) continue;\n\n if (((CCuttingTool *) ob)->m_tool_number == tool_number)\n {\n return(ob->m_id);\n } \/\/ End if - then\n } \/\/ End for\n\n return(-1);\n\n} \/\/ End FindCuttingTool() method\n\n<|endoftext|>"} {"text":"\/\/ Make sure we report atexit stats.\n\/\/ RUN: %clangxx_asan -O3 %s -o %t\n\/\/ RUN: env ASAN_OPTIONS=atexit=1:print_stats=1 %run %t 2>&1 | FileCheck %s\n\/\/\n\/\/ No atexit output on Android due to\n\/\/ https:\/\/code.google.com\/p\/address-sanitizer\/issues\/detail?id=263\n\/\/ XFAIL: android\n\n#include \n#if !defined(__APPLE__)\n#include \n#endif\nint *p1 = (int*)malloc(900);\nint *p2 = (int*)malloc(90000);\nint *p3 = (int*)malloc(9000000);\nint main() { }\n\n\/\/ CHECK: AddressSanitizer exit stats:\nAdd FreeBSD support to the address sanitizer's atexit_stats.cc test case Differential Revision: http:\/\/reviews.llvm.org\/D4524\/\/ Make sure we report atexit stats.\n\/\/ RUN: %clangxx_asan -O3 %s -o %t\n\/\/ RUN: env ASAN_OPTIONS=atexit=1:print_stats=1 %run %t 2>&1 | FileCheck %s\n\/\/\n\/\/ No atexit output on Android due to\n\/\/ https:\/\/code.google.com\/p\/address-sanitizer\/issues\/detail?id=263\n\/\/ XFAIL: android\n\n#include \n#if !defined(__APPLE__) && !defined(__FreeBSD__)\n#include \n#endif\nint *p1 = (int*)malloc(900);\nint *p2 = (int*)malloc(90000);\nint *p3 = (int*)malloc(9000000);\nint main() { }\n\n\/\/ CHECK: AddressSanitizer exit stats:\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: normal_estimation.cpp 1032 2011-05-18 22:43:27Z marton $\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_k = 0;\ndouble default_radius = 0.0;\n\nvoid\nprintHelp (int argc, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -radius X = use a radius of Xm around each point to determine the neighborhood (default: \"); \n print_value (\"%f\", default_radius); print_info (\")\\n\");\n print_info (\" -k X = use a fixed number of X-nearest neighbors around each point (default: \"); \n print_value (\"%f\", default_k); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" seconds : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n int k, double radius)\n{\n \/\/ Convert data to PointCloud\n PointCloud::Ptr xyz (new PointCloud);\n fromROSMsg (*input, *xyz);\n\n \/\/ Estimate\n TicToc tt;\n tt.tic ();\n \n print_highlight (stderr, \"Computing \");\n\n NormalEstimation ne;\n ne.setInputCloud (xyz);\n ne.setSearchMethod (pcl::KdTreeFLANN::Ptr (new pcl::KdTreeFLANN));\n ne.setKSearch (k);\n ne.setRadiusSearch (radius);\n \n PointCloud normals;\n ne.compute (normals);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" seconds : \"); print_value (\"%d\", normals.width * normals.height); print_info (\" points]\\n\");\n\n \/\/ Convert data back\n sensor_msgs::PointCloud2 output_normals;\n toROSMsg (normals, output_normals);\n concatenateFields (*input, output_normals, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n \n pcl::io::savePCDFile (filename, output);\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" seconds : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Estimate surface normals using pcl::NormalEstimation. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n int k = default_k;\n double radius = default_radius;\n parse_argument (argc, argv, \"-k\", k);\n parse_argument (argc, argv, \"-radius\", radius);\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud)) \n return (-1);\n\n \/\/ Perform the feature estimation\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, k, radius);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n\nsaving files as binary in the normal estimation PCL_TOOL\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: normal_estimation.cpp 1032 2011-05-18 22:43:27Z marton $\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_k = 0;\ndouble default_radius = 0.0;\n\nEigen::Vector4f translation;\nEigen::Quaternionf orientation;\n\nvoid\nprintHelp (int argc, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -radius X = use a radius of Xm around each point to determine the neighborhood (default: \"); \n print_value (\"%f\", default_radius); print_info (\")\\n\");\n print_info (\" -k X = use a fixed number of X-nearest neighbors around each point (default: \"); \n print_value (\"%f\", default_k); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud, translation, orientation) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" seconds : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n int k, double radius)\n{\n \/\/ Convert data to PointCloud\n PointCloud::Ptr xyz (new PointCloud);\n fromROSMsg (*input, *xyz);\n\n \/\/ Estimate\n TicToc tt;\n tt.tic ();\n \n print_highlight (stderr, \"Computing \");\n\n NormalEstimation ne;\n ne.setInputCloud (xyz);\n ne.setSearchMethod (pcl::KdTreeFLANN::Ptr (new pcl::KdTreeFLANN));\n ne.setKSearch (k);\n ne.setRadiusSearch (radius);\n \n PointCloud normals;\n ne.compute (normals);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" seconds : \"); print_value (\"%d\", normals.width * normals.height); print_info (\" points]\\n\");\n\n \/\/ Convert data back\n sensor_msgs::PointCloud2 output_normals;\n toROSMsg (normals, output_normals);\n concatenateFields (*input, output_normals, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n \n pcl::io::savePCDFile (filename, output, translation, orientation, true);\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" seconds : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Estimate surface normals using pcl::NormalEstimation. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n int k = default_k;\n double radius = default_radius;\n parse_argument (argc, argv, \"-k\", k);\n parse_argument (argc, argv, \"-radius\", radius);\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud)) \n return (-1);\n\n \/\/ Perform the feature estimation\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, k, radius);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n\n<|endoftext|>"} {"text":"\/\/===- yaml2elf - Convert YAML to a ELF object file -----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief The ELF component of yaml2obj.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"yaml2obj.h\"\n#include \"llvm\/Object\/ELF.h\"\n#include \"llvm\/Object\/ELFYAML.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/YAMLTraits.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\n\/\/ There is similar code in yaml2coff, but with some slight COFF-specific\n\/\/ variations like different initial state. Might be able to deduplicate\n\/\/ some day, but also want to make sure that the Mach-O use case is served.\n\/\/\n\/\/ This class has a deliberately small interface, since a lot of\n\/\/ implementation variation is possible.\n\/\/\n\/\/ TODO: Use an ordered container with a suffix-based comparison in order\n\/\/ to deduplicate suffixes. std::map<> with a custom comparator is likely\n\/\/ to be the simplest implementation, but a suffix trie could be more\n\/\/ suitable for the job.\nclass StringTableBuilder {\n \/\/\/ \\brief Indices of strings currently present in `Buf`.\n StringMap StringIndices;\n \/\/\/ \\brief The contents of the string table as we build it.\n std::string Buf;\npublic:\n StringTableBuilder() {\n Buf.push_back('\\0');\n }\n \/\/\/ \\returns Index of string in string table.\n unsigned addString(StringRef S) {\n StringMapEntry &Entry = StringIndices.GetOrCreateValue(S);\n unsigned &I = Entry.getValue();\n if (I != 0)\n return I;\n I = Buf.size();\n Buf.append(S.begin(), S.end());\n Buf.push_back('\\0');\n return I;\n }\n size_t size() const {\n return Buf.size();\n }\n void writeToStream(raw_ostream &OS) {\n OS.write(Buf.data(), Buf.size());\n }\n};\n\n\/\/ This class is used to build up a contiguous binary blob while keeping\n\/\/ track of an offset in the output (which notionally begins at\n\/\/ `InitialOffset`).\nclass ContiguousBlobAccumulator {\n const uint64_t InitialOffset;\n raw_svector_ostream OS;\n\npublic:\n ContiguousBlobAccumulator(uint64_t InitialOffset_, SmallVectorImpl &Buf)\n : InitialOffset(InitialOffset_), OS(Buf) {}\n raw_ostream &getOS() { return OS; }\n uint64_t currentOffset() const { return InitialOffset + OS.tell(); }\n void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }\n};\n\n\/\/ Used to keep track of section names, so that in the YAML file sections\n\/\/ can be referenced by name instead of by index.\nclass SectionNameToIdxMap {\n StringMap Map;\npublic:\n \/\/\/ \\returns true if name is already present in the map.\n bool addName(StringRef SecName, unsigned i) {\n StringMapEntry &Entry = Map.GetOrCreateValue(SecName, -1);\n if (Entry.getValue() != -1)\n return true;\n Entry.setValue((int)i);\n return false;\n }\n \/\/\/ \\returns true if name is not present in the map\n bool lookupSection(StringRef SecName, unsigned &Idx) const {\n StringMap::const_iterator I = Map.find(SecName);\n if (I == Map.end())\n return true;\n Idx = I->getValue();\n return false;\n }\n};\n\ntemplate \nstatic size_t vectorDataSize(const std::vector &Vec) {\n return Vec.size() * sizeof(T);\n}\n\ntemplate \nstatic void writeVectorData(raw_ostream &OS, const std::vector &Vec) {\n OS.write((const char *)Vec.data(), vectorDataSize(Vec));\n}\n\ntemplate \nstatic void zero(T &Obj) {\n memset(&Obj, 0, sizeof(Obj));\n}\n\ntemplate \nstatic void writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {\n using namespace llvm::ELF;\n using namespace llvm::object;\n typedef typename ELFObjectFile::Elf_Ehdr Elf_Ehdr;\n typedef typename ELFObjectFile::Elf_Shdr Elf_Shdr;\n\n const ELFYAML::FileHeader &Hdr = Doc.Header;\n\n Elf_Ehdr Header;\n zero(Header);\n Header.e_ident[EI_MAG0] = 0x7f;\n Header.e_ident[EI_MAG1] = 'E';\n Header.e_ident[EI_MAG2] = 'L';\n Header.e_ident[EI_MAG3] = 'F';\n Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;\n bool IsLittleEndian = ELFT::TargetEndianness == support::little;\n Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;\n Header.e_ident[EI_VERSION] = EV_CURRENT;\n \/\/ TODO: Implement ELF_ELFOSABI enum.\n Header.e_ident[EI_OSABI] = ELFOSABI_NONE;\n \/\/ TODO: Implement ELF_ABIVERSION enum.\n Header.e_ident[EI_ABIVERSION] = 0;\n Header.e_type = Hdr.Type;\n Header.e_machine = Hdr.Machine;\n Header.e_version = EV_CURRENT;\n Header.e_entry = Hdr.Entry;\n Header.e_ehsize = sizeof(Elf_Ehdr);\n\n \/\/ TODO: Flesh out section header support.\n \/\/ TODO: Program headers.\n\n Header.e_shentsize = sizeof(Elf_Shdr);\n \/\/ Immediately following the ELF header.\n Header.e_shoff = sizeof(Header);\n std::vector Sections = Doc.Sections;\n if (Sections.empty() || Sections.front().Type != SHT_NULL) {\n ELFYAML::Section S;\n S.Type = SHT_NULL;\n zero(S.Flags);\n Sections.insert(Sections.begin(), S);\n }\n \/\/ \"+ 1\" for string table.\n Header.e_shnum = Sections.size() + 1;\n \/\/ Place section header string table last.\n Header.e_shstrndx = Sections.size();\n\n SectionNameToIdxMap SN2I;\n for (unsigned i = 0, e = Sections.size(); i != e; ++i) {\n StringRef Name = Sections[i].Name;\n if (Name.empty())\n continue;\n if (SN2I.addName(Name, i)) {\n errs() << \"error: Repeated section name: '\" << Name\n << \"' at YAML section number \" << i << \".\\n\";\n return;\n }\n }\n\n StringTableBuilder StrTab;\n SmallVector Buf;\n \/\/ XXX: This offset is tightly coupled with the order that we write\n \/\/ things to `OS`.\n const size_t SectionContentBeginOffset =\n Header.e_ehsize + Header.e_shentsize * Header.e_shnum;\n ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);\n std::vector SHeaders;\n for (unsigned i = 0, e = Sections.size(); i != e; ++i) {\n const ELFYAML::Section &Sec = Sections[i];\n Elf_Shdr SHeader;\n zero(SHeader);\n SHeader.sh_name = StrTab.addString(Sec.Name);\n SHeader.sh_type = Sec.Type;\n SHeader.sh_flags = Sec.Flags;\n SHeader.sh_addr = Sec.Address;\n\n SHeader.sh_offset = CBA.currentOffset();\n SHeader.sh_size = Sec.Content.binary_size();\n Sec.Content.writeAsBinary(CBA.getOS());\n\n if (!Sec.Link.empty()) {\n unsigned Index;\n if (SN2I.lookupSection(Sec.Link, Index)) {\n errs() << \"error: Unknown section referenced: '\" << Sec.Link\n << \"' at YAML section number \" << i << \".\\n\";\n return;\n }\n SHeader.sh_link = Index;\n }\n SHeader.sh_info = 0;\n SHeader.sh_addralign = Sec.AddressAlign;\n SHeader.sh_entsize = 0;\n SHeaders.push_back(SHeader);\n }\n\n \/\/ String table header.\n Elf_Shdr StrTabSHeader;\n zero(StrTabSHeader);\n StrTabSHeader.sh_name = 0;\n StrTabSHeader.sh_type = SHT_STRTAB;\n StrTabSHeader.sh_flags = 0;\n StrTabSHeader.sh_addr = 0;\n StrTabSHeader.sh_offset = CBA.currentOffset();\n StrTabSHeader.sh_size = StrTab.size();\n StrTab.writeToStream(CBA.getOS());\n StrTabSHeader.sh_link = 0;\n StrTabSHeader.sh_info = 0;\n StrTabSHeader.sh_addralign = 1;\n StrTabSHeader.sh_entsize = 0;\n\n OS.write((const char *)&Header, sizeof(Header));\n writeVectorData(OS, SHeaders);\n OS.write((const char *)&StrTabSHeader, sizeof(StrTabSHeader));\n CBA.writeBlobToStream(OS);\n}\n\nint yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {\n yaml::Input YIn(Buf->getBuffer());\n ELFYAML::Object Doc;\n YIn >> Doc;\n if (YIn.error()) {\n errs() << \"yaml2obj: Failed to parse YAML file!\\n\";\n return 1;\n }\n if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {\n if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))\n writeELF >(outs(), Doc);\n else\n writeELF >(outs(), Doc);\n } else {\n if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))\n writeELF >(outs(), Doc);\n else\n writeELF >(outs(), Doc);\n }\n\n return 0;\n}\n[yaml2obj] Move some classes into anonymous namespaces.\/\/===- yaml2elf - Convert YAML to a ELF object file -----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief The ELF component of yaml2obj.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"yaml2obj.h\"\n#include \"llvm\/Object\/ELF.h\"\n#include \"llvm\/Object\/ELFYAML.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/YAMLTraits.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace llvm;\n\n\/\/ There is similar code in yaml2coff, but with some slight COFF-specific\n\/\/ variations like different initial state. Might be able to deduplicate\n\/\/ some day, but also want to make sure that the Mach-O use case is served.\n\/\/\n\/\/ This class has a deliberately small interface, since a lot of\n\/\/ implementation variation is possible.\n\/\/\n\/\/ TODO: Use an ordered container with a suffix-based comparison in order\n\/\/ to deduplicate suffixes. std::map<> with a custom comparator is likely\n\/\/ to be the simplest implementation, but a suffix trie could be more\n\/\/ suitable for the job.\nnamespace {\nclass StringTableBuilder {\n \/\/\/ \\brief Indices of strings currently present in `Buf`.\n StringMap StringIndices;\n \/\/\/ \\brief The contents of the string table as we build it.\n std::string Buf;\npublic:\n StringTableBuilder() {\n Buf.push_back('\\0');\n }\n \/\/\/ \\returns Index of string in string table.\n unsigned addString(StringRef S) {\n StringMapEntry &Entry = StringIndices.GetOrCreateValue(S);\n unsigned &I = Entry.getValue();\n if (I != 0)\n return I;\n I = Buf.size();\n Buf.append(S.begin(), S.end());\n Buf.push_back('\\0');\n return I;\n }\n size_t size() const {\n return Buf.size();\n }\n void writeToStream(raw_ostream &OS) {\n OS.write(Buf.data(), Buf.size());\n }\n};\n} \/\/ end anonymous namespace\n\n\/\/ This class is used to build up a contiguous binary blob while keeping\n\/\/ track of an offset in the output (which notionally begins at\n\/\/ `InitialOffset`).\nnamespace {\nclass ContiguousBlobAccumulator {\n const uint64_t InitialOffset;\n raw_svector_ostream OS;\n\npublic:\n ContiguousBlobAccumulator(uint64_t InitialOffset_, SmallVectorImpl &Buf)\n : InitialOffset(InitialOffset_), OS(Buf) {}\n raw_ostream &getOS() { return OS; }\n uint64_t currentOffset() const { return InitialOffset + OS.tell(); }\n void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }\n};\n} \/\/ end anonymous namespace\n\n\/\/ Used to keep track of section names, so that in the YAML file sections\n\/\/ can be referenced by name instead of by index.\nnamespace {\nclass SectionNameToIdxMap {\n StringMap Map;\npublic:\n \/\/\/ \\returns true if name is already present in the map.\n bool addName(StringRef SecName, unsigned i) {\n StringMapEntry &Entry = Map.GetOrCreateValue(SecName, -1);\n if (Entry.getValue() != -1)\n return true;\n Entry.setValue((int)i);\n return false;\n }\n \/\/\/ \\returns true if name is not present in the map\n bool lookupSection(StringRef SecName, unsigned &Idx) const {\n StringMap::const_iterator I = Map.find(SecName);\n if (I == Map.end())\n return true;\n Idx = I->getValue();\n return false;\n }\n};\n} \/\/ end anonymous namespace\n\ntemplate \nstatic size_t vectorDataSize(const std::vector &Vec) {\n return Vec.size() * sizeof(T);\n}\n\ntemplate \nstatic void writeVectorData(raw_ostream &OS, const std::vector &Vec) {\n OS.write((const char *)Vec.data(), vectorDataSize(Vec));\n}\n\ntemplate \nstatic void zero(T &Obj) {\n memset(&Obj, 0, sizeof(Obj));\n}\n\ntemplate \nstatic void writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {\n using namespace llvm::ELF;\n using namespace llvm::object;\n typedef typename ELFObjectFile::Elf_Ehdr Elf_Ehdr;\n typedef typename ELFObjectFile::Elf_Shdr Elf_Shdr;\n\n const ELFYAML::FileHeader &Hdr = Doc.Header;\n\n Elf_Ehdr Header;\n zero(Header);\n Header.e_ident[EI_MAG0] = 0x7f;\n Header.e_ident[EI_MAG1] = 'E';\n Header.e_ident[EI_MAG2] = 'L';\n Header.e_ident[EI_MAG3] = 'F';\n Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;\n bool IsLittleEndian = ELFT::TargetEndianness == support::little;\n Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;\n Header.e_ident[EI_VERSION] = EV_CURRENT;\n \/\/ TODO: Implement ELF_ELFOSABI enum.\n Header.e_ident[EI_OSABI] = ELFOSABI_NONE;\n \/\/ TODO: Implement ELF_ABIVERSION enum.\n Header.e_ident[EI_ABIVERSION] = 0;\n Header.e_type = Hdr.Type;\n Header.e_machine = Hdr.Machine;\n Header.e_version = EV_CURRENT;\n Header.e_entry = Hdr.Entry;\n Header.e_ehsize = sizeof(Elf_Ehdr);\n\n \/\/ TODO: Flesh out section header support.\n \/\/ TODO: Program headers.\n\n Header.e_shentsize = sizeof(Elf_Shdr);\n \/\/ Immediately following the ELF header.\n Header.e_shoff = sizeof(Header);\n std::vector Sections = Doc.Sections;\n if (Sections.empty() || Sections.front().Type != SHT_NULL) {\n ELFYAML::Section S;\n S.Type = SHT_NULL;\n zero(S.Flags);\n Sections.insert(Sections.begin(), S);\n }\n \/\/ \"+ 1\" for string table.\n Header.e_shnum = Sections.size() + 1;\n \/\/ Place section header string table last.\n Header.e_shstrndx = Sections.size();\n\n SectionNameToIdxMap SN2I;\n for (unsigned i = 0, e = Sections.size(); i != e; ++i) {\n StringRef Name = Sections[i].Name;\n if (Name.empty())\n continue;\n if (SN2I.addName(Name, i)) {\n errs() << \"error: Repeated section name: '\" << Name\n << \"' at YAML section number \" << i << \".\\n\";\n return;\n }\n }\n\n StringTableBuilder StrTab;\n SmallVector Buf;\n \/\/ XXX: This offset is tightly coupled with the order that we write\n \/\/ things to `OS`.\n const size_t SectionContentBeginOffset =\n Header.e_ehsize + Header.e_shentsize * Header.e_shnum;\n ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);\n std::vector SHeaders;\n for (unsigned i = 0, e = Sections.size(); i != e; ++i) {\n const ELFYAML::Section &Sec = Sections[i];\n Elf_Shdr SHeader;\n zero(SHeader);\n SHeader.sh_name = StrTab.addString(Sec.Name);\n SHeader.sh_type = Sec.Type;\n SHeader.sh_flags = Sec.Flags;\n SHeader.sh_addr = Sec.Address;\n\n SHeader.sh_offset = CBA.currentOffset();\n SHeader.sh_size = Sec.Content.binary_size();\n Sec.Content.writeAsBinary(CBA.getOS());\n\n if (!Sec.Link.empty()) {\n unsigned Index;\n if (SN2I.lookupSection(Sec.Link, Index)) {\n errs() << \"error: Unknown section referenced: '\" << Sec.Link\n << \"' at YAML section number \" << i << \".\\n\";\n return;\n }\n SHeader.sh_link = Index;\n }\n SHeader.sh_info = 0;\n SHeader.sh_addralign = Sec.AddressAlign;\n SHeader.sh_entsize = 0;\n SHeaders.push_back(SHeader);\n }\n\n \/\/ String table header.\n Elf_Shdr StrTabSHeader;\n zero(StrTabSHeader);\n StrTabSHeader.sh_name = 0;\n StrTabSHeader.sh_type = SHT_STRTAB;\n StrTabSHeader.sh_flags = 0;\n StrTabSHeader.sh_addr = 0;\n StrTabSHeader.sh_offset = CBA.currentOffset();\n StrTabSHeader.sh_size = StrTab.size();\n StrTab.writeToStream(CBA.getOS());\n StrTabSHeader.sh_link = 0;\n StrTabSHeader.sh_info = 0;\n StrTabSHeader.sh_addralign = 1;\n StrTabSHeader.sh_entsize = 0;\n\n OS.write((const char *)&Header, sizeof(Header));\n writeVectorData(OS, SHeaders);\n OS.write((const char *)&StrTabSHeader, sizeof(StrTabSHeader));\n CBA.writeBlobToStream(OS);\n}\n\nint yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {\n yaml::Input YIn(Buf->getBuffer());\n ELFYAML::Object Doc;\n YIn >> Doc;\n if (YIn.error()) {\n errs() << \"yaml2obj: Failed to parse YAML file!\\n\";\n return 1;\n }\n if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {\n if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))\n writeELF >(outs(), Doc);\n else\n writeELF >(outs(), Doc);\n } else {\n if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))\n writeELF >(outs(), Doc);\n else\n writeELF >(outs(), Doc);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"FancyMeshComponent.hpp\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace FancyMeshPlugin\n{\n FancyMeshComponent::FancyMeshComponent( const std::string& name )\n : Ra::Engine::Component( name )\n {\n }\n\n FancyMeshComponent::~FancyMeshComponent()\n {\n \/\/ TODO(Charly): Should we ask the RO manager to delete our render object ?\n }\n\n void FancyMeshComponent::initialize()\n {\n }\n\n void FancyMeshComponent::addMeshRenderObject( const Ra::Core::TriangleMesh& mesh, const std::string& name )\n {\n Ra::Engine::RenderTechnique* technique = new Ra::Engine::RenderTechnique;\n technique->material = new Ra::Engine::Material( \"Default\" );\n technique->shaderConfig = Ra::Engine::ShaderConfiguration( \"Default\", \"..\/Shaders\" );\n\n addMeshRenderObject(mesh, name, technique);\n }\n\n void FancyMeshComponent::addMeshRenderObject( const Ra::Core::TriangleMesh& mesh,\n const std::string& name,\n Ra::Engine::RenderTechnique* technique )\n {\n Ra::Engine::RenderObject* renderObject = new Ra::Engine::RenderObject( name, this, Ra::Engine::RenderObjectType::FANCY );\n renderObject->setVisible( true );\n\n renderObject->setRenderTechnique( technique );\n\n std::shared_ptr displayMesh( new Ra::Engine::Mesh( name ) );\n std::vector indices;\n indices.reserve( mesh.m_triangles.size() * 3 );\n for ( const auto& i : mesh.m_triangles )\n {\n indices.push_back( i.x() );\n indices.push_back( i.y() );\n indices.push_back( i.z() );\n }\n\n displayMesh->loadGeometry( mesh.m_vertices, indices );\n displayMesh->addData( Ra::Engine::Mesh::VERTEX_NORMAL, mesh.m_normals );\n\n renderObject->setMesh( displayMesh );\n\n addRenderObject( renderObject );\n }\n\n void FancyMeshComponent::handleMeshLoading( const Ra::Asset::GeometryData* data )\n {\n std::string name( m_name );\n std::string roName;\n std::string meshName;\n std::string matName;\n\n if ( data->getName() == \"\" )\n {\n name = m_name;\n \n roName = name + \"_RO\";\n meshName = name + \"_Mesh\";\n matName = name + \"_Mat\";\n }\n else\n {\n name = data->getName();\n roName = name;\n meshName = name;\n matName = name + \"_Mat\";\n m_name = m_name + \"|\" + data->getName();\n }\n\n Ra::Engine::RenderObject* renderObject = new Ra::Engine::RenderObject( roName, this, Ra::Engine::RenderObjectType::FANCY );\n renderObject->setVisible( true );\n renderObject->setLocalTransform( data->getFrame() );\n\n Ra::Engine::RenderObject* renderObject = new Ra::Engine::RenderObject( roName, this, Ra::Engine::RenderObjectType::FANCY );\n renderObject->setVisible( true );\n renderObject->setLocalTransform( data->getFrame() );\n\n\n m_mesh.clear();\n for( const auto& v : data->getVertices() ) \n {\n m_mesh.m_vertices.push_back( data->getFrame() * v );\n }\n for( const auto& face : data->getFaces() ) {\n m_mesh.m_triangles.push_back( Ra::Core::Vector3i( face[0], face[1], face[2] ) );\n }\n Ra::Core::Geometry::areaWeightedNormal( m_mesh.m_vertices, m_mesh.m_triangles, m_mesh.m_normals );\n\n\n \/\/ FIXME(Charly): Find a cleaner way to build geometry\n std::vector indices;\n for ( const auto& face : data->getFaces() )\n {\n indices.push_back( face[0] );\n indices.push_back( face[1] );\n indices.push_back( face[2] );\n }\n\n Ra::Core::Vector3Array positions;\n Ra::Core::Vector3Array normals;\n Ra::Core::Vector4Array tangents;\n Ra::Core::Vector4Array bitangents;\n Ra::Core::Vector4Array texcoords;\n Ra::Core::Vector4Array colors;\n\n positions = m_mesh.m_vertices;\n normals = m_mesh.m_normals;\n for ( const auto& v : data->getTangents() ) tangents.push_back( v );\n for ( const auto& v : data->getBiTangents() ) bitangents.push_back( v );\n for ( const auto& v : data->getTexCoords() ) texcoords.push_back( v );\n for ( const auto& v : data->getColors() ) colors.push_back( v );\n\n mesh->loadGeometry( positions, indices );\n\n\n mesh->addData( Ra::Engine::Mesh::VERTEX_NORMAL, normals );\n mesh->addData( Ra::Engine::Mesh::VERTEX_TANGENT, tangents );\n mesh->addData( Ra::Engine::Mesh::VERTEX_BITANGENT, bitangents );\n mesh->addData( Ra::Engine::Mesh::VERTEX_TEXCOORD, texcoords );\n mesh->addData( Ra::Engine::Mesh::VERTEX_COLOR, colors );\n \/\/ FIXME(Charly): Should not weights be part of the geometry ?\n \/\/ mesh->addData( Ra::Engine::Mesh::VERTEX_WEIGHTS, meshData.weights );\n\n renderObject->setMesh( mesh );\n\n m_meshIndex = addRenderObject(renderObject);\n\n \/\/ FIXME(Charly)\n \/\/ Build m_mesh\n \/\/ int triangleCount = meshData.indices.size() \/ 3;\n \/\/ int vertexCount = meshData.positions.size();\n \/\/ m_mesh.m_vertices.resize(vertexCount);\n \/\/ m_mesh.m_normals.resize(vertexCount);\n \/\/ m_mesh.m_triangles.resize(triangleCount);\n\n \/\/ for (int i = 0; i < vertexCount; i++)\n \/\/ {\n \/\/ Ra::Core::Vector4 pos = meshData.positions[i];\n \/\/ Ra::Core::Vector4 normals = meshData.normals[i];\n \/\/ m_mesh.m_vertices[i] = Ra::Core::Vector3(pos(0), pos(1), pos(2));\n \/\/ m_mesh.m_normals[i] = Ra::Core::Vector3(normals(0), normals(1), normals(2));\n \/\/ }\n\n \/\/ for (int i = 0; i < triangleCount; i++)\n \/\/ m_mesh.m_triangles[i] = Ra::Core::Triangle(meshData.indices[i * 3], meshData.indices[i * 3 + 1], meshData.indices[i * 3 + 2]);\n\n Ra::Engine::RenderTechnique* rt = new Ra::Engine::RenderTechnique;\n Ra::Engine::Material* mat = new Ra::Engine::Material( matName );\n auto m = data->getMaterial();\n if ( m.hasDiffuse() ) mat->setKd( m.m_diffuse );\n if ( m.hasSpecular() ) mat->setKs( m.m_specular );\n if ( m.hasShininess() ) mat->setNs( m.m_shininess );\n if ( m.hasDiffuseTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_DIFFUSE, m.m_texDiffuse );\n if ( m.hasSpecularTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SPECULAR, m.m_texSpecular );\n if ( m.hasShininessTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SHININESS, m.m_texShininess );\n if ( m.hasOpacityTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_ALPHA, m.m_texOpacity );\n if ( m.hasNormalTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_NORMAL, m.m_texNormal );\n\n rt->material = mat;\n rt->shaderConfig = Ra::Engine::ShaderConfiguration( \"BlinnPhong\", \"..\/Shaders\" );\n\n renderObject->setRenderTechnique( rt );\n\n }\n\n Ra::Core::Index FancyMeshComponent::getMeshIndex() const\n {\n return m_meshIndex;\n }\n\n Ra::Core::TriangleMesh FancyMeshComponent::getMesh() const\n {\n return m_mesh;\n }\n\n void FancyMeshComponent::rayCastQuery( const Ra::Core::Ray& r) const\n {\n auto result = Ra::Core::MeshUtils::castRay( m_mesh, r );\n int tidx = result.m_hitTriangle;\n if (tidx >= 0)\n {\n LOG(logINFO) << \" Hit triangle \" << tidx;\n LOG(logINFO) << \" Nearest vertex \" << result.m_nearestVertex;\n }\n }\n\n} \/\/ namespace FancyMeshPlugin\ntexturing fully disabled#include \"FancyMeshComponent.hpp\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace FancyMeshPlugin\n{\n FancyMeshComponent::FancyMeshComponent( const std::string& name )\n : Ra::Engine::Component( name )\n {\n }\n\n FancyMeshComponent::~FancyMeshComponent()\n {\n \/\/ TODO(Charly): Should we ask the RO manager to delete our render object ?\n }\n\n void FancyMeshComponent::initialize()\n {\n }\n\n void FancyMeshComponent::addMeshRenderObject( const Ra::Core::TriangleMesh& mesh, const std::string& name )\n {\n Ra::Engine::RenderTechnique* technique = new Ra::Engine::RenderTechnique;\n technique->material = new Ra::Engine::Material( \"Default\" );\n technique->shaderConfig = Ra::Engine::ShaderConfiguration( \"Default\", \"..\/Shaders\" );\n\n addMeshRenderObject(mesh, name, technique);\n }\n\n void FancyMeshComponent::addMeshRenderObject( const Ra::Core::TriangleMesh& mesh,\n const std::string& name,\n Ra::Engine::RenderTechnique* technique )\n {\n Ra::Engine::RenderObject* renderObject = new Ra::Engine::RenderObject( name, this, Ra::Engine::RenderObjectType::FANCY );\n renderObject->setVisible( true );\n\n renderObject->setRenderTechnique( technique );\n\n std::shared_ptr displayMesh( new Ra::Engine::Mesh( name ) );\n std::vector indices;\n indices.reserve( mesh.m_triangles.size() * 3 );\n for ( const auto& i : mesh.m_triangles )\n {\n indices.push_back( i.x() );\n indices.push_back( i.y() );\n indices.push_back( i.z() );\n }\n\n displayMesh->loadGeometry( mesh.m_vertices, indices );\n displayMesh->addData( Ra::Engine::Mesh::VERTEX_NORMAL, mesh.m_normals );\n\n renderObject->setMesh( displayMesh );\n\n addRenderObject( renderObject );\n }\n\n void FancyMeshComponent::handleMeshLoading( const Ra::Asset::GeometryData* data )\n {\n std::string name( m_name );\n std::string roName;\n std::string meshName;\n std::string matName;\n\n if ( data->getName() == \"\" )\n {\n name = m_name;\n \n roName = name + \"_RO\";\n meshName = name + \"_Mesh\";\n matName = name + \"_Mat\";\n }\n else\n {\n name = data->getName();\n roName = name;\n meshName = name;\n matName = name + \"_Mat\";\n m_name = m_name + \"|\" + data->getName();\n }\n\n Ra::Engine::RenderObject* renderObject = new Ra::Engine::RenderObject( roName, this, Ra::Engine::RenderObjectType::FANCY );\n renderObject->setVisible( true );\n renderObject->setLocalTransform( data->getFrame() );\n\n Ra::Engine::RenderObject* renderObject = new Ra::Engine::RenderObject( roName, this, Ra::Engine::RenderObjectType::FANCY );\n renderObject->setVisible( true );\n renderObject->setLocalTransform( data->getFrame() );\n\n\n m_mesh.clear();\n for( const auto& v : data->getVertices() ) \n {\n m_mesh.m_vertices.push_back( data->getFrame() * v );\n }\n for( const auto& face : data->getFaces() ) {\n m_mesh.m_triangles.push_back( Ra::Core::Vector3i( face[0], face[1], face[2] ) );\n }\n Ra::Core::Geometry::uniformNormal( m_mesh.m_vertices, m_mesh.m_triangles, m_mesh.m_normals );\n\n\n \/\/ FIXME(Charly): Find a cleaner way to build geometry\n std::vector indices;\n for ( const auto& face : data->getFaces() )\n {\n indices.push_back( face[0] );\n indices.push_back( face[1] );\n indices.push_back( face[2] );\n }\n\n Ra::Core::Vector3Array positions;\n Ra::Core::Vector3Array normals;\n Ra::Core::Vector4Array tangents;\n Ra::Core::Vector4Array bitangents;\n Ra::Core::Vector4Array texcoords;\n Ra::Core::Vector4Array colors;\n\n positions = m_mesh.m_vertices;\n normals = m_mesh.m_normals;\n for ( const auto& v : data->getTangents() ) tangents.push_back( v );\n for ( const auto& v : data->getBiTangents() ) bitangents.push_back( v );\n for ( const auto& v : data->getTexCoords() ) texcoords.push_back( v );\n for ( const auto& v : data->getColors() ) colors.push_back( v );\n\n mesh->loadGeometry( positions, indices );\n\n\n mesh->addData( Ra::Engine::Mesh::VERTEX_NORMAL, normals );\n mesh->addData( Ra::Engine::Mesh::VERTEX_TANGENT, tangents );\n mesh->addData( Ra::Engine::Mesh::VERTEX_BITANGENT, bitangents );\n mesh->addData( Ra::Engine::Mesh::VERTEX_TEXCOORD, texcoords );\n mesh->addData( Ra::Engine::Mesh::VERTEX_COLOR, colors );\n \/\/ FIXME(Charly): Should not weights be part of the geometry ?\n \/\/ mesh->addData( Ra::Engine::Mesh::VERTEX_WEIGHTS, meshData.weights );\n\n renderObject->setMesh( mesh );\n\n m_meshIndex = addRenderObject(renderObject);\n\n \/\/ FIXME(Charly)\n \/\/ Build m_mesh\n \/\/ int triangleCount = meshData.indices.size() \/ 3;\n \/\/ int vertexCount = meshData.positions.size();\n \/\/ m_mesh.m_vertices.resize(vertexCount);\n \/\/ m_mesh.m_normals.resize(vertexCount);\n \/\/ m_mesh.m_triangles.resize(triangleCount);\n\n \/\/ for (int i = 0; i < vertexCount; i++)\n \/\/ {\n \/\/ Ra::Core::Vector4 pos = meshData.positions[i];\n \/\/ Ra::Core::Vector4 normals = meshData.normals[i];\n \/\/ m_mesh.m_vertices[i] = Ra::Core::Vector3(pos(0), pos(1), pos(2));\n \/\/ m_mesh.m_normals[i] = Ra::Core::Vector3(normals(0), normals(1), normals(2));\n \/\/ }\n\n \/\/ for (int i = 0; i < triangleCount; i++)\n \/\/ m_mesh.m_triangles[i] = Ra::Core::Triangle(meshData.indices[i * 3], meshData.indices[i * 3 + 1], meshData.indices[i * 3 + 2]);\n\n Ra::Engine::RenderTechnique* rt = new Ra::Engine::RenderTechnique;\n Ra::Engine::Material* mat = new Ra::Engine::Material( matName );\n auto m = data->getMaterial();\n if ( m.hasDiffuse() ) mat->setKd( m.m_diffuse );\n if ( m.hasSpecular() ) mat->setKs( m.m_specular );\n if ( m.hasShininess() ) mat->setNs( m.m_shininess );\n \/\/if ( m.hasDiffuseTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_DIFFUSE, m.m_texDiffuse );\n \/\/if ( m.hasSpecularTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SPECULAR, m.m_texSpecular );\n \/\/if ( m.hasShininessTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_SHININESS, m.m_texShininess );\n \/\/if ( m.hasOpacityTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_ALPHA, m.m_texOpacity );\n \/\/if ( m.hasNormalTexture() ) mat->addTexture( Ra::Engine::Material::TextureType::TEX_NORMAL, m.m_texNormal );\n\n rt->material = mat;\n rt->shaderConfig = Ra::Engine::ShaderConfiguration( \"BlinnPhong\", \"..\/Shaders\" );\n\n renderObject->setRenderTechnique( rt );\n\n }\n\n Ra::Core::Index FancyMeshComponent::getMeshIndex() const\n {\n return m_meshIndex;\n }\n\n Ra::Core::TriangleMesh FancyMeshComponent::getMesh() const\n {\n return m_mesh;\n }\n\n void FancyMeshComponent::rayCastQuery( const Ra::Core::Ray& r) const\n {\n auto result = Ra::Core::MeshUtils::castRay( m_mesh, r );\n int tidx = result.m_hitTriangle;\n if (tidx >= 0)\n {\n LOG(logINFO) << \" Hit triangle \" << tidx;\n LOG(logINFO) << \" Nearest vertex \" << result.m_nearestVertex;\n }\n }\n\n} \/\/ namespace FancyMeshPlugin\n<|endoftext|>"} {"text":"\/\/ REQUIRES: static-analyzer\n\/\/ RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s\nextern void *malloc(unsigned long);\nextern void free(void *);\n\nvoid f() {\n int *p = new int(42);\n delete p;\n delete p;\n \/\/ CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete]\n}\n\nvoid g() {\n void *q = malloc(132);\n free(q);\n free(q);\n \/\/ CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]\n}\nFix a lit test failure after MallocChecker changes\/\/ REQUIRES: static-analyzer\n\/\/ RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s\nextern void *malloc(unsigned long);\nextern void free(void *);\n\nvoid f() {\n int *p = new int(42);\n delete p;\n delete p;\n \/\/ CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete]\n}\n\nvoid g() {\n void *q = malloc(132);\n free(q);\n free(q);\n \/\/ CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nusing namespace osgIntrospection;\n\n\n\/\/ borrowed from osgDB...\nstd::string createLibraryNameForWrapper(const std::string& ext)\n{\n#if defined(WIN32)\n \/\/ !! recheck evolving Cygwin DLL extension naming protocols !! NHV\n #ifdef __CYGWIN__\n return \"cygosgwrapper_\"+ext+\".dll\";\n #elif defined(__MINGW32__)\n return \"libosgwrapper_\"+ext+\".dll\";\n #else\n #ifdef _DEBUG\n return \"osgwrapper_\"+ext+\"d.dll\";\n #else\n return \"osgwrapper_\"+ext+\".dll\";\n #endif\n #endif\n#elif macintosh\n return \"osgwrapper_\"+ext;\n#elif defined(__hpux__)\n \/\/ why don't we use PLUGIN_EXT from the makefiles here?\n return \"osgwrapper_\"+ext+\".sl\";\n#else\n return \"osgwrapper_\"+ext+\".so\";\n#endif\n\n}\n\nbool type_order(const Type *v1, const Type *v2)\n{\n if (!v1->isDefined()) return v2->isDefined();\n if (!v2->isDefined()) return false;\n return v1->getQualifiedName().compare(v2->getQualifiedName()) < 0;\n}\n\nvoid print_types()\n{\n \/\/ get the map of types that have been reflected\n const TypeMap &tm = Reflection::getTypes();\n \n \/\/ create a sortable list of types\n TypeList types(tm.size());\n TypeList::iterator j = types.begin();\n for (TypeMap::const_iterator i=tm.begin(); i!=tm.end(); ++i, ++j)\n *j = i->second;\n \n \/\/ sort the map\n std::sort(types.begin(), types.end(), &type_order);\n\n \/\/ iterate through the type map and display some\n \/\/ details for each type\n for (TypeList::const_iterator i=types.begin(); i!=types.end(); ++i)\n {\n \/\/ ignore pointer types and undefined types\n if (!(*i)->isDefined() || (*i)->isPointer() || (*i)->isReference())\n continue;\n\n \/\/ print the type name\n std::cout << (*i)->getQualifiedName() << \"\\n\";\n\n \/\/ check whether the type is abstract\n if ((*i)->isAbstract()) std::cout << \"\\t[abstract]\\n\";\n\n \/\/ check whether the type is atomic\n if ((*i)->isAtomic()) std::cout << \"\\t[atomic]\\n\";\n\n \/\/ check whether the type is an enumeration. If yes, display\n \/\/ the list of enumeration labels\n if ((*i)->isEnum()) \n {\n std::cout << \"\\t[enum]\\n\";\n std::cout << \"\\tenumeration values:\\n\";\n const EnumLabelMap &emap = (*i)->getEnumLabels();\n for (EnumLabelMap::const_iterator j=emap.begin(); j!=emap.end(); ++j)\n {\n std::cout << \"\\t\\t\" << j->second << \" = \" << j->first << \"\\n\";\n }\n }\n\n \/\/ if the type has one or more base types, then display their\n \/\/ names\n if ((*i)->getNumBaseTypes() > 0)\n {\n std::cout << \"\\tderived from: \";\n for (int j=0; j<(*i)->getNumBaseTypes(); ++j)\n {\n const Type &base = (*i)->getBaseType(j);\n if (base.isDefined())\n std::cout << base.getQualifiedName() << \" \";\n else\n std::cout << \"[undefined type] \";\n }\n std::cout << \"\\n\";\n }\n\n \/\/ display a list of methods defined for the current type\n const MethodInfoList &mil = (*i)->getMethods();\n if (!mil.empty())\n {\n std::cout << \"\\t* methods:\\n\";\n for (MethodInfoList::const_iterator j=mil.begin(); j!=mil.end(); ++j)\n {\n \/\/ get the MethodInfo object that describes the current\n \/\/ method\n const MethodInfo &mi = **j;\n\n std::cout << \"\\t \";\n\n \/\/ display if the method is virtual\n if (mi.isVirtual())\n std::cout << \"virtual \";\n\n \/\/ display the method's return type if defined\n if (mi.getReturnType().isDefined())\n std::cout << mi.getReturnType().getQualifiedName() << \" \";\n else\n std::cout << \"[UNDEFINED TYPE] \";\n\n \/\/ display the method's name\n std::cout << mi.getName() << \"(\";\n\n \/\/ display method's parameters\n const ParameterInfoList ¶ms = mi.getParameters();\n for (ParameterInfoList::const_iterator k=params.begin(); k!=params.end(); ++k)\n {\n \/\/ get the ParameterInfo object that describes the \n \/\/ current parameter\n const ParameterInfo &pi = **k;\n\n \/\/ display the parameter's modifier\n if (pi.isIn())\n std::cout << \"IN\";\n if (pi.isOut())\n std::cout << \"OUT\";\n if (pi.isIn() || pi.isOut())\n std::cout << \" \";\n\n \/\/ display the parameter's type name\n if (pi.getParameterType().isDefined())\n std::cout << pi.getParameterType().getQualifiedName();\n\n \/\/ display the parameter's name if defined\n if (!pi.getName().empty())\n std::cout << \" \" << pi.getName();\n\n if ((k+1)!=params.end())\n std::cout << \", \";\n }\n std::cout << \")\";\n if (mi.isConst())\n std::cout << \" const\";\n if (mi.isPureVirtual())\n std::cout << \" = 0\";\n std::cout << \"\\n\";\n }\n }\n\n \/\/ display a list of properties defined for the current type\n const PropertyInfoList &pil = (*i)->getProperties();\n if (!pil.empty())\n {\n std::cout << \"\\t* properties:\\n\";\n for (PropertyInfoList::const_iterator j=pil.begin(); j!=pil.end(); ++j)\n {\n \/\/ get the PropertyInfo object that describes the current\n \/\/ property\n const PropertyInfo &pi = **j;\n\n std::cout << \"\\t \";\n\n std::cout << \"{\";\n std::cout << (pi.canGet()? \"G\": \" \");\n std::cout << (pi.canSet()? \"S\": \" \");\n std::cout << (pi.canCount()? \"C\": \" \");\n std::cout << (pi.canAdd()? \"A\": \" \");\n std::cout << \"} \";\n\n \/\/ display the property's name\n std::cout << pi.getName();\n\n \/\/ display the property's value type if defined\n std::cout << \" (\";\n if (pi.getPropertyType().isDefined())\n std::cout << pi.getPropertyType().getQualifiedName();\n else\n std::cout << \"UNDEFINED TYPE\";\n std::cout << \") \";\n\n \/\/ check whether the property is an array property\n if (pi.isArray())\n {\n std::cout << \" [ARRAY]\";\n }\n\n \/\/ check whether the property is an indexed property\n if (pi.isIndexed())\n {\n std::cout << \" [INDEXED]\\n\\t\\t indices:\\n\";\n\n const ParameterInfoList &ind = pi.getIndexParameters();\n\n \/\/ print the list of indices\n int num = 1;\n for (ParameterInfoList::const_iterator k=ind.begin(); k!=ind.end(); ++k, ++num)\n {\n std::cout << \"\\t\\t \" << num << \") \";\n const ParameterInfo &par = **k;\n std::cout << par.getParameterType().getQualifiedName() << \" \" << par.getName();\n std::cout << \"\\n\";\n }\n }\n\n std::cout << \"\\n\";\n }\n }\n std::cout << \"\\n\" << std::string(75, '-') << \"\\n\";\n }\n}\n\nint main()\n{\n \/\/ load the library of wrappers that reflect the \n \/\/ classes defined in the 'osg' namespace. In the\n \/\/ future this will be done automatically under\n \/\/ certain circumstances (like deserialization).\n osg::ref_ptr osg_reflectors = \n osgDB::DynamicLibrary::loadLibrary(createLibraryNameForWrapper(\"osg\"));\n \n \/\/ display a detailed list of reflected types\n try\n {\n print_types();\n }\n catch(const osgIntrospection::Exception &e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n return 0;\n}\n\nFrom Mike Wittman, updates to support new protected method support#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nusing namespace osgIntrospection;\n\n\n\/\/ borrowed from osgDB...\nstd::string createLibraryNameForWrapper(const std::string& ext)\n{\n#if defined(WIN32)\n \/\/ !! recheck evolving Cygwin DLL extension naming protocols !! NHV\n #ifdef __CYGWIN__\n return \"cygosgwrapper_\"+ext+\".dll\";\n #elif defined(__MINGW32__)\n return \"libosgwrapper_\"+ext+\".dll\";\n #else\n #ifdef _DEBUG\n return \"osgwrapper_\"+ext+\"d.dll\";\n #else\n return \"osgwrapper_\"+ext+\".dll\";\n #endif\n #endif\n#elif macintosh\n return \"osgwrapper_\"+ext;\n#elif defined(__hpux__)\n \/\/ why don't we use PLUGIN_EXT from the makefiles here?\n return \"osgwrapper_\"+ext+\".sl\";\n#else\n return \"osgwrapper_\"+ext+\".so\";\n#endif\n\n}\n\nbool type_order(const Type *v1, const Type *v2)\n{\n if (!v1->isDefined()) return v2->isDefined();\n if (!v2->isDefined()) return false;\n return v1->getQualifiedName().compare(v2->getQualifiedName()) < 0;\n}\n\nvoid print_method(const MethodInfo &mi)\n{\n std::cout << \"\\t \";\n\n \/\/ display if the method is virtual\n if (mi.isVirtual())\n std::cout << \"virtual \";\n\n \/\/ display the method's return type if defined\n if (mi.getReturnType().isDefined())\n std::cout << mi.getReturnType().getQualifiedName() << \" \";\n else\n std::cout << \"[UNDEFINED TYPE] \";\n\n \/\/ display the method's name\n std::cout << mi.getName() << \"(\";\n\n \/\/ display method's parameters\n const ParameterInfoList ¶ms = mi.getParameters();\n for (ParameterInfoList::const_iterator k=params.begin(); k!=params.end(); ++k)\n {\n \/\/ get the ParameterInfo object that describes the \n \/\/ current parameter\n const ParameterInfo &pi = **k;\n\n \/\/ display the parameter's modifier\n if (pi.isIn())\n std::cout << \"IN\";\n if (pi.isOut())\n std::cout << \"OUT\";\n if (pi.isIn() || pi.isOut())\n std::cout << \" \";\n\n \/\/ display the parameter's type name\n if (pi.getParameterType().isDefined())\n std::cout << pi.getParameterType().getQualifiedName();\n\n \/\/ display the parameter's name if defined\n if (!pi.getName().empty())\n std::cout << \" \" << pi.getName();\n\n if ((k+1)!=params.end())\n std::cout << \", \";\n }\n std::cout << \")\";\n if (mi.isConst())\n std::cout << \" const\";\n if (mi.isPureVirtual())\n std::cout << \" = 0\";\n std::cout << \"\\n\";\n}\n\nvoid print_type(const Type &type)\n{\n \/\/ ignore pointer types and undefined types\n if (!type.isDefined() || type.isPointer() || type.isReference())\n return;\n\n \/\/ print the type name\n std::cout << type.getQualifiedName() << \"\\n\";\n\n \/\/ check whether the type is abstract\n if (type.isAbstract()) std::cout << \"\\t[abstract]\\n\";\n\n \/\/ check whether the type is atomic\n if (type.isAtomic()) std::cout << \"\\t[atomic]\\n\";\n\n \/\/ check whether the type is an enumeration. If yes, display\n \/\/ the list of enumeration labels\n if (type.isEnum()) \n {\n std::cout << \"\\t[enum]\\n\";\n std::cout << \"\\tenumeration values:\\n\";\n const EnumLabelMap &emap = type.getEnumLabels();\n for (EnumLabelMap::const_iterator j=emap.begin(); j!=emap.end(); ++j)\n {\n std::cout << \"\\t\\t\" << j->second << \" = \" << j->first << \"\\n\";\n }\n }\n\n \/\/ if the type has one or more base types, then display their\n \/\/ names\n if (type.getNumBaseTypes() > 0)\n {\n std::cout << \"\\tderived from: \";\n for (int j=0; jsecond;\n \n \/\/ sort the map\n std::sort(types.begin(), types.end(), &type_order);\n\n \/\/ iterate through the type map and display some\n \/\/ details for each type\n for (TypeList::const_iterator i=types.begin(); i!=types.end(); ++i)\n {\n print_type(**i);\n }\n}\n\nint main()\n{\n \/\/ load the library of wrappers that reflect the \n \/\/ classes defined in the 'osg' namespace. In the\n \/\/ future this will be done automatically under\n \/\/ certain circumstances (like deserialization).\n osg::ref_ptr osg_reflectors = \n osgDB::DynamicLibrary::loadLibrary(createLibraryNameForWrapper(\"osg\"));\n \n \/\/ display a detailed list of reflected types\n try\n {\n print_types();\n }\n catch(const osgIntrospection::Exception &e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"WrapperGenerator.h\"\n\nusing namespace std;\n\nvoid WrapperGenerator::initOpToGenMap() {\n shared_ptr traceGen;\n shared_ptr cachingIPCGen;\n shared_ptr nonCachingIPCGen;\n\n traceGen = make_shared(operationMap);\n cachingIPCGen = make_shared();\n nonCachingIPCGen = make_shared();\n\n wrapperToGenMap = WrapperGenMap({{\"MUTEX_LOCK\", traceGen}, \n {\"MUTEX_UNLOCK\", traceGen},\n {\"CV_WAIT\", traceGen},\n {\"CV_BROADCAST\", traceGen},\n {\"CV_SIGNAL\", traceGen},\n {\"QUEUE_ENQUEUE\", traceGen},\n {\"QUEUE_DEQUEUE\", traceGen},\n {\"MESSAGE_SEND\", traceGen},\n {\"MESSAGE_RECEIVE\", traceGen},\n {\"MKNOD\", cachingIPCGen},\n {\"OPEN\", cachingIPCGen},\n {\"PIPE\", cachingIPCGen},\n {\"MSGGET\", cachingIPCGen},\n {\"READ\", nonCachingIPCGen},\n {\"WRITE\", nonCachingIPCGen},\n {\"MSGRCV\", nonCachingIPCGen},\n {\"MSGSND\", nonCachingIPCGen}});\n}\n\nWrapperGenerator::WrapperGenerator(shared_ptr> _prototypeMap,\n std::shared_ptr> _operationMap,\n string pathPrefix):\n prototypeMap(_prototypeMap),\n operationMap(_operationMap),\n vprofInternalOps({{MKNOD, true}, {READ, true},\n {WRITE, true}, {PIPE, true},\n {MSGGET, true}, {MSGSND, true},\n {MSGRCV, true}}) {\n initOpToGenMap();\n\n headerFile.open(pathPrefix + \"VProfEventWrappers.h\");\n implementationFile.open(pathPrefix + \"VProfEventWrappers.cpp\");\n\n const string generatedFileMessage = \n \" \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \\n\"\n \" \/\/ Note that this file was generated by VProfiler. \/\/ \\n\"\n \" \/\/ Please do not change the contents of this file! \/\/ \\n\"\n \" \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \\n\\n\";\n\n headerFile << generatedFileMessage; \n implementationFile << generatedFileMessage;\n}\n\nbool WrapperGenerator::isIPCOperation(const Operation op) const { \n return vprofInternalOps.find(op) != vprofInternalOps.end();\n}\n\nvoid instrumentIPCFunction(std::string &functionName, FunctionPrototype &prototype) {\n}\n\nvector WrapperGenerator::getFilenames() {\n vector result;\n\n for (auto kv : *prototypeMap) {\n result.push_back(kv.second.filename);\n }\n\n sort(result.begin(), result.end());\n result.erase(unique(result.begin(), result.end()), result.end());\n return result;\n}\n\nvoid WrapperGenerator::GenerateHeader() {\n vector includeNames = getFilenames();\n headerFile << \"#ifndef VPROFEVENTWRAPPERS_H\\n#define VPROFEVENTWRAPPERS_H\\n\";\n for (string &includeName : includeNames) {\n headerFile << \"#include \\\"\" + includeName + \"\\\"\\n\";\n }\n headerFile << \"#include \\\"trace_tool.h\\\"\\n\\n\"\n \"#ifdef __cplusplus\\nextern \\\"C\\\" {\\n#endif\";\n\n for (auto kv : *prototypeMap) {\n headerFile << kv.second.functionPrototype + \";\\n\\n\";\n }\n\n headerFile << \"#ifdef __cplusplus\\n}\\n#endif\\n\\n#endif\";\n\n headerFile.close();\n}\n\nvoid WrapperGenerator::GenerateImplementations() {\n string operation;\n implementationFile << \"#include \\\"VProfEventWrappers.h\\\"\\n\\n\";\n\n for (auto kv : *prototypeMap) {\n operation = (*operationMap)[kv.first];\n \n implementationFile << kv.second.functionPrototype + \" {\\n\\t\";\n\n if (kv.second.returnType != \"void\") {\n implementationFile << kv.second.returnType + \" result;\\n\\t\";\n }\n\n operationToGenMap[operation]->GenerateWrapperPrologue(kv.first, kv.second);\n\n if (kv.second.returnType != \"void\") {\n implementationFile << \"result = \";\n }\n\n implementationFile << kv.second.innerCallPrefix + \"(\";\n\n for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) {\n implementationFile << kv.second.paramVars[i];\n\n if (i != (j - 1)) {\n implementationFile << \", \";\n }\n }\n\n implementationFile <<\");\\n\\t\";\n\n operationToGenMap[operation]->GenerateWrapperEpilogue(kv.first, kv.second);\n\n if (kv.second.returnType != \"void\") {\n implementationFile << \"\\treturn result;\\n\";\n }\n\n implementationFile << \"}\\n\\n\";\n }\n\n implementationFile.close();\n}\n\nvoid WrapperGenerator::GenerateWrappers() {\n GenerateHeader();\n GenerateImplementations();\n}\nFew changes before band#include \"WrapperGenerator.h\"\n\nusing namespace std;\n\nvoid WrapperGenerator::initOpToGenMap() {\n shared_ptr traceGen;\n shared_ptr cachingIPCGen;\n shared_ptr nonCachingIPCGen;\n\n traceGen = make_shared(operationMap);\n cachingIPCGen = make_shared();\n nonCachingIPCGen = make_shared();\n\n operationToGenerator = WrapperGenMap({{\"MUTEX_LOCK\", traceGen}, \n {\"MUTEX_UNLOCK\", traceGen},\n {\"CV_WAIT\", traceGen},\n {\"CV_BROADCAST\", traceGen},\n {\"CV_SIGNAL\", traceGen},\n {\"QUEUE_ENQUEUE\", traceGen},\n {\"QUEUE_DEQUEUE\", traceGen},\n {\"MESSAGE_SEND\", traceGen},\n {\"MESSAGE_RECEIVE\", traceGen},\n {\"MKNOD\", cachingIPCGen},\n {\"OPEN\", cachingIPCGen},\n {\"PIPE\", cachingIPCGen},\n {\"MSGGET\", cachingIPCGen},\n {\"READ\", nonCachingIPCGen},\n {\"WRITE\", nonCachingIPCGen},\n {\"MSGRCV\", nonCachingIPCGen},\n {\"MSGSND\", nonCachingIPCGen}});\n}\n\nWrapperGenerator::WrapperGenerator(shared_ptr> _prototypeMap,\n std::shared_ptr> _operationMap,\n string pathPrefix):\n prototypeMap(_prototypeMap),\n operationMap(_operationMap) {\n initOpToGenMap();\n\n headerFile.open(pathPrefix + \"VProfEventWrappers.h\");\n implementationFile.open(pathPrefix + \"VProfEventWrappers.cpp\");\n\n const string generatedFileMessage = \n \" \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \\n\"\n \" \/\/ Note that this file was generated by VProfiler. \/\/ \\n\"\n \" \/\/ Please do not change the contents of this file! \/\/ \\n\"\n \" \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \\n\\n\";\n\n headerFile << generatedFileMessage; \n implementationFile << generatedFileMessage;\n}\n\nvector WrapperGenerator::getFilenames() {\n vector result;\n\n for (auto kv : *prototypeMap) {\n result.push_back(kv.second.filename);\n }\n\n sort(result.begin(), result.end());\n result.erase(unique(result.begin(), result.end()), result.end());\n return result;\n}\n\nvoid WrapperGenerator::GenerateHeader() {\n vector includeNames = getFilenames();\n headerFile << \"#ifndef VPROFEVENTWRAPPERS_H\\n#define VPROFEVENTWRAPPERS_H\\n\";\n for (string &includeName : includeNames) {\n headerFile << \"#include \\\"\" + includeName + \"\\\"\\n\";\n }\n headerFile << \"#include \\\"trace_tool.h\\\"\\n\\n\"\n \"#ifdef __cplusplus\\nextern \\\"C\\\" {\\n#endif\";\n\n for (auto kv : *prototypeMap) {\n headerFile << kv.second.functionPrototype + \";\\n\\n\";\n }\n\n headerFile << \"#ifdef __cplusplus\\n}\\n#endif\\n\\n#endif\";\n\n headerFile.close();\n}\n\nvoid WrapperGenerator::GenerateImplementations() {\n string operation;\n implementationFile << \"#include \\\"VProfEventWrappers.h\\\"\\n\\n\";\n\n for (auto kv : *prototypeMap) {\n operation = (*operationMap)[kv.first];\n \n implementationFile << kv.second.functionPrototype + \" {\\n\\t\";\n\n if (kv.second.returnType != \"void\") {\n implementationFile << kv.second.returnType + \" result;\\n\\t\";\n }\n\n operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second);\n\n if (kv.second.returnType != \"void\") {\n implementationFile << \"result = \";\n }\n\n implementationFile << kv.second.innerCallPrefix + \"(\";\n\n for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) {\n implementationFile << kv.second.paramVars[i];\n\n if (i != (j - 1)) {\n implementationFile << \", \";\n }\n }\n\n implementationFile <<\");\\n\\t\";\n\n operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second);\n\n if (kv.second.returnType != \"void\") {\n implementationFile << \"\\treturn result;\\n\";\n }\n\n implementationFile << \"}\\n\\n\";\n }\n\n implementationFile.close();\n}\n\nvoid WrapperGenerator::GenerateWrappers() {\n GenerateHeader();\n GenerateImplementations();\n}\n<|endoftext|>"} {"text":"#pragma once\n#ifndef ARGUMENT_LIB_HPP__\n#define ARGUMENT_LIB_HPP__ \"0.0.0@fArgumentLib.hpp\"\n\/**\n*\tDESCRIPTION:\n*\t\tModule contains implementation of argument parser and helprer structures.\n*\tAUTHOR:\n*\t\tMikhail Demchenko\n*\t\tmailto:dev.echo.mike@gmail.com\n*\t\thttps:\/\/github.com\/echo-Mike\n**\/\n\/** \n* MIT License\n*\n* Copyright (c) 2017-2018 Mikhail Demchenko dev.echo.mike@gmail.com\n* \n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n* \n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n* \n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n**\/\n\/\/STD\n#include \n\n#ifdef TEST\n #include \n struct FArgumentLibLoggerSingleton\n {\n static std::FILE* getInstance(const char* path)\n {\n static FArgumentLibLoggerSingleton s(path);\n return s.h;\n }\n private:\n std::FILE* h;\n FArgumentLibLoggerSingleton(const char* path) : h(std::fopen(path,\"w+\")) {}\n ~FArgumentLibLoggerSingleton()\n {\n std::fflush(h);\n std::fclose(h);\n }\n };\n#endif\n\n#if defined(TEST) && !defined(LOG)\n#define LOG(format, ...) \\\ndo { \\\n\tstd::fprintf(FArgumentLibLoggerSingleton::getInstance(\".\\\\fArgumentLibTestLog.txt\"), \"[%-35s: %-25s: line:%-4d] \" format \"\\n\", __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \\\n} while(0);\n#endif\n\n\/\/Main lib namespace\nnamespace Arguments \n{\n \/\/Set of possible option prefixes\n static const char *opt_ionPrefixes = \"-\/\";\n\n \/\/Set of types of otions\n enum class ArgTypes : char {\n Null = 0, \/\/Type of last option in option list\n Flag, \/\/The flag option type\n Value \/\/Option with leading value type\n \/\/MultiValue\n };\n\n struct Option {\n const char* shortCommand;\n const char* longCommand;\n ArgTypes type;\n int data;\n };\n\n \/**\n * @brief Identifies null-terminated string 'arg' as option\/\n * @param[in] arg Pointer to first char of examined null-terminated string.\n * @return Pointer to first option char in 'arg' or nullptr if not an option\/\n **\/\n char* isOption(char* arg)\n {\n auto size = std::strspn(arg, opt_ionPrefixes);\n return (size == 0) ? nullptr : arg + size;\n }\n\n \/**\n * @brief Attempts to find flag argument in argument list\n * @param[in] argc Argument list length.\n * @param[in] argv Argument list.\n * @param[in:out] opt Option to find.\n * @param[in] start Position in argument list to start with.\n * @return Noreturn\n **\/\n void findFlagArg(int argc, char* argv[], Option& opt, int start = 0) \n {\n opt.data = false;\n \/\/ Flag argument must be at maximum at the end\n if (start >= argc) \n return;\n char* opt_ = nullptr;\n for (auto index = start; index < argc; ++index) \n {\n opt_ = isOption(argv[index]);\n if (opt_) \n {\n if (std::strstr(opt_, opt.shortCommand) != NULL || \n !std::strcmp(opt_, opt.longCommand)) \n {\n opt.data = true;\n return;\n }\n }\n }\n }\n\n \/**\n * @brief Attempts to find value argument in argument list\n * @param[in] argc Argument list length.\n * @param[in] argv Argument list.\n * @param[in:out] opt Option to find.\n * @param[in] start Position in argument list to start with.\n * @return Noreturn\n **\/\n void findValueArg(int argc, char* argv[], Option& opt, int start = 0)\n {\n opt.data = -1;\n \/\/ Value argument must have one following argument at minimum\n if (start >= argc - 1) \n return;\n char* opt_ = nullptr;\n for (auto index = start; index < argc - 1; ++index) \n {\n opt_ = isOption(argv[index]);\n if (opt_) {\n if (!std::strcmp(opt_, opt.shortCommand) || \n !std::strcmp(opt_, opt.longCommand)) \n {\n opt.data = index + 1;\n return;\n }\n }\n }\n }\n\n \/**\n * @brief Main argumant parsing function.\n * @param[in] argc Argument list length.\n * @param[in] argv Argument list.\n * @param[in:out] optv Option list.\n * @retunr Noreturn\n **\/\n void parseArgs(int argc, char* argv[], Option optv[]) \n {\n int index = 0;\n while (optv[index].type != ArgTypes::Null) \n {\n switch (optv[index].type) {\n case ArgTypes::Flag:\n findFlagArg(argc, argv, optv[index]);\n break;\n case ArgTypes::Value:\n findValueArg(argc, argv, optv[index]);\n break;\n default:\n return;\n }\n ++index;\n }\n }\n}\n#endif[=][ARG]Grammar and style corrections#ifndef ARGUMENT_LIB_HPP_\n#define ARGUMENT_LIB_HPP_ \"0.0.0@fArgumentLib.hpp\"\n\/**\n * DESCRIPTION:\n * Module contains implementation of argument parser and helper structures.\n * AUTHOR:\n * Mikhail Demchenko\n * mailto:dev.echo.mike@gmail.com\n * https:\/\/github.com\/echo-Mike\n *\/\n\n\/**\n * MIT License\n *\n * Copyright (c) 2017-2018 Mikhail Demchenko dev.echo.mike@gmail.com\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n\/\/ STD\n#include \n\n#ifdef TEST\n #include \n struct FArgumentLibLoggerSingleton\n {\n static std::FILE* getInstance(const char* path)\n {\n static FArgumentLibLoggerSingleton s(path);\n return s.h;\n }\n private:\n std::FILE* h;\n FArgumentLibLoggerSingleton(const char* path) : h(std::fopen(path,\"w+\")) {}\n ~FArgumentLibLoggerSingleton()\n {\n std::fflush(h);\n std::fclose(h);\n }\n };\n#endif\n\n#if defined(TEST) && !defined(LOG)\n#define LOG(format, ...) \\\ndo { \\\n std::fprintf(FArgumentLibLoggerSingleton::getInstance(\".\\\\fArgumentLibTestLog.txt\"), \"[%-35s: %-25s: line:%-4d] \" format \"\\n\", __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \\\n} while(0);\n#endif\n\n\/**\n * @namespace Arguments\n * @brief Main namespace of argument parser library\n *\/\nnamespace Arguments \n{\n \/\/ Set of possible option prefixes\n static const char* opt_ionPrefixes = \"-\/\";\n\n \/\/ Set of types of options\n enum class ArgTypes : char\n {\n Null = 0, \/\/Type of last option in option list\n Flag, \/\/The flag option type\n Value \/\/Option with leading value type\n };\n\n struct Option\n {\n const char* shortCommand;\n const char* longCommand;\n ArgTypes type;\n int data;\n };\n\n \/**\n * @brief Identifies null-terminated string 'arg' as an option\n * @param[in] arg Pointer to first char of examined null-terminated string\n * @return Pointer to first option char in 'arg' or nullptr if not an option\n *\/\n char* isOption(char* arg)\n {\n auto size = std::strspn(arg, opt_ionPrefixes);\n return (size == 0) ? nullptr : arg + size;\n }\n\n \/**\n * @brief Attempts to find flag argument in argument list\n * @param[in] argc Argument list length\n * @param[in] argv Argument list\n * @param[in:out] opt Option to find\n * @param[in] start Position in argument list to start with\n *\/\n void findFlagArg(int argc, char* argv[], Option& opt, int start = 0) \n {\n opt.data = false;\n \/\/ Flag argument must be at maximum at the end\n if (start >= argc) \n return;\n char* opt_ = nullptr;\n for (auto index = start; index < argc; ++index) \n {\n opt_ = isOption(argv[index]);\n if (opt_) \n {\n if (std::strstr(opt_, opt.shortCommand) != NULL || \n !std::strcmp(opt_, opt.longCommand)) \n {\n opt.data = true;\n return;\n }\n }\n }\n }\n\n \/**\n * @brief Attempts to find value argument in argument list\n * @param[in] argc Argument list length\n * @param[in] argv Argument list\n * @param[in:out] opt Option to find\n * @param[in] start Position in argument list to start with\n *\/\n void findValueArg(int argc, char* argv[], Option& opt, int start = 0)\n {\n opt.data = -1;\n \/\/ Value argument must have one following argument at minimum\n if (start >= argc - 1) \n return;\n char* opt_ = nullptr;\n for (auto index = start; index < argc - 1; ++index) \n {\n opt_ = isOption(argv[index]);\n if (opt_)\n {\n if (!std::strcmp(opt_, opt.shortCommand) || \n !std::strcmp(opt_, opt.longCommand)) \n {\n opt.data = index + 1;\n return;\n }\n }\n }\n }\n\n \/**\n * @brief Main argument parsing function.\n * @param[in] argc Argument list length\n * @param[in] argv Argument list\n * @param[in:out] optv Option list\n *\/\n void parseArgs(int argc, char* argv[], Option optv[]) \n {\n int index = 0;\n while (optv[index].type != ArgTypes::Null) \n {\n switch (optv[index].type)\n {\n case ArgTypes::Flag:\n findFlagArg(argc, argv, optv[index]);\n break;\n case ArgTypes::Value:\n findValueArg(argc, argv, optv[index]);\n break;\n default:\n return;\n }\n ++index;\n }\n }\n}\n#endif \/* ARGUMENT_LIB_HPP_ *\/<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macitem.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 15:00:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _STREAM_HXX \/\/autogen\n#include \n#endif\n\n#ifndef GCC\n#endif\n#define ITEMID_MACRO 0\n\n#include \"macitem.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SvxMacroItem);\n\n\/\/ -----------------------------------------------------------------------\n\nTYPEINIT1_AUTOFACTORY(SvxMacroItem, SfxPoolItem);\n\n\/\/ -----------------------------------------------------------------------\n\n\nSjJSbxObjectBase::~SjJSbxObjectBase()\n{\n}\n\nSjJSbxObjectBase* SjJSbxObjectBase::Clone( void )\n{\n return NULL;\n}\n\nSvxMacro::SvxMacro( const String &rMacName, const String &rLanguage)\n : aMacName( rMacName ), aLibName( rLanguage),\n pFunctionObject(NULL), eType( EXTENDED_STYPE)\n{\n if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_STARBASIC))\n eType=STARBASIC;\n else if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_JAVASCRIPT))\n eType=JAVASCRIPT;\n}\n\n\nSvxMacro::~SvxMacro()\n{\n delete pFunctionObject;\n}\n\nString SvxMacro::GetLanguage()const\n{\n if(eType==STARBASIC)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_STARBASIC));\n }\n else if(eType==JAVASCRIPT)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_JAVASCRIPT));\n }\n else if(eType==EXTENDED_STYPE)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_SF));\n\n }\n return aLibName;\n}\n\n\n\nSvxMacro& SvxMacro::operator=( const SvxMacro& rBase )\n{\n if( this != &rBase )\n {\n aMacName = rBase.aMacName;\n aLibName = rBase.aLibName;\n delete pFunctionObject;\n pFunctionObject = rBase.pFunctionObject ? rBase.pFunctionObject->Clone() : NULL;\n eType = rBase.eType;\n }\n return *this;\n}\n\n\nSvxMacroTableDtor& SvxMacroTableDtor::operator=( const SvxMacroTableDtor& rTbl )\n{\n DelDtor();\n SvxMacro* pTmp = ((SvxMacroTableDtor&)rTbl).First();\n while( pTmp )\n {\n SvxMacro *pNew = new SvxMacro( *pTmp );\n Insert( rTbl.GetCurKey(), pNew );\n pTmp = ((SvxMacroTableDtor&)rTbl).Next();\n }\n return *this;\n}\n\n\nSvStream& SvxMacroTableDtor::Read( SvStream& rStrm, USHORT nVersion )\n{\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> nVersion;\n short nMacro;\n rStrm >> nMacro;\n\n for( short i = 0; i < nMacro; ++i )\n {\n USHORT nCurKey, eType = STARBASIC;\n String aLibName, aMacName;\n rStrm >> nCurKey;\n SfxPoolItem::readByteString(rStrm, aLibName);\n SfxPoolItem::readByteString(rStrm, aMacName);\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> eType;\n\n SvxMacro* pNew = new SvxMacro( aMacName, aLibName, (ScriptType)eType );\n\n SvxMacro *pOld = Get( nCurKey );\n if( pOld )\n {\n delete pOld;\n Replace( nCurKey, pNew );\n }\n else\n Insert( nCurKey, pNew );\n }\n return rStrm;\n}\n\n\nSvStream& SvxMacroTableDtor::Write( SvStream& rStream ) const\n{\n USHORT nVersion = SOFFICE_FILEFORMAT_31 == rStream.GetVersion()\n ? SVX_MACROTBL_VERSION31\n : SVX_MACROTBL_AKTVERSION;\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << nVersion;\n\n rStream << (USHORT)Count();\n\n SvxMacro* pMac = ((SvxMacroTableDtor*)this)->First();\n while( pMac && rStream.GetError() == SVSTREAM_OK )\n {\n rStream << (short)GetCurKey();\n SfxPoolItem::writeByteString(rStream, pMac->GetLibName());\n SfxPoolItem::writeByteString(rStream, pMac->GetMacName());\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << (USHORT)pMac->GetScriptType();\n pMac = ((SvxMacroTableDtor*)this)->Next();\n }\n return rStream;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroTableDtor::DelDtor()\n{\n SvxMacro* pTmp = First();\n while( pTmp )\n {\n delete pTmp;\n pTmp = Next();\n }\n Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint SvxMacroItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n\n const SvxMacroTableDtor& rOwn = aMacroTable;\n const SvxMacroTableDtor& rOther = ( (SvxMacroItem&) rAttr ).aMacroTable;\n\n \/\/ Anzahl unterschiedlich => auf jeden Fall ungleich\n if ( rOwn.Count() != rOther.Count() )\n return FALSE;\n\n \/\/ einzeln verleichen; wegen Performance ist die Reihenfolge wichtig\n for ( USHORT nNo = 0; nNo < rOwn.Count(); ++nNo )\n {\n const SvxMacro *pOwnMac = rOwn.GetObject(nNo);\n const SvxMacro *pOtherMac = rOther.GetObject(nNo);\n if ( rOwn.GetKey(pOwnMac) != rOther.GetKey(pOtherMac) ||\n pOwnMac->GetLibName() != pOtherMac->GetLibName() ||\n pOwnMac->GetMacName() != pOtherMac->GetMacName() )\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Clone( SfxItemPool* ) const\n{\n return new SvxMacroItem( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nSfxItemPresentation SvxMacroItem::GetPresentation\n(\n SfxItemPresentation \/*ePres*\/,\n SfxMapUnit \/*eCoreUnit*\/,\n SfxMapUnit \/*ePresUnit*\/,\n XubString& rText,\n const IntlWrapper *\n) const\n{\n\/*!!!\n SvxMacroTableDtor& rTbl = (SvxMacroTableDtor&)GetMacroTable();\n SvxMacro* pMac = rTbl.First();\n\n while ( pMac )\n {\n rText += pMac->GetLibName();\n rText += cpDelim;\n rText += pMac->GetMacName();\n pMac = rTbl.Next();\n if ( pMac )\n rText += cpDelim;\n }\n*\/\n rText.Erase();\n return SFX_ITEM_PRESENTATION_NONE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvStream& SvxMacroItem::Store( SvStream& rStrm , USHORT ) const\n{\n return aMacroTable.Write( rStrm );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Create( SvStream& rStrm, USHORT nVersion ) const\n{\n SvxMacroItem* pAttr = new SvxMacroItem( Which() );\n pAttr->aMacroTable.Read( rStrm, nVersion );\n return pAttr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroItem::SetMacro( USHORT nEvent, const SvxMacro& rMacro )\n{\n SvxMacro *pMacro;\n if ( 0 != (pMacro=aMacroTable.Get(nEvent)) )\n {\n delete pMacro;\n aMacroTable.Replace(nEvent, new SvxMacro( rMacro ) );\n }\n else\n aMacroTable.Insert(nEvent, new SvxMacro( rMacro ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SvxMacroItem::GetVersion( USHORT nFileFormatVersion ) const\n{\n return SOFFICE_FILEFORMAT_31 == nFileFormatVersion\n ? 0 : aMacroTable.GetVersion();\n}\n\nINTEGRATION: CWS pchfix04 (1.7.70); FILE MERGED 2007\/02\/05 08:45:54 os 1.7.70.1: #i73604# usage of ITEMID_* removed\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macitem.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 16:37:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _STREAM_HXX \/\/autogen\n#include \n#endif\n\n#ifndef GCC\n#endif\n\n#include \"macitem.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nDBG_NAME(SvxMacroItem);\n\n\/\/ -----------------------------------------------------------------------\nTYPEINIT1_FACTORY(SvxMacroItem, SfxPoolItem, new SvxMacroItem(0));\n\n\/\/ -----------------------------------------------------------------------\n\n\nSjJSbxObjectBase::~SjJSbxObjectBase()\n{\n}\n\nSjJSbxObjectBase* SjJSbxObjectBase::Clone( void )\n{\n return NULL;\n}\n\nSvxMacro::SvxMacro( const String &rMacName, const String &rLanguage)\n : aMacName( rMacName ), aLibName( rLanguage),\n pFunctionObject(NULL), eType( EXTENDED_STYPE)\n{\n if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_STARBASIC))\n eType=STARBASIC;\n else if (rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_JAVASCRIPT))\n eType=JAVASCRIPT;\n}\n\n\nSvxMacro::~SvxMacro()\n{\n delete pFunctionObject;\n}\n\nString SvxMacro::GetLanguage()const\n{\n if(eType==STARBASIC)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_STARBASIC));\n }\n else if(eType==JAVASCRIPT)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_JAVASCRIPT));\n }\n else if(eType==EXTENDED_STYPE)\n {\n return UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM(SVX_MACRO_LANGUAGE_SF));\n\n }\n return aLibName;\n}\n\n\n\nSvxMacro& SvxMacro::operator=( const SvxMacro& rBase )\n{\n if( this != &rBase )\n {\n aMacName = rBase.aMacName;\n aLibName = rBase.aLibName;\n delete pFunctionObject;\n pFunctionObject = rBase.pFunctionObject ? rBase.pFunctionObject->Clone() : NULL;\n eType = rBase.eType;\n }\n return *this;\n}\n\n\nSvxMacroTableDtor& SvxMacroTableDtor::operator=( const SvxMacroTableDtor& rTbl )\n{\n DelDtor();\n SvxMacro* pTmp = ((SvxMacroTableDtor&)rTbl).First();\n while( pTmp )\n {\n SvxMacro *pNew = new SvxMacro( *pTmp );\n Insert( rTbl.GetCurKey(), pNew );\n pTmp = ((SvxMacroTableDtor&)rTbl).Next();\n }\n return *this;\n}\n\n\nSvStream& SvxMacroTableDtor::Read( SvStream& rStrm, USHORT nVersion )\n{\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> nVersion;\n short nMacro;\n rStrm >> nMacro;\n\n for( short i = 0; i < nMacro; ++i )\n {\n USHORT nCurKey, eType = STARBASIC;\n String aLibName, aMacName;\n rStrm >> nCurKey;\n SfxPoolItem::readByteString(rStrm, aLibName);\n SfxPoolItem::readByteString(rStrm, aMacName);\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStrm >> eType;\n\n SvxMacro* pNew = new SvxMacro( aMacName, aLibName, (ScriptType)eType );\n\n SvxMacro *pOld = Get( nCurKey );\n if( pOld )\n {\n delete pOld;\n Replace( nCurKey, pNew );\n }\n else\n Insert( nCurKey, pNew );\n }\n return rStrm;\n}\n\n\nSvStream& SvxMacroTableDtor::Write( SvStream& rStream ) const\n{\n USHORT nVersion = SOFFICE_FILEFORMAT_31 == rStream.GetVersion()\n ? SVX_MACROTBL_VERSION31\n : SVX_MACROTBL_AKTVERSION;\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << nVersion;\n\n rStream << (USHORT)Count();\n\n SvxMacro* pMac = ((SvxMacroTableDtor*)this)->First();\n while( pMac && rStream.GetError() == SVSTREAM_OK )\n {\n rStream << (short)GetCurKey();\n SfxPoolItem::writeByteString(rStream, pMac->GetLibName());\n SfxPoolItem::writeByteString(rStream, pMac->GetMacName());\n\n if( SVX_MACROTBL_VERSION40 <= nVersion )\n rStream << (USHORT)pMac->GetScriptType();\n pMac = ((SvxMacroTableDtor*)this)->Next();\n }\n return rStream;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroTableDtor::DelDtor()\n{\n SvxMacro* pTmp = First();\n while( pTmp )\n {\n delete pTmp;\n pTmp = Next();\n }\n Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint SvxMacroItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n\n const SvxMacroTableDtor& rOwn = aMacroTable;\n const SvxMacroTableDtor& rOther = ( (SvxMacroItem&) rAttr ).aMacroTable;\n\n \/\/ Anzahl unterschiedlich => auf jeden Fall ungleich\n if ( rOwn.Count() != rOther.Count() )\n return FALSE;\n\n \/\/ einzeln verleichen; wegen Performance ist die Reihenfolge wichtig\n for ( USHORT nNo = 0; nNo < rOwn.Count(); ++nNo )\n {\n const SvxMacro *pOwnMac = rOwn.GetObject(nNo);\n const SvxMacro *pOtherMac = rOther.GetObject(nNo);\n if ( rOwn.GetKey(pOwnMac) != rOther.GetKey(pOtherMac) ||\n pOwnMac->GetLibName() != pOtherMac->GetLibName() ||\n pOwnMac->GetMacName() != pOtherMac->GetMacName() )\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Clone( SfxItemPool* ) const\n{\n return new SvxMacroItem( *this );\n}\n\n\/\/------------------------------------------------------------------------\n\nSfxItemPresentation SvxMacroItem::GetPresentation\n(\n SfxItemPresentation \/*ePres*\/,\n SfxMapUnit \/*eCoreUnit*\/,\n SfxMapUnit \/*ePresUnit*\/,\n XubString& rText,\n const IntlWrapper *\n) const\n{\n\/*!!!\n SvxMacroTableDtor& rTbl = (SvxMacroTableDtor&)GetMacroTable();\n SvxMacro* pMac = rTbl.First();\n\n while ( pMac )\n {\n rText += pMac->GetLibName();\n rText += cpDelim;\n rText += pMac->GetMacName();\n pMac = rTbl.Next();\n if ( pMac )\n rText += cpDelim;\n }\n*\/\n rText.Erase();\n return SFX_ITEM_PRESENTATION_NONE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSvStream& SvxMacroItem::Store( SvStream& rStrm , USHORT ) const\n{\n return aMacroTable.Write( rStrm );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nSfxPoolItem* SvxMacroItem::Create( SvStream& rStrm, USHORT nVersion ) const\n{\n SvxMacroItem* pAttr = new SvxMacroItem( Which() );\n pAttr->aMacroTable.Read( rStrm, nVersion );\n return pAttr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid SvxMacroItem::SetMacro( USHORT nEvent, const SvxMacro& rMacro )\n{\n SvxMacro *pMacro;\n if ( 0 != (pMacro=aMacroTable.Get(nEvent)) )\n {\n delete pMacro;\n aMacroTable.Replace(nEvent, new SvxMacro( rMacro ) );\n }\n else\n aMacroTable.Insert(nEvent, new SvxMacro( rMacro ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nUSHORT SvxMacroItem::GetVersion( USHORT nFileFormatVersion ) const\n{\n return SOFFICE_FILEFORMAT_31 == nFileFormatVersion\n ? 0 : aMacroTable.GetVersion();\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stritem.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:00:54 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SFXSTRITEM_HXX\n#include \n#endif\n\n\/\/============================================================================\n\/\/\n\/\/ class SfxStringItem\n\/\/\n\/\/============================================================================\n\nTYPEINIT1_AUTOFACTORY(SfxStringItem, CntUnencodedStringItem)\n\n\/\/============================================================================\n\/\/ virtual\nSfxStringItem::SfxStringItem(USHORT nWhich, SvStream & rStream):\n CntUnencodedStringItem(nWhich)\n{\n UniString aValue;\n readByteString(rStream, aValue);\n SetValue(aValue);\n}\n\n\n\/\/============================================================================\n\/\/ virtual\nSfxPoolItem * SfxStringItem::Create(SvStream & rStream, USHORT) const\n{\n return new SfxStringItem(Which(), rStream);\n}\n\n\/\/============================================================================\n\/\/ virtual\nSvStream & SfxStringItem::Store(SvStream & rStream, USHORT) const\n{\n writeByteString(rStream, GetValue());\n return rStream;\n}\n\n\/\/============================================================================\n\/\/ virtual\nSfxPoolItem * SfxStringItem::Clone(SfxItemPool *) const\n{\n return new SfxStringItem(*this);\n}\n\nINTEGRATION: CWS warnings01 (1.2.60); FILE MERGED 2005\/11\/15 17:54:42 pl 1.2.60.1: #i55991# removed warnings\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stritem.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 21:13:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SFXSTRITEM_HXX\n#include \n#endif\n\n\/\/============================================================================\n\/\/\n\/\/ class SfxStringItem\n\/\/\n\/\/============================================================================\n\nTYPEINIT1_AUTOFACTORY(SfxStringItem, CntUnencodedStringItem)\n\n\/\/============================================================================\n\/\/ virtual\nSfxStringItem::SfxStringItem(USHORT which, SvStream & rStream):\n CntUnencodedStringItem(which)\n{\n UniString aValue;\n readByteString(rStream, aValue);\n SetValue(aValue);\n}\n\n\n\/\/============================================================================\n\/\/ virtual\nSfxPoolItem * SfxStringItem::Create(SvStream & rStream, USHORT) const\n{\n return new SfxStringItem(Which(), rStream);\n}\n\n\/\/============================================================================\n\/\/ virtual\nSvStream & SfxStringItem::Store(SvStream & rStream, USHORT) const\n{\n writeByteString(rStream, GetValue());\n return rStream;\n}\n\n\/\/============================================================================\n\/\/ virtual\nSfxPoolItem * SfxStringItem::Clone(SfxItemPool *) const\n{\n return new SfxStringItem(*this);\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmdirlbox.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:08:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _SVX_FRMDIRLBOX_HXX\n#include \"frmdirlbox.hxx\"\n#endif\n\nnamespace svx {\n\n\/\/ ============================================================================\n\nnamespace {\n\ninline void* lclEnumToVoid( SvxFrameDirection eDirection )\n{\n return reinterpret_cast< void* >( static_cast< sal_uInt32 >( eDirection ) );\n}\n\ninline SvxFrameDirection lclVoidToEnum( void* pDirection )\n{\n return static_cast< SvxFrameDirection >( reinterpret_cast< sal_uInt32 >( pDirection ) );\n}\n\n} \/\/ namespace\n\n\/\/ ============================================================================\n\nFrameDirectionListBox::FrameDirectionListBox( Window* pParent, WinBits nStyle ) :\n ListBox( pParent, nStyle )\n{\n}\n\nFrameDirectionListBox::FrameDirectionListBox( Window* pParent, const ResId& rResId ) :\n ListBox( pParent, rResId )\n{\n}\n\nFrameDirectionListBox::~FrameDirectionListBox()\n{\n}\n\nvoid FrameDirectionListBox::InsertEntryValue( const String& rString, SvxFrameDirection eDirection, sal_uInt16 nPos )\n{\n sal_uInt16 nRealPos = InsertEntry( rString, nPos );\n SetEntryData( nRealPos, lclEnumToVoid( eDirection ) );\n}\n\nvoid FrameDirectionListBox::RemoveEntryValue( SvxFrameDirection eDirection )\n{\n sal_uInt16 nPos = GetEntryPos( lclEnumToVoid( eDirection ) );\n if( nPos != LISTBOX_ENTRY_NOTFOUND )\n RemoveEntry( nPos );\n}\n\nvoid FrameDirectionListBox::SelectEntryValue( SvxFrameDirection eDirection )\n{\n sal_uInt16 nPos = GetEntryPos( lclEnumToVoid( eDirection ) );\n if( nPos == LISTBOX_ENTRY_NOTFOUND )\n SetNoSelection();\n else\n SelectEntryPos( nPos );\n}\n\nSvxFrameDirection FrameDirectionListBox::GetSelectEntryValue() const\n{\n sal_uInt16 nPos = GetSelectEntryPos();\n if( nPos == LISTBOX_ENTRY_NOTFOUND )\n return static_cast< SvxFrameDirection >( 0xFFFF );\n return lclVoidToEnum( GetEntryData( nPos ) );\n}\n\n\/\/ ============================================================================\n\nFrameDirListBoxWrapper::FrameDirListBoxWrapper( FrameDirListBox& rListBox ) :\n SingleControlWrapperType( rListBox )\n{\n}\n\nbool FrameDirListBoxWrapper::IsControlDontKnow() const\n{\n return GetControl().GetSelectEntryCount() == 0;\n}\n\nvoid FrameDirListBoxWrapper::SetControlDontKnow( bool bSet )\n{\n if( bSet )\n GetControl().SetNoSelection();\n}\n\nSvxFrameDirection FrameDirListBoxWrapper::GetControlValue() const\n{\n return GetControl().GetSelectEntryValue();\n}\n\nvoid FrameDirListBoxWrapper::SetControlValue( SvxFrameDirection eValue )\n{\n GetControl().SelectEntryValue( eValue );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace svx\n\nINTEGRATION: CWS intptr (1.2.768); FILE MERGED 2005\/09\/13 14:50:10 kendy 1.2.768.1: #i54498# Introduce and use sal_IntPtr\/sal_uIntPtr for ints where we have to store a pointer\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmdirlbox.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2005-10-05 14:34:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _SVX_FRMDIRLBOX_HXX\n#include \"frmdirlbox.hxx\"\n#endif\n\nnamespace svx {\n\n\/\/ ============================================================================\n\nnamespace {\n\ninline void* lclEnumToVoid( SvxFrameDirection eDirection )\n{\n return reinterpret_cast< void* >( static_cast< sal_uInt32 >( eDirection ) );\n}\n\ninline SvxFrameDirection lclVoidToEnum( void* pDirection )\n{\n return static_cast< SvxFrameDirection >( reinterpret_cast< sal_IntPtr >( pDirection ) );\n}\n\n} \/\/ namespace\n\n\/\/ ============================================================================\n\nFrameDirectionListBox::FrameDirectionListBox( Window* pParent, WinBits nStyle ) :\n ListBox( pParent, nStyle )\n{\n}\n\nFrameDirectionListBox::FrameDirectionListBox( Window* pParent, const ResId& rResId ) :\n ListBox( pParent, rResId )\n{\n}\n\nFrameDirectionListBox::~FrameDirectionListBox()\n{\n}\n\nvoid FrameDirectionListBox::InsertEntryValue( const String& rString, SvxFrameDirection eDirection, sal_uInt16 nPos )\n{\n sal_uInt16 nRealPos = InsertEntry( rString, nPos );\n SetEntryData( nRealPos, lclEnumToVoid( eDirection ) );\n}\n\nvoid FrameDirectionListBox::RemoveEntryValue( SvxFrameDirection eDirection )\n{\n sal_uInt16 nPos = GetEntryPos( lclEnumToVoid( eDirection ) );\n if( nPos != LISTBOX_ENTRY_NOTFOUND )\n RemoveEntry( nPos );\n}\n\nvoid FrameDirectionListBox::SelectEntryValue( SvxFrameDirection eDirection )\n{\n sal_uInt16 nPos = GetEntryPos( lclEnumToVoid( eDirection ) );\n if( nPos == LISTBOX_ENTRY_NOTFOUND )\n SetNoSelection();\n else\n SelectEntryPos( nPos );\n}\n\nSvxFrameDirection FrameDirectionListBox::GetSelectEntryValue() const\n{\n sal_uInt16 nPos = GetSelectEntryPos();\n if( nPos == LISTBOX_ENTRY_NOTFOUND )\n return static_cast< SvxFrameDirection >( 0xFFFF );\n return lclVoidToEnum( GetEntryData( nPos ) );\n}\n\n\/\/ ============================================================================\n\nFrameDirListBoxWrapper::FrameDirListBoxWrapper( FrameDirListBox& rListBox ) :\n SingleControlWrapperType( rListBox )\n{\n}\n\nbool FrameDirListBoxWrapper::IsControlDontKnow() const\n{\n return GetControl().GetSelectEntryCount() == 0;\n}\n\nvoid FrameDirListBoxWrapper::SetControlDontKnow( bool bSet )\n{\n if( bSet )\n GetControl().SetNoSelection();\n}\n\nSvxFrameDirection FrameDirListBoxWrapper::GetControlValue() const\n{\n return GetControl().GetSelectEntryValue();\n}\n\nvoid FrameDirListBoxWrapper::SetControlValue( SvxFrameDirection eValue )\n{\n GetControl().SelectEntryValue( eValue );\n}\n\n\/\/ ============================================================================\n\n} \/\/ namespace svx\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: volume3d.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 17:01:15 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _VOLUME3D_HXX\n#include \"volume3d.hxx\"\n#endif\n\n#ifndef _POLY3D_HXX\n#include \"poly3d.hxx\"\n#endif\n\n#ifndef _SVX_MATRIX3D_HXX\n#include \"matrix3d.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n\/*************************************************************************\n|*\n|* Konstruktor 1: |\n|* rPos: Zentrum oder minimale Koordinate links, unten, hinten |__\n|* (abhaengig von bPosIsCenter) \/\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D(const Vector3D& rPos, const Vector3D& r3DSize, BOOL bPosIsCenter)\n: B3dVolume(rPos, r3DSize, bPosIsCenter)\n{\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor 2 - leeres Volumen, Werte als ungueltig markieren\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D() : B3dVolume()\n{\n}\n\n\/*************************************************************************\n|*\n|* Transformation des Volumens berechnen und als neues Volumen\n|* zurueckgeben\n|*\n\\************************************************************************\/\n\nVolume3D Volume3D::GetTransformVolume(const Matrix4D& rTfMatrix) const\n{\n Volume3D aTfVol;\n\n if(IsValid())\n {\n Vector3D aTfVec;\n Vol3DPointIterator aIter(*this, &rTfMatrix);\n\n while(aIter.Next(aTfVec))\n aTfVol.Union(aTfVec);\n }\n return aTfVol;\n}\n\n\/*************************************************************************\n|*\n|* Drahtgitter-Linien fuer das Volumen berechnen und in rPoly3D ablegen\n|*\n\\************************************************************************\/\n\nvoid Volume3D::CreateWireframe(Polygon3D& rPoly3D, const Matrix4D* pTf) const\n{\n if(!IsValid())\n return;\n\n Vector3D aDiff = aMaxVec - aMinVec;\n Polygon3D aVolPnts(8);\n UINT16 nZeroCnt(0);\n UINT16 nIdx = rPoly3D.GetPointCount();\n\n \/\/ Alle Punkte holen\n Vol3DPointIterator aIter(*this, pTf);\n Vector3D aTfVec;\n UINT16 i(0);\n\n while(aIter.Next(aTfVec))\n aVolPnts[i++] = aTfVec;\n\n \/\/ 0-Ausmasse des BoundVolumes zaehlen\n for(i = 0; i < 3; i++)\n if(aDiff[i] == 0)\n nZeroCnt++;\n\n \/\/ Die drei Ecksegemente des Volumens mit je drei Linien ausgeben;\n \/\/ falls Koordinatenanteile 0 sind, nicht alle Segmente verwenden,\n \/\/ um das gegenseitige Ausloeschen bei XOR-Ausgabe zu verhindern\n \/\/ 4\n \/\/ | Dieses Segment immer\n \/\/ |\n \/\/ 0---1\n \/\/ \/\n \/\/ 3\n \/\/ Die Liniensegmente eines Segments werden immer in der Reihenfolge\n \/\/ X-, Y- und dann Z-Richtung ausgegeben (gilt natuerlich nur fuer\n \/\/ untransformierte Koordinaten)\n\n rPoly3D[nIdx++] = aVolPnts[0];\n\n if(nZeroCnt < 3)\n {\n \/\/ wenn keine Ausdehnung, dann nur den ersten Punkt einfuegen\n rPoly3D[nIdx++] = aVolPnts[1];\n rPoly3D[nIdx++] = aVolPnts[0];\n rPoly3D[nIdx++] = aVolPnts[4];\n rPoly3D[nIdx++] = aVolPnts[0];\n rPoly3D[nIdx++] = aVolPnts[3];\n }\n if(nZeroCnt < 2)\n {\n if(nZeroCnt == 0 || aDiff.X() == 0)\n {\n \/\/ 4\n \/\/ \/\n \/\/ 7---6\n \/\/ |\n \/\/ |\n \/\/ 3\n rPoly3D[nIdx++] = aVolPnts[7];\n rPoly3D[nIdx++] = aVolPnts[6];\n rPoly3D[nIdx++] = aVolPnts[7];\n rPoly3D[nIdx++] = aVolPnts[3];\n rPoly3D[nIdx++] = aVolPnts[7];\n rPoly3D[nIdx++] = aVolPnts[4];\n }\n if(nZeroCnt == 0 || (aDiff.Y() == 0))\n {\n \/\/ 6\n \/\/ | 1\n \/\/ |\/\n \/\/ 3---2\n rPoly3D[nIdx++] = aVolPnts[2];\n rPoly3D[nIdx++] = aVolPnts[3];\n rPoly3D[nIdx++] = aVolPnts[2];\n rPoly3D[nIdx++] = aVolPnts[6];\n rPoly3D[nIdx++] = aVolPnts[2];\n rPoly3D[nIdx++] = aVolPnts[1];\n }\n if(nZeroCnt == 0 || (aDiff.Z() == 0))\n {\n \/\/ 4---5\n \/\/ \/|\n \/\/ 6 |\n \/\/ 1\n rPoly3D[nIdx++] = aVolPnts[5];\n rPoly3D[nIdx++] = aVolPnts[4];\n rPoly3D[nIdx++] = aVolPnts[5];\n rPoly3D[nIdx++] = aVolPnts[1];\n rPoly3D[nIdx++] = aVolPnts[5];\n rPoly3D[nIdx++] = aVolPnts[6];\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor des Point-Iterators\n|*\n\\************************************************************************\/\n\nVol3DPointIterator::Vol3DPointIterator(const Volume3D& rVol, const Matrix4D* pTf)\n: rVolume(rVol),\n pTransform(pTf),\n nIndex(0)\n{\n DBG_ASSERT(rVol.IsValid(), \"Vol3DPointIterator-Aufruf mit ungueltigem Volume3D!\");\n a3DExtent = rVolume.aMaxVec - rVolume.aMinVec;\n}\n\n\/*************************************************************************\n|*\n|* Gibt die einzelnen Punkte des (ggf. transformierten) Volumens zurueck\n|*\n|* 4---5 -> Reihenfolge der Punktausgabe (untransformiert)\n|* \/| \/|\n|* 7---6 |\n|* | 0-|-1\n|* |\/ |\/\n|* 3---2\n|*\n\\************************************************************************\/\n\nBOOL Vol3DPointIterator::Next(Vector3D& rVec)\n{\n if(nIndex > 7)\n {\n return FALSE;\n }\n else\n {\n rVec = rVolume.aMinVec;\n\n if(nIndex >= 4)\n rVec.Y() += a3DExtent.Y();\n\n switch(nIndex)\n {\n case 6:\n case 2: rVec.Z() += a3DExtent.Z();\n case 5:\n case 1: rVec.X() += a3DExtent.X();\n break;\n case 7:\n case 3: rVec.Z() += a3DExtent.Z();\n break;\n }\n nIndex++;\n\n if(pTransform)\n rVec *= *pTransform;\n\n return TRUE;\n }\n}\n\n\nINTEGRATION: CWS ooo19126 (1.1.1.1.1670); FILE MERGED 2005\/09\/05 14:24:18 rt 1.1.1.1.1670.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: volume3d.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:44:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _VOLUME3D_HXX\n#include \"volume3d.hxx\"\n#endif\n\n#ifndef _POLY3D_HXX\n#include \"poly3d.hxx\"\n#endif\n\n#ifndef _SVX_MATRIX3D_HXX\n#include \"matrix3d.hxx\"\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n\/*************************************************************************\n|*\n|* Konstruktor 1: |\n|* rPos: Zentrum oder minimale Koordinate links, unten, hinten |__\n|* (abhaengig von bPosIsCenter) \/\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D(const Vector3D& rPos, const Vector3D& r3DSize, BOOL bPosIsCenter)\n: B3dVolume(rPos, r3DSize, bPosIsCenter)\n{\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor 2 - leeres Volumen, Werte als ungueltig markieren\n|*\n\\************************************************************************\/\n\nVolume3D::Volume3D() : B3dVolume()\n{\n}\n\n\/*************************************************************************\n|*\n|* Transformation des Volumens berechnen und als neues Volumen\n|* zurueckgeben\n|*\n\\************************************************************************\/\n\nVolume3D Volume3D::GetTransformVolume(const Matrix4D& rTfMatrix) const\n{\n Volume3D aTfVol;\n\n if(IsValid())\n {\n Vector3D aTfVec;\n Vol3DPointIterator aIter(*this, &rTfMatrix);\n\n while(aIter.Next(aTfVec))\n aTfVol.Union(aTfVec);\n }\n return aTfVol;\n}\n\n\/*************************************************************************\n|*\n|* Drahtgitter-Linien fuer das Volumen berechnen und in rPoly3D ablegen\n|*\n\\************************************************************************\/\n\nvoid Volume3D::CreateWireframe(Polygon3D& rPoly3D, const Matrix4D* pTf) const\n{\n if(!IsValid())\n return;\n\n Vector3D aDiff = aMaxVec - aMinVec;\n Polygon3D aVolPnts(8);\n UINT16 nZeroCnt(0);\n UINT16 nIdx = rPoly3D.GetPointCount();\n\n \/\/ Alle Punkte holen\n Vol3DPointIterator aIter(*this, pTf);\n Vector3D aTfVec;\n UINT16 i(0);\n\n while(aIter.Next(aTfVec))\n aVolPnts[i++] = aTfVec;\n\n \/\/ 0-Ausmasse des BoundVolumes zaehlen\n for(i = 0; i < 3; i++)\n if(aDiff[i] == 0)\n nZeroCnt++;\n\n \/\/ Die drei Ecksegemente des Volumens mit je drei Linien ausgeben;\n \/\/ falls Koordinatenanteile 0 sind, nicht alle Segmente verwenden,\n \/\/ um das gegenseitige Ausloeschen bei XOR-Ausgabe zu verhindern\n \/\/ 4\n \/\/ | Dieses Segment immer\n \/\/ |\n \/\/ 0---1\n \/\/ \/\n \/\/ 3\n \/\/ Die Liniensegmente eines Segments werden immer in der Reihenfolge\n \/\/ X-, Y- und dann Z-Richtung ausgegeben (gilt natuerlich nur fuer\n \/\/ untransformierte Koordinaten)\n\n rPoly3D[nIdx++] = aVolPnts[0];\n\n if(nZeroCnt < 3)\n {\n \/\/ wenn keine Ausdehnung, dann nur den ersten Punkt einfuegen\n rPoly3D[nIdx++] = aVolPnts[1];\n rPoly3D[nIdx++] = aVolPnts[0];\n rPoly3D[nIdx++] = aVolPnts[4];\n rPoly3D[nIdx++] = aVolPnts[0];\n rPoly3D[nIdx++] = aVolPnts[3];\n }\n if(nZeroCnt < 2)\n {\n if(nZeroCnt == 0 || aDiff.X() == 0)\n {\n \/\/ 4\n \/\/ \/\n \/\/ 7---6\n \/\/ |\n \/\/ |\n \/\/ 3\n rPoly3D[nIdx++] = aVolPnts[7];\n rPoly3D[nIdx++] = aVolPnts[6];\n rPoly3D[nIdx++] = aVolPnts[7];\n rPoly3D[nIdx++] = aVolPnts[3];\n rPoly3D[nIdx++] = aVolPnts[7];\n rPoly3D[nIdx++] = aVolPnts[4];\n }\n if(nZeroCnt == 0 || (aDiff.Y() == 0))\n {\n \/\/ 6\n \/\/ | 1\n \/\/ |\/\n \/\/ 3---2\n rPoly3D[nIdx++] = aVolPnts[2];\n rPoly3D[nIdx++] = aVolPnts[3];\n rPoly3D[nIdx++] = aVolPnts[2];\n rPoly3D[nIdx++] = aVolPnts[6];\n rPoly3D[nIdx++] = aVolPnts[2];\n rPoly3D[nIdx++] = aVolPnts[1];\n }\n if(nZeroCnt == 0 || (aDiff.Z() == 0))\n {\n \/\/ 4---5\n \/\/ \/|\n \/\/ 6 |\n \/\/ 1\n rPoly3D[nIdx++] = aVolPnts[5];\n rPoly3D[nIdx++] = aVolPnts[4];\n rPoly3D[nIdx++] = aVolPnts[5];\n rPoly3D[nIdx++] = aVolPnts[1];\n rPoly3D[nIdx++] = aVolPnts[5];\n rPoly3D[nIdx++] = aVolPnts[6];\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* Konstruktor des Point-Iterators\n|*\n\\************************************************************************\/\n\nVol3DPointIterator::Vol3DPointIterator(const Volume3D& rVol, const Matrix4D* pTf)\n: rVolume(rVol),\n pTransform(pTf),\n nIndex(0)\n{\n DBG_ASSERT(rVol.IsValid(), \"Vol3DPointIterator-Aufruf mit ungueltigem Volume3D!\");\n a3DExtent = rVolume.aMaxVec - rVolume.aMinVec;\n}\n\n\/*************************************************************************\n|*\n|* Gibt die einzelnen Punkte des (ggf. transformierten) Volumens zurueck\n|*\n|* 4---5 -> Reihenfolge der Punktausgabe (untransformiert)\n|* \/| \/|\n|* 7---6 |\n|* | 0-|-1\n|* |\/ |\/\n|* 3---2\n|*\n\\************************************************************************\/\n\nBOOL Vol3DPointIterator::Next(Vector3D& rVec)\n{\n if(nIndex > 7)\n {\n return FALSE;\n }\n else\n {\n rVec = rVolume.aMinVec;\n\n if(nIndex >= 4)\n rVec.Y() += a3DExtent.Y();\n\n switch(nIndex)\n {\n case 6:\n case 2: rVec.Z() += a3DExtent.Z();\n case 5:\n case 1: rVec.X() += a3DExtent.X();\n break;\n case 7:\n case 3: rVec.Z() += a3DExtent.Z();\n break;\n }\n nIndex++;\n\n if(pTransform)\n rVec *= *pTransform;\n\n return TRUE;\n }\n}\n\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*\n * hard formatting (Attribute)\n *\/\n\nvoid SwEditShell::ResetAttr( const std::set &attrs, SwPaM* pPaM )\n{\n SET_CURR_SHELL( this );\n SwPaM* pCrsr = pPaM ? pPaM : GetCrsr( );\n\n StartAllAction();\n bool bUndoGroup = pCrsr->GetNext() != pCrsr;\n if( bUndoGroup )\n {\n GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_RESETATTR, NULL);\n }\n\n SwPaM* pStartCrsr = pCrsr;\n do {\n GetDoc()->ResetAttrs(*pCrsr, true, attrs);\n } while ( ( pCrsr = static_cast< SwPaM* >( pCrsr->GetNext() ) ) != pStartCrsr );\n\n if( bUndoGroup )\n {\n GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_RESETATTR, NULL);\n }\n CallChgLnk();\n EndAllAction();\n}\n\nvoid SwEditShell::GCAttr()\n{\n FOREACHPAM_START(GetCrsr())\n if ( !PCURCRSR->HasMark() )\n {\n SwTxtNode *const pTxtNode =\n PCURCRSR->GetPoint()->nNode.GetNode().GetTxtNode();\n if (pTxtNode)\n {\n pTxtNode->GCAttr();\n }\n }\n else\n {\n const SwNodeIndex& rEnd = PCURCRSR->End()->nNode;\n SwNodeIndex aIdx( PCURCRSR->Start()->nNode );\n SwNode* pNd = &aIdx.GetNode();\n do {\n if( pNd->IsTxtNode() )\n static_cast(pNd)->GCAttr();\n }\n while( 0 != ( pNd = GetDoc()->GetNodes().GoNext( &aIdx )) &&\n aIdx <= rEnd );\n }\n FOREACHPAM_END()\n}\n\n\/\/\/ Set the attribute as new default attribute in the document.\nvoid SwEditShell::SetDefault( const SfxPoolItem& rFmtHint )\n{\n \/\/ 7502: Action-Parenthesis\n StartAllAction();\n GetDoc()->SetDefault( rFmtHint );\n EndAllAction();\n}\n\n\/\/\/ request the default attribute in this document.\nconst SfxPoolItem& SwEditShell::GetDefault( sal_uInt16 nFmtHint ) const\n{\n return GetDoc()->GetDefault( nFmtHint );\n}\n\nvoid SwEditShell::SetAttrItem( const SfxPoolItem& rHint, sal_uInt16 nFlags )\n{\n SET_CURR_SHELL( this );\n StartAllAction();\n SwPaM* pCrsr = GetCrsr();\n if( pCrsr->GetNext() != pCrsr ) \/\/ Ring of Cursors\n {\n bool bIsTblMode = IsTableMode();\n GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_INSATTR, NULL);\n\n FOREACHPAM_START(GetCrsr())\n if( PCURCRSR->HasMark() && ( bIsTblMode ||\n *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() ))\n {\n GetDoc()->getIDocumentContentOperations().InsertPoolItem(*PCURCRSR, rHint, nFlags );\n }\n FOREACHPAM_END()\n\n GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_INSATTR, NULL);\n }\n else\n {\n if( !HasSelection() )\n UpdateAttr();\n GetDoc()->getIDocumentContentOperations().InsertPoolItem( *pCrsr, rHint, nFlags );\n }\n EndAllAction();\n}\n\nvoid SwEditShell::SetAttrSet( const SfxItemSet& rSet, sal_uInt16 nFlags, SwPaM* pPaM )\n{\n SET_CURR_SHELL( this );\n\n SwPaM* pCrsr = pPaM ? pPaM : GetCrsr();\n StartAllAction();\n if( pCrsr->GetNext() != pCrsr ) \/\/ Ring of Cursors\n {\n bool bIsTblMode = IsTableMode();\n GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_INSATTR, NULL);\n\n for(SwPaM& rTmpCrsr : pCrsr->GetRingContainer())\n {\n if( rTmpCrsr.HasMark() && ( bIsTblMode ||\n *rTmpCrsr.GetPoint() != *rTmpCrsr.GetMark() ))\n {\n GetDoc()->getIDocumentContentOperations().InsertItemSet(rTmpCrsr, rSet, nFlags );\n }\n }\n\n GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_INSATTR, NULL);\n }\n else\n {\n if( !HasSelection() )\n UpdateAttr();\n GetDoc()->getIDocumentContentOperations().InsertItemSet( *pCrsr, rSet, nFlags );\n }\n EndAllAction();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nuse C++11 iteration\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*\n * hard formatting (Attribute)\n *\/\n\nvoid SwEditShell::ResetAttr( const std::set &attrs, SwPaM* pPaM )\n{\n SET_CURR_SHELL( this );\n SwPaM* pCrsr = pPaM ? pPaM : GetCrsr( );\n\n StartAllAction();\n bool bUndoGroup = pCrsr->GetNext() != pCrsr;\n if( bUndoGroup )\n {\n GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_RESETATTR, NULL);\n }\n\n for(SwPaM& rCurCrsr : pCrsr->GetRingContainer())\n GetDoc()->ResetAttrs(rCurCrsr, true, attrs);\n\n if( bUndoGroup )\n {\n GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_RESETATTR, NULL);\n }\n CallChgLnk();\n EndAllAction();\n}\n\nvoid SwEditShell::GCAttr()\n{\n FOREACHPAM_START(GetCrsr())\n if ( !PCURCRSR->HasMark() )\n {\n SwTxtNode *const pTxtNode =\n PCURCRSR->GetPoint()->nNode.GetNode().GetTxtNode();\n if (pTxtNode)\n {\n pTxtNode->GCAttr();\n }\n }\n else\n {\n const SwNodeIndex& rEnd = PCURCRSR->End()->nNode;\n SwNodeIndex aIdx( PCURCRSR->Start()->nNode );\n SwNode* pNd = &aIdx.GetNode();\n do {\n if( pNd->IsTxtNode() )\n static_cast(pNd)->GCAttr();\n }\n while( 0 != ( pNd = GetDoc()->GetNodes().GoNext( &aIdx )) &&\n aIdx <= rEnd );\n }\n FOREACHPAM_END()\n}\n\n\/\/\/ Set the attribute as new default attribute in the document.\nvoid SwEditShell::SetDefault( const SfxPoolItem& rFmtHint )\n{\n \/\/ 7502: Action-Parenthesis\n StartAllAction();\n GetDoc()->SetDefault( rFmtHint );\n EndAllAction();\n}\n\n\/\/\/ request the default attribute in this document.\nconst SfxPoolItem& SwEditShell::GetDefault( sal_uInt16 nFmtHint ) const\n{\n return GetDoc()->GetDefault( nFmtHint );\n}\n\nvoid SwEditShell::SetAttrItem( const SfxPoolItem& rHint, sal_uInt16 nFlags )\n{\n SET_CURR_SHELL( this );\n StartAllAction();\n SwPaM* pCrsr = GetCrsr();\n if( pCrsr->GetNext() != pCrsr ) \/\/ Ring of Cursors\n {\n bool bIsTblMode = IsTableMode();\n GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_INSATTR, NULL);\n\n FOREACHPAM_START(GetCrsr())\n if( PCURCRSR->HasMark() && ( bIsTblMode ||\n *PCURCRSR->GetPoint() != *PCURCRSR->GetMark() ))\n {\n GetDoc()->getIDocumentContentOperations().InsertPoolItem(*PCURCRSR, rHint, nFlags );\n }\n FOREACHPAM_END()\n\n GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_INSATTR, NULL);\n }\n else\n {\n if( !HasSelection() )\n UpdateAttr();\n GetDoc()->getIDocumentContentOperations().InsertPoolItem( *pCrsr, rHint, nFlags );\n }\n EndAllAction();\n}\n\nvoid SwEditShell::SetAttrSet( const SfxItemSet& rSet, sal_uInt16 nFlags, SwPaM* pPaM )\n{\n SET_CURR_SHELL( this );\n\n SwPaM* pCrsr = pPaM ? pPaM : GetCrsr();\n StartAllAction();\n if( pCrsr->GetNext() != pCrsr ) \/\/ Ring of Cursors\n {\n bool bIsTblMode = IsTableMode();\n GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_INSATTR, NULL);\n\n for(SwPaM& rTmpCrsr : pCrsr->GetRingContainer())\n {\n if( rTmpCrsr.HasMark() && ( bIsTblMode ||\n *rTmpCrsr.GetPoint() != *rTmpCrsr.GetMark() ))\n {\n GetDoc()->getIDocumentContentOperations().InsertItemSet(rTmpCrsr, rSet, nFlags );\n }\n }\n\n GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_INSATTR, NULL);\n }\n else\n {\n if( !HasSelection() )\n UpdateAttr();\n GetDoc()->getIDocumentContentOperations().InsertItemSet( *pCrsr, rSet, nFlags );\n }\n EndAllAction();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2014 Torsten Rahn \n\/\/\n\n\/\/ Local\n#include \"VerticalPerspectiveProjection.h\"\n#include \"AbstractProjection_p.h\"\n\n#include \"MarbleDebug.h\"\n\n\/\/ Marble\n#include \"ViewportParams.h\"\n#include \"GeoDataPoint.h\"\n#include \"GeoDataLineString.h\"\n#include \"GeoDataCoordinates.h\"\n#include \"MarbleGlobal.h\"\n#include \"AzimuthalProjection_p.h\"\n\n#include \n\n#define SAFE_DISTANCE\n\nnamespace Marble\n{\n\nclass VerticalPerspectiveProjectionPrivate : public AzimuthalProjectionPrivate\n{\n public:\n explicit VerticalPerspectiveProjectionPrivate( VerticalPerspectiveProjection * parent );\n\n void calculateConstants(qreal radius) const;\n qreal getPfromDistance(qreal radius) const;\n\n mutable qreal m_P;\n mutable qreal m_previousRadius;\n mutable qreal m_altitudeToPixel;\n mutable qreal m_perspectiveRadius;\n mutable qreal m_pPfactor;\n\n Q_DECLARE_PUBLIC( VerticalPerspectiveProjection )\n};\n\nVerticalPerspectiveProjection::VerticalPerspectiveProjection()\n : AzimuthalProjection( new VerticalPerspectiveProjectionPrivate( this ) )\n{\n setMinLat( minValidLat() );\n setMaxLat( maxValidLat() );\n}\n\nVerticalPerspectiveProjection::VerticalPerspectiveProjection( VerticalPerspectiveProjectionPrivate *dd )\n : AzimuthalProjection( dd )\n{\n setMinLat( minValidLat() );\n setMaxLat( maxValidLat() );\n}\n\nVerticalPerspectiveProjection::~VerticalPerspectiveProjection()\n{\n}\n\n\nVerticalPerspectiveProjectionPrivate::VerticalPerspectiveProjectionPrivate( VerticalPerspectiveProjection * parent )\n : AzimuthalProjectionPrivate( parent ),\n m_P(1),\n m_previousRadius(1),\n m_altitudeToPixel(1),\n m_perspectiveRadius(1),\n m_pPfactor(1)\n{\n}\n\n\nQString VerticalPerspectiveProjection::name() const\n{\n return QObject::tr( \"Vertical Perspective Projection\" );\n}\n\nQString VerticalPerspectiveProjection::description() const\n{\n return QObject::tr( \"

Vertical Perspective Projection<\/b> (\\\"orthogonal\\\")<\/p>

Shows the earth as it appears from a relatively short distance above the surface. Applications: Used for Virtual Globes.<\/p>\" );\n}\n\nQIcon VerticalPerspectiveProjection::icon() const\n{\n return QIcon(\":\/icons\/map-globe.png\");\n}\n\nvoid VerticalPerspectiveProjectionPrivate::calculateConstants(qreal radius) const\n{\n if (radius == m_previousRadius) return;\n m_previousRadius = radius;\n m_P = getPfromDistance(radius);\n m_altitudeToPixel = radius \/ (EARTH_RADIUS * qSqrt((m_P-1)\/(m_P+1)));\n m_perspectiveRadius = radius \/ qSqrt((m_P-1)\/(m_P+1));\n m_pPfactor = (m_P+1)\/(m_perspectiveRadius*m_perspectiveRadius*(m_P-1));\n}\n\nqreal VerticalPerspectiveProjectionPrivate::getPfromDistance(qreal radius) const {\n \/\/ Return the Distance of the point of perspective in earth diameters\n qreal distance = 3 * 1000 * EARTH_RADIUS * 0.4 \/ radius \/ qTan(0.5 * 110 * DEG2RAD);\n return 1.5 + distance \/ EARTH_RADIUS;\n}\n\nqreal VerticalPerspectiveProjection::clippingRadius() const\n{\n return 1;\n}\n\nbool VerticalPerspectiveProjection::screenCoordinates( const GeoDataCoordinates &coordinates,\n const ViewportParams *viewport,\n qreal &x, qreal &y, bool &globeHidesPoint ) const\n{\n Q_D(const VerticalPerspectiveProjection);\n d->calculateConstants(viewport->radius());\n const qreal P = d->m_P; \/\/ Distance of the point of perspective in earth diameters\n const qreal deltaLambda = coordinates.longitude() - viewport->centerLongitude();\n const qreal phi = coordinates.latitude();\n const qreal phi1 = viewport->centerLatitude();\n\n qreal cosC = qSin( phi1 ) * qSin( phi ) + qCos( phi1 ) * qCos( phi ) * qCos( deltaLambda );\n\n \/\/ Don't display placemarks that are below 10km altitude and\n \/\/ are on the Earth's backside (where cosC < 1\/P)\n if (cosC < 1\/P && coordinates.altitude() < 10000) {\n globeHidesPoint = true;\n return false;\n }\n\n \/\/ Let (x, y) be the position on the screen of the placemark ..\n \/\/ First determine the position in unit coordinates:\n qreal k = (P - 1) \/ (P - cosC); \/\/ scale factor\n x = ( qCos( phi ) * qSin( deltaLambda ) ) * k;\n y = ( qCos( phi1 ) * qSin( phi ) - qSin( phi1 ) * qCos( phi ) * qCos( deltaLambda ) ) * k;\n\n \/\/ Transform to screen coordinates\n qreal pixelAltitude = (coordinates.altitude() + EARTH_RADIUS) * d->m_altitudeToPixel;\n x *= pixelAltitude;\n y *= pixelAltitude;\n\n\n \/\/ Don't display satellites that are on the Earth's backside:\n if (cosC < 1\/P && x*x+y*y < viewport->radius() * viewport->radius()) {\n globeHidesPoint = true;\n return false;\n }\n \/\/ The remaining placemarks are definetely not on the Earth's backside\n globeHidesPoint = false;\n\n x += viewport->width() \/ 2;\n y = viewport->height() \/ 2 - y;\n\n \/\/ Skip placemarks that are outside the screen area\n if ( x < 0 || x >= viewport->width() || y < 0 || y >= viewport->height() ) {\n return false;\n }\n\n return true;\n}\n\nbool VerticalPerspectiveProjection::screenCoordinates( const GeoDataCoordinates &coordinates,\n const ViewportParams *viewport,\n qreal *x, qreal &y,\n int &pointRepeatNum,\n const QSizeF& size,\n bool &globeHidesPoint ) const\n{\n pointRepeatNum = 0;\n globeHidesPoint = false;\n\n bool visible = screenCoordinates( coordinates, viewport, *x, y, globeHidesPoint );\n\n \/\/ Skip placemarks that are outside the screen area\n if ( *x + size.width() \/ 2.0 < 0.0 || *x >= viewport->width() + size.width() \/ 2.0\n || y + size.height() \/ 2.0 < 0.0 || y >= viewport->height() + size.height() \/ 2.0 )\n {\n return false;\n }\n\n \/\/ This projection doesn't have any repetitions,\n \/\/ so the number of screen points referring to the geopoint is one.\n pointRepeatNum = 1;\n return visible;\n}\n\n\nbool VerticalPerspectiveProjection::geoCoordinates( const int x, const int y,\n const ViewportParams *viewport,\n qreal& lon, qreal& lat,\n GeoDataCoordinates::Unit unit ) const\n{\n Q_D(const VerticalPerspectiveProjection);\n d->calculateConstants(viewport->radius());\n const qreal P = d->m_P;\n const qreal rx = ( - viewport->width() \/ 2 + x );\n const qreal ry = ( viewport->height() \/ 2 - y );\n const qreal p2 = rx*rx + ry*ry;\n\n if (p2 == 0) {\n lon = viewport->centerLongitude();\n lat = viewport->centerLatitude();\n return true;\n }\n\n const qreal pP = p2*d->m_pPfactor;\n\n if ( pP > 1) return false;\n\n const qreal p = qSqrt(p2);\n const qreal fract = d->m_perspectiveRadius*(P-1)\/p;\n const qreal c = qAsin((P-qSqrt(1-pP))\/(fract+1\/fract));\n const qreal sinc = qSin(c);\n\n const qreal centerLon = viewport->centerLongitude();\n const qreal centerLat = viewport->centerLatitude();\n lon = centerLon + qAtan2(rx*sinc, (p*qCos(centerLat)*qCos(c) - ry*qSin(centerLat)*sinc));\n\n while ( lon < -M_PI ) lon += 2 * M_PI;\n while ( lon > M_PI ) lon -= 2 * M_PI;\n\n lat = qAsin(qCos(c)*qSin(centerLat) + (ry*sinc*qCos(centerLat))\/p);\n\n if ( unit == GeoDataCoordinates::Degree ) {\n lon *= RAD2DEG;\n lat *= RAD2DEG;\n }\n\n return true;\n}\n\n}\nsimplify\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2014 Torsten Rahn \n\/\/\n\n\/\/ Local\n#include \"VerticalPerspectiveProjection.h\"\n#include \"AbstractProjection_p.h\"\n\n#include \"MarbleDebug.h\"\n\n\/\/ Marble\n#include \"ViewportParams.h\"\n#include \"GeoDataPoint.h\"\n#include \"GeoDataLineString.h\"\n#include \"GeoDataCoordinates.h\"\n#include \"MarbleGlobal.h\"\n#include \"AzimuthalProjection_p.h\"\n\n#include \n\n#define SAFE_DISTANCE\n\nnamespace Marble\n{\n\nclass VerticalPerspectiveProjectionPrivate : public AzimuthalProjectionPrivate\n{\n public:\n explicit VerticalPerspectiveProjectionPrivate( VerticalPerspectiveProjection * parent );\n\n void calculateConstants(qreal radius) const;\n\n mutable qreal m_P; \/\/\/< Distance of the point of perspective in earth diameters\n mutable qreal m_previousRadius;\n mutable qreal m_altitudeToPixel;\n mutable qreal m_perspectiveRadius;\n mutable qreal m_pPfactor;\n\n Q_DECLARE_PUBLIC( VerticalPerspectiveProjection )\n};\n\nVerticalPerspectiveProjection::VerticalPerspectiveProjection()\n : AzimuthalProjection( new VerticalPerspectiveProjectionPrivate( this ) )\n{\n setMinLat( minValidLat() );\n setMaxLat( maxValidLat() );\n}\n\nVerticalPerspectiveProjection::VerticalPerspectiveProjection( VerticalPerspectiveProjectionPrivate *dd )\n : AzimuthalProjection( dd )\n{\n setMinLat( minValidLat() );\n setMaxLat( maxValidLat() );\n}\n\nVerticalPerspectiveProjection::~VerticalPerspectiveProjection()\n{\n}\n\n\nVerticalPerspectiveProjectionPrivate::VerticalPerspectiveProjectionPrivate( VerticalPerspectiveProjection * parent )\n : AzimuthalProjectionPrivate( parent ),\n m_P(1),\n m_previousRadius(1),\n m_altitudeToPixel(1),\n m_perspectiveRadius(1),\n m_pPfactor(1)\n{\n}\n\n\nQString VerticalPerspectiveProjection::name() const\n{\n return QObject::tr( \"Vertical Perspective Projection\" );\n}\n\nQString VerticalPerspectiveProjection::description() const\n{\n return QObject::tr( \"

Vertical Perspective Projection<\/b> (\\\"orthogonal\\\")<\/p>

Shows the earth as it appears from a relatively short distance above the surface. Applications: Used for Virtual Globes.<\/p>\" );\n}\n\nQIcon VerticalPerspectiveProjection::icon() const\n{\n return QIcon(\":\/icons\/map-globe.png\");\n}\n\nvoid VerticalPerspectiveProjectionPrivate::calculateConstants(qreal radius) const\n{\n if (radius == m_previousRadius) return;\n m_previousRadius = radius;\n m_P = 1.5 + 3 * 1000 * 0.4 \/ radius \/ qTan(0.5 * 110 * DEG2RAD);\n m_altitudeToPixel = radius \/ (EARTH_RADIUS * qSqrt((m_P-1)\/(m_P+1)));\n m_perspectiveRadius = radius \/ qSqrt((m_P-1)\/(m_P+1));\n m_pPfactor = (m_P+1)\/(m_perspectiveRadius*m_perspectiveRadius*(m_P-1));\n}\n\nqreal VerticalPerspectiveProjection::clippingRadius() const\n{\n return 1;\n}\n\nbool VerticalPerspectiveProjection::screenCoordinates( const GeoDataCoordinates &coordinates,\n const ViewportParams *viewport,\n qreal &x, qreal &y, bool &globeHidesPoint ) const\n{\n Q_D(const VerticalPerspectiveProjection);\n d->calculateConstants(viewport->radius());\n const qreal P = d->m_P;\n const qreal deltaLambda = coordinates.longitude() - viewport->centerLongitude();\n const qreal phi = coordinates.latitude();\n const qreal phi1 = viewport->centerLatitude();\n\n qreal cosC = qSin( phi1 ) * qSin( phi ) + qCos( phi1 ) * qCos( phi ) * qCos( deltaLambda );\n\n \/\/ Don't display placemarks that are below 10km altitude and\n \/\/ are on the Earth's backside (where cosC < 1\/P)\n if (cosC < 1\/P && coordinates.altitude() < 10000) {\n globeHidesPoint = true;\n return false;\n }\n\n \/\/ Let (x, y) be the position on the screen of the placemark ..\n \/\/ First determine the position in unit coordinates:\n qreal k = (P - 1) \/ (P - cosC); \/\/ scale factor\n x = ( qCos( phi ) * qSin( deltaLambda ) ) * k;\n y = ( qCos( phi1 ) * qSin( phi ) - qSin( phi1 ) * qCos( phi ) * qCos( deltaLambda ) ) * k;\n\n \/\/ Transform to screen coordinates\n qreal pixelAltitude = (coordinates.altitude() + EARTH_RADIUS) * d->m_altitudeToPixel;\n x *= pixelAltitude;\n y *= pixelAltitude;\n\n\n \/\/ Don't display satellites that are on the Earth's backside:\n if (cosC < 1\/P && x*x+y*y < viewport->radius() * viewport->radius()) {\n globeHidesPoint = true;\n return false;\n }\n \/\/ The remaining placemarks are definetely not on the Earth's backside\n globeHidesPoint = false;\n\n x += viewport->width() \/ 2;\n y = viewport->height() \/ 2 - y;\n\n \/\/ Skip placemarks that are outside the screen area\n if ( x < 0 || x >= viewport->width() || y < 0 || y >= viewport->height() ) {\n return false;\n }\n\n return true;\n}\n\nbool VerticalPerspectiveProjection::screenCoordinates( const GeoDataCoordinates &coordinates,\n const ViewportParams *viewport,\n qreal *x, qreal &y,\n int &pointRepeatNum,\n const QSizeF& size,\n bool &globeHidesPoint ) const\n{\n pointRepeatNum = 0;\n globeHidesPoint = false;\n\n bool visible = screenCoordinates( coordinates, viewport, *x, y, globeHidesPoint );\n\n \/\/ Skip placemarks that are outside the screen area\n if ( *x + size.width() \/ 2.0 < 0.0 || *x >= viewport->width() + size.width() \/ 2.0\n || y + size.height() \/ 2.0 < 0.0 || y >= viewport->height() + size.height() \/ 2.0 )\n {\n return false;\n }\n\n \/\/ This projection doesn't have any repetitions,\n \/\/ so the number of screen points referring to the geopoint is one.\n pointRepeatNum = 1;\n return visible;\n}\n\n\nbool VerticalPerspectiveProjection::geoCoordinates( const int x, const int y,\n const ViewportParams *viewport,\n qreal& lon, qreal& lat,\n GeoDataCoordinates::Unit unit ) const\n{\n Q_D(const VerticalPerspectiveProjection);\n d->calculateConstants(viewport->radius());\n const qreal P = d->m_P;\n const qreal rx = ( - viewport->width() \/ 2 + x );\n const qreal ry = ( viewport->height() \/ 2 - y );\n const qreal p2 = rx*rx + ry*ry;\n\n if (p2 == 0) {\n lon = viewport->centerLongitude();\n lat = viewport->centerLatitude();\n return true;\n }\n\n const qreal pP = p2*d->m_pPfactor;\n\n if ( pP > 1) return false;\n\n const qreal p = qSqrt(p2);\n const qreal fract = d->m_perspectiveRadius*(P-1)\/p;\n const qreal c = qAsin((P-qSqrt(1-pP))\/(fract+1\/fract));\n const qreal sinc = qSin(c);\n\n const qreal centerLon = viewport->centerLongitude();\n const qreal centerLat = viewport->centerLatitude();\n lon = centerLon + qAtan2(rx*sinc, (p*qCos(centerLat)*qCos(c) - ry*qSin(centerLat)*sinc));\n\n while ( lon < -M_PI ) lon += 2 * M_PI;\n while ( lon > M_PI ) lon -= 2 * M_PI;\n\n lat = qAsin(qCos(c)*qSin(centerLat) + (ry*sinc*qCos(centerLat))\/p);\n\n if ( unit == GeoDataCoordinates::Degree ) {\n lon *= RAD2DEG;\n lat *= RAD2DEG;\n }\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"ws, warnings<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmltbli.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: vg $ $Date: 2007-02-28 15:55:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLTBLI_HXX\n#define _XMLTBLI_HXX\n\n#ifndef _XMLOFF_XMLTEXTTABLECONTEXT_HXX\n#include \n#endif\n\n\/\/ STL include\n#include \n\n#if !defined(_SVSTDARR_USHORTS_DECL) || !defined(_SVSTDARR_BOOLS_DECL) || !defined(_SVSTDARR_STRINGSDTOR_DECL)\n#define _SVSTDARR_USHORTS\n#define _SVSTDARR_BOOLS\n#define _SVSTDARR_STRINGSDTOR\n#include \n#endif\n\nclass SwXMLImport;\nclass SwTableNode;\nclass SwTableBox;\nclass SwTableLine;\nclass SwStartNode;\nclass SwTableBoxFmt;\nclass SwTableLineFmt;\nclass SwXMLTableCell_Impl;\nclass SwXMLTableRows_Impl;\nclass SwXMLDDETableContext_Impl;\nclass TableBoxIndexHasher;\nclass TableBoxIndex;\n\nnamespace com { namespace sun { namespace star {\n namespace text { class XTextContent; }\n namespace text { class XTextCursor; }\n} } }\n\n\n\nclass SwXMLTableContext : public XMLTextTableContext\n{\n ::rtl::OUString aStyleName;\n ::rtl::OUString aDfltCellStyleName;\n\n SvUShorts aColumnWidths;\n SvBools aColumnRelWidths;\n SvStringsDtor *pColumnDefaultCellStyleNames;\n\n ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextCursor > xOldCursor;\n ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextContent > xTextContent;\n\n SwXMLTableRows_Impl *pRows;\n\n SwTableNode *pTableNode;\n SwTableBox *pBox1;\n const SwStartNode *pSttNd1;\n\n SwTableBoxFmt *pBoxFmt;\n SwTableLineFmt *pLineFmt;\n\n \/\/ hash map of shared format, indexed by the (XML) style name,\n \/\/ the column width, and protection flag\n typedef std::hash_map map_BoxFmt;\n map_BoxFmt* pSharedBoxFormats;\n\n SvXMLImportContextRef xParentTable; \/\/ if table is a sub table\n\n SwXMLDDETableContext_Impl *pDDESource;\n\n sal_Bool bFirstSection : 1;\n sal_Bool bRelWidth : 1;\n sal_Bool bHasSubTables : 1;\n\n USHORT nHeaderRows;\n sal_uInt32 nCurRow;\n sal_uInt32 nCurCol;\n sal_Int32 nWidth;\n\n SwTableBox *NewTableBox( const SwStartNode *pStNd,\n SwTableLine *pUpper );\n SwTableBox *MakeTableBox( SwTableLine *pUpper,\n const SwXMLTableCell_Impl *pStartNode,\n sal_uInt32 nTopRow, sal_uInt32 nLeftCol,\n sal_uInt32 nBottomRow, sal_uInt32 nRightCol );\n SwTableBox *MakeTableBox( SwTableLine *pUpper,\n sal_uInt32 nTopRow, sal_uInt32 nLeftCol,\n sal_uInt32 nBottomRow, sal_uInt32 nRightCol );\n SwTableLine *MakeTableLine( SwTableBox *pUpper,\n sal_uInt32 nTopRow, sal_uInt32 nLeftCol,\n sal_uInt32 nBottomRow, sal_uInt32 nRightCol );\n\n void _MakeTable( SwTableBox *pBox=0 );\n void MakeTable( SwTableBox *pBox, sal_Int32 nWidth );\n void MakeTable();\n\n inline SwXMLTableContext *GetParentTable() const;\n\n const SwStartNode *GetPrevStartNode( sal_uInt32 nRow,\n sal_uInt32 nCol ) const;\n inline const SwStartNode *GetLastStartNode() const;\n void FixRowSpan( sal_uInt32 nRow, sal_uInt32 nCol, sal_uInt32 nColSpan );\n void ReplaceWithEmptyCell( sal_uInt32 nRow, sal_uInt32 nCol, bool bRows );\n\n \/** sets the appropriate SwTblBoxFmt at pBox. *\/\n SwTableBoxFmt* GetSharedBoxFormat(\n SwTableBox* pBox, \/\/\/ the table box\n const ::rtl::OUString& rStyleName, \/\/\/ XML style name\n sal_Int32 nColumnWidth, \/\/\/ width of column\n sal_Bool bProtected, \/\/\/ is cell protected?\n sal_Bool bMayShare, \/\/\/ may the format be shared (no value, formula...)\n sal_Bool& bNew, \/\/\/ true, if the format it not from the cache\n sal_Bool* pModifyLocked ); \/\/\/ if set, call pBox->LockModify() and return old lock status\n\npublic:\n\n TYPEINFO();\n\n SwXMLTableContext( SwXMLImport& rImport, sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n SwXMLTableContext( SwXMLImport& rImport, sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList,\n SwXMLTableContext *pTable );\n\n virtual ~SwXMLTableContext();\n\n virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n\n SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); }\n\n void InsertColumn( sal_Int32 nWidth, sal_Bool bRelWidth,\n const ::rtl::OUString *pDfltCellStyleName = 0 );\n sal_Int32 GetColumnWidth( sal_uInt32 nCol, sal_uInt32 nColSpan=1UL ) const;\n ::rtl::OUString GetColumnDefaultCellStyleName( sal_uInt32 nCol ) const;\n inline sal_uInt32 GetColumnCount() const;\n inline sal_Bool HasColumnDefaultCellStyleNames() const;\n\n sal_Bool IsInsertCellPossible() const { return nCurCol < GetColumnCount(); }\n sal_Bool IsInsertColPossible() const { return nCurCol < USHRT_MAX; }\n sal_Bool IsInsertRowPossible() const { return nCurRow < USHRT_MAX; }\n sal_Bool IsValid() const { return pTableNode != 0; }\n\n void InsertCell( const ::rtl::OUString& rStyleName,\n sal_uInt32 nRowSpan=1U, sal_uInt32 nColSpan=1U,\n const SwStartNode *pStNd=0,\n SwXMLTableContext *pTable=0,\n sal_Bool bIsProtected = sal_False,\n const ::rtl::OUString *pFormula=0,\n sal_Bool bHasValue = sal_False,\n double fValue = 0.0 );\n void InsertRow( const ::rtl::OUString& rStyleName,\n const ::rtl::OUString& rDfltCellStyleName,\n sal_Bool bInHead );\n void FinishRow();\n void InsertRepRows( sal_uInt32 nCount );\n SwXMLTableCell_Impl *GetCell( sal_uInt32 nRow, sal_uInt32 nCol ) const;\n const SwStartNode *InsertTableSection( const SwStartNode *pPrevSttNd=0 );\n\n virtual void EndElement();\n\n virtual ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextContent > GetXTextContent() const;\n\n void SetHasSubTables( sal_Bool bNew ) { bHasSubTables = bNew; }\n};\n\ninline SwXMLTableContext *SwXMLTableContext::GetParentTable() const\n{\n return (SwXMLTableContext *)&xParentTable;\n}\n\ninline sal_uInt32 SwXMLTableContext::GetColumnCount() const\n{\n return aColumnWidths.Count();\n}\n\ninline const SwStartNode *SwXMLTableContext::GetLastStartNode() const\n{\n return GetPrevStartNode( 0UL, GetColumnCount() );\n}\n\ninline sal_Bool SwXMLTableContext::HasColumnDefaultCellStyleNames() const\n{\n return pColumnDefaultCellStyleNames != 0;\n}\n\n#endif\nINTEGRATION: CWS rpt23fix01 (1.15.162); FILE MERGED 2007\/07\/12 11:03:20 ama 1.15.162.1: Fix #i78685#: Text value\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmltbli.hxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: hr $ $Date: 2007-08-02 14:22:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLTBLI_HXX\n#define _XMLTBLI_HXX\n\n#ifndef _XMLOFF_XMLTEXTTABLECONTEXT_HXX\n#include \n#endif\n\n\/\/ STL include\n#include \n\n#if !defined(_SVSTDARR_USHORTS_DECL) || !defined(_SVSTDARR_BOOLS_DECL) || !defined(_SVSTDARR_STRINGSDTOR_DECL)\n#define _SVSTDARR_USHORTS\n#define _SVSTDARR_BOOLS\n#define _SVSTDARR_STRINGSDTOR\n#include \n#endif\n\nclass SwXMLImport;\nclass SwTableNode;\nclass SwTableBox;\nclass SwTableLine;\nclass SwStartNode;\nclass SwTableBoxFmt;\nclass SwTableLineFmt;\nclass SwXMLTableCell_Impl;\nclass SwXMLTableRows_Impl;\nclass SwXMLDDETableContext_Impl;\nclass TableBoxIndexHasher;\nclass TableBoxIndex;\n\nnamespace com { namespace sun { namespace star {\n namespace text { class XTextContent; }\n namespace text { class XTextCursor; }\n} } }\n\n\n\nclass SwXMLTableContext : public XMLTextTableContext\n{\n ::rtl::OUString aStyleName;\n ::rtl::OUString aDfltCellStyleName;\n\n SvUShorts aColumnWidths;\n SvBools aColumnRelWidths;\n SvStringsDtor *pColumnDefaultCellStyleNames;\n\n ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextCursor > xOldCursor;\n ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextContent > xTextContent;\n\n SwXMLTableRows_Impl *pRows;\n\n SwTableNode *pTableNode;\n SwTableBox *pBox1;\n const SwStartNode *pSttNd1;\n\n SwTableBoxFmt *pBoxFmt;\n SwTableLineFmt *pLineFmt;\n\n \/\/ hash map of shared format, indexed by the (XML) style name,\n \/\/ the column width, and protection flag\n typedef std::hash_map map_BoxFmt;\n map_BoxFmt* pSharedBoxFormats;\n\n SvXMLImportContextRef xParentTable; \/\/ if table is a sub table\n\n SwXMLDDETableContext_Impl *pDDESource;\n\n sal_Bool bFirstSection : 1;\n sal_Bool bRelWidth : 1;\n sal_Bool bHasSubTables : 1;\n\n USHORT nHeaderRows;\n sal_uInt32 nCurRow;\n sal_uInt32 nCurCol;\n sal_Int32 nWidth;\n\n SwTableBox *NewTableBox( const SwStartNode *pStNd,\n SwTableLine *pUpper );\n SwTableBox *MakeTableBox( SwTableLine *pUpper,\n const SwXMLTableCell_Impl *pStartNode,\n sal_uInt32 nTopRow, sal_uInt32 nLeftCol,\n sal_uInt32 nBottomRow, sal_uInt32 nRightCol );\n SwTableBox *MakeTableBox( SwTableLine *pUpper,\n sal_uInt32 nTopRow, sal_uInt32 nLeftCol,\n sal_uInt32 nBottomRow, sal_uInt32 nRightCol );\n SwTableLine *MakeTableLine( SwTableBox *pUpper,\n sal_uInt32 nTopRow, sal_uInt32 nLeftCol,\n sal_uInt32 nBottomRow, sal_uInt32 nRightCol );\n\n void _MakeTable( SwTableBox *pBox=0 );\n void MakeTable( SwTableBox *pBox, sal_Int32 nWidth );\n void MakeTable();\n\n inline SwXMLTableContext *GetParentTable() const;\n\n const SwStartNode *GetPrevStartNode( sal_uInt32 nRow,\n sal_uInt32 nCol ) const;\n inline const SwStartNode *GetLastStartNode() const;\n void FixRowSpan( sal_uInt32 nRow, sal_uInt32 nCol, sal_uInt32 nColSpan );\n void ReplaceWithEmptyCell( sal_uInt32 nRow, sal_uInt32 nCol, bool bRows );\n\n \/** sets the appropriate SwTblBoxFmt at pBox. *\/\n SwTableBoxFmt* GetSharedBoxFormat(\n SwTableBox* pBox, \/\/\/ the table box\n const ::rtl::OUString& rStyleName, \/\/\/ XML style name\n sal_Int32 nColumnWidth, \/\/\/ width of column\n sal_Bool bProtected, \/\/\/ is cell protected?\n sal_Bool bMayShare, \/\/\/ may the format be shared (no value, formula...)\n sal_Bool& bNew, \/\/\/ true, if the format it not from the cache\n sal_Bool* pModifyLocked ); \/\/\/ if set, call pBox->LockModify() and return old lock status\n\npublic:\n\n TYPEINFO();\n\n SwXMLTableContext( SwXMLImport& rImport, sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n SwXMLTableContext( SwXMLImport& rImport, sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList,\n SwXMLTableContext *pTable );\n\n virtual ~SwXMLTableContext();\n\n virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n\n SwXMLImport& GetSwImport() { return (SwXMLImport&)GetImport(); }\n\n void InsertColumn( sal_Int32 nWidth, sal_Bool bRelWidth,\n const ::rtl::OUString *pDfltCellStyleName = 0 );\n sal_Int32 GetColumnWidth( sal_uInt32 nCol, sal_uInt32 nColSpan=1UL ) const;\n ::rtl::OUString GetColumnDefaultCellStyleName( sal_uInt32 nCol ) const;\n inline sal_uInt32 GetColumnCount() const;\n inline sal_Bool HasColumnDefaultCellStyleNames() const;\n\n sal_Bool IsInsertCellPossible() const { return nCurCol < GetColumnCount(); }\n sal_Bool IsInsertColPossible() const { return nCurCol < USHRT_MAX; }\n sal_Bool IsInsertRowPossible() const { return nCurRow < USHRT_MAX; }\n sal_Bool IsValid() const { return pTableNode != 0; }\n\n void InsertCell( const ::rtl::OUString& rStyleName,\n sal_uInt32 nRowSpan=1U, sal_uInt32 nColSpan=1U,\n const SwStartNode *pStNd=0,\n SwXMLTableContext *pTable=0,\n sal_Bool bIsProtected = sal_False,\n const ::rtl::OUString *pFormula=0,\n sal_Bool bHasValue = sal_False,\n double fValue = 0.0,\n sal_Bool bTextValue = sal_False );\n void InsertRow( const ::rtl::OUString& rStyleName,\n const ::rtl::OUString& rDfltCellStyleName,\n sal_Bool bInHead );\n void FinishRow();\n void InsertRepRows( sal_uInt32 nCount );\n SwXMLTableCell_Impl *GetCell( sal_uInt32 nRow, sal_uInt32 nCol ) const;\n const SwStartNode *InsertTableSection( const SwStartNode *pPrevSttNd=0 );\n\n virtual void EndElement();\n\n virtual ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextContent > GetXTextContent() const;\n\n void SetHasSubTables( sal_Bool bNew ) { bHasSubTables = bNew; }\n};\n\ninline SwXMLTableContext *SwXMLTableContext::GetParentTable() const\n{\n return (SwXMLTableContext *)&xParentTable;\n}\n\ninline sal_uInt32 SwXMLTableContext::GetColumnCount() const\n{\n return aColumnWidths.Count();\n}\n\ninline const SwStartNode *SwXMLTableContext::GetLastStartNode() const\n{\n return GetPrevStartNode( 0UL, GetColumnCount() );\n}\n\ninline sal_Bool SwXMLTableContext::HasColumnDefaultCellStyleNames() const\n{\n return pColumnDefaultCellStyleNames != 0;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file\n *\/\n#pragma once\n\n#include \"numbirch\/type.hpp\"\n\n\/* for recent versions of CUDA, disables warnings about diag_suppress being\n * deprecated in favor of nv_diag_suppress *\/\n#pragma nv_diag_suppress 20236\n\n#if defined(HAVE_UNSUPPORTED_EIGEN_SPECIALFUNCTIONS)\n#include \n#elif defined(HAVE_EIGEN3_UNSUPPORTED_EIGEN_SPECIALFUNCTIONS)\n#include \n#endif\n\nnamespace numbirch {\nstatic const long double PI = 3.1415926535897932384626433832795;\n\ntemplate\nstruct identity_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return x;\n }\n};\n\ntemplate\nstruct negate_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return -x;\n }\n};\n\ntemplate\nstruct add_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x + y;\n }\n};\n\ntemplate\nstruct subtract_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x - y;\n }\n};\n\ntemplate\nstruct multiply_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x*y;\n }\n};\n\ntemplate\nstruct divide_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x\/y;\n }\n};\n\ntemplate\nstruct not_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return !x;\n }\n};\n\ntemplate\nstruct and_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x && y;\n }\n};\n\ntemplate\nstruct or_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x || y;\n }\n};\n\ntemplate\nstruct equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x == y;\n }\n};\n\ntemplate\nstruct not_equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x != y;\n }\n};\n\ntemplate\nstruct less_functor {\n NUMBIRCH_HOST_DEVICE bool operator()(const T x, const T y) const {\n return x < y;\n }\n};\n\ntemplate\nstruct less_or_equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x <= y;\n }\n};\n\ntemplate\nstruct greater_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x > y;\n }\n};\n\ntemplate\nstruct greater_or_equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x >= y;\n }\n};\n\ntemplate\nstruct abs_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::abs(x);\n }\n};\n\ntemplate,int>>\nstruct acos_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::acos(x);\n }\n};\n\ntemplate,int>>\nstruct asin_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::asin(x);\n }\n};\n\ntemplate,int>>\nstruct atan_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::atan(x);\n }\n};\n\ntemplate\nstruct ceil_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n if constexpr (is_integral_v) {\n return x;\n } else {\n return std::ceil(x);\n }\n }\n};\n\ntemplate,int>>\nstruct cos_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::cos(x);\n }\n};\n\ntemplate,int>>\nstruct cosh_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::cosh(x);\n }\n};\n\ntemplate\nstruct count_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return (x == 0) ? 0 : 1;\n }\n};\n\ntemplate\nstruct diagonal_functor {\n diagonal_functor(const U a) :\n a(a) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE auto operator()(const int i, const int j) const {\n return (i == j) ? T(element(a)) : 0;\n }\n const U a;\n};\n\ntemplate,int>>\nstruct digamma_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return Eigen::numext::digamma(x);\n }\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n T z = 0;\n for (T i = 1; i <= y; ++i) {\n z += Eigen::numext::digamma(x + T(0.5)*(1 - i));\n }\n return z;\n }\n};\n\ntemplate,int>>\nstruct exp_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::exp(x);\n }\n};\n\ntemplate,int>>\nstruct expm1_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::expm1(x);\n }\n};\n\ntemplate\nstruct floor_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n if constexpr (is_integral_v) {\n return x;\n } else {\n return std::floor(x);\n }\n }\n};\n\ntemplate,int>>\nstruct lfact_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::lgamma(x + T(1));\n }\n};\n\ntemplate,int>>\nstruct lfact_grad_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T g, const T x) const {\n return g*Eigen::numext::digamma(x + T(1));\n }\n};\n\ntemplate,int>>\nstruct lgamma_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::lgamma(x);\n }\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n T z = T(0.25)*y*(y - T(1))*std::log(T(PI));\n for (T i = T(1); i <= y; ++i) {\n z += std::lgamma(x + T(0.5)*(T(1) - i));\n }\n return z;\n }\n};\n\ntemplate,int>>\nstruct log_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::log(x);\n }\n};\n\ntemplate,int>>\nstruct log1p_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::log1p(x);\n }\n};\n\ntemplate,int>>\nstruct log_abs_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::log(std::abs(x));\n }\n};\n\ntemplate,int>>\nstruct log_square_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return T(2)*std::log(x);\n }\n};\n\ntemplate,int>>\nstruct rcp_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return T(1)\/x;\n }\n};\n\ntemplate\nstruct rectify_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::max(T(0), x);\n }\n};\n\ntemplate,int>>\nstruct rectify_grad_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T g, const T x) const {\n return (x > T(0)) ? g : T(0);\n }\n};\n\ntemplate\nstruct round_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n if constexpr (is_integral_v) {\n return x;\n } else {\n return std::round(x);\n }\n }\n};\n\ntemplate,int>>\nstruct sin_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::sin(x);\n }\n};\n\ntemplate,int>>\nstruct sinh_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::sinh(x);\n }\n};\n\ntemplate,int>>\nstruct sqrt_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::sqrt(x);\n }\n};\n\ntemplate,int>>\nstruct tan_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::tan(x);\n }\n};\n\ntemplate,int>>\nstruct tanh_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::tanh(x);\n }\n};\n\ntemplate\nstruct copysign_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n if constexpr (is_integral_v) {\n \/\/ don't use std::copysign, as it promotes to floating point, which\n \/\/ we don't wish to do here\n return (y >= T(0)) ? std::abs(x) : -std::abs(x);\n } else {\n return std::copysign(x, y);\n }\n }\n};\n\ntemplate,int>>\nstruct gamma_p_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T a, const T x) const {\n return Eigen::numext::igamma(a, x);\n }\n};\n\ntemplate,int>>\nstruct gamma_q_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T a, const T x) const {\n return Eigen::numext::igammac(a, x);\n }\n};\n\ntemplate,int>>\nstruct lbeta_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return std::lgamma(x) + std::lgamma(y) - std::lgamma(x + y);\n }\n};\n\ntemplate,int>>\nstruct lchoose_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const int x, const int y) const {\n return std::lgamma(x + T(1)) - std::lgamma(y + T(1)) - std::lgamma(x - y);\n }\n};\n\ntemplate,int>>\nstruct lchoose_grad_functor {\n NUMBIRCH_HOST_DEVICE pair operator()(const T g, const T x, const T y)\n const {\n T gx = Eigen::numext::digamma(x + T(1)) -\n Eigen::numext::digamma(x - y + T(1));\n T gy = -Eigen::numext::digamma(y + T(1)) +\n Eigen::numext::digamma(x - y + T(1));\n return pair{g*gx, g*gy};\n }\n};\n\ntemplate,int>>\nstruct pow_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return std::pow(x, y);\n }\n};\n\ntemplate\nstruct single_functor {\n single_functor(const U k, const V l = 1) :\n k(k), l(l) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE T operator()(const int i, const int j) const {\n return (i == element(k) - 1 && j == element(l) - 1) ? T(1) : T(0);\n }\n const U k;\n const V l;\n};\n\ntemplate,int>>\nstruct ibeta_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T a, const T b, const T x) const {\n \/* as of Eigen 3.4.0, the edge cases of a == 0 and b == 0 are not handled\n * internally, see https:\/\/gitlab.com\/libeigen\/eigen\/-\/issues\/2359 *\/\n if (a == T(0) && b != T(0)) {\n return T(1);\n } else if (a != T(0) && b == T(0)) {\n return T(0);\n } else {\n return Eigen::numext::betainc(a, b, x);\n }\n }\n};\n\n}\nFixed lchoose().\/**\n * @file\n *\/\n#pragma once\n\n#include \"numbirch\/type.hpp\"\n\n\/* for recent versions of CUDA, disables warnings about diag_suppress being\n * deprecated in favor of nv_diag_suppress *\/\n#pragma nv_diag_suppress 20236\n\n#if defined(HAVE_UNSUPPORTED_EIGEN_SPECIALFUNCTIONS)\n#include \n#elif defined(HAVE_EIGEN3_UNSUPPORTED_EIGEN_SPECIALFUNCTIONS)\n#include \n#endif\n\nnamespace numbirch {\nstatic const long double PI = 3.1415926535897932384626433832795;\n\ntemplate\nstruct identity_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return x;\n }\n};\n\ntemplate\nstruct negate_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return -x;\n }\n};\n\ntemplate\nstruct add_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x + y;\n }\n};\n\ntemplate\nstruct subtract_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x - y;\n }\n};\n\ntemplate\nstruct multiply_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x*y;\n }\n};\n\ntemplate\nstruct divide_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x\/y;\n }\n};\n\ntemplate\nstruct not_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return !x;\n }\n};\n\ntemplate\nstruct and_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x && y;\n }\n};\n\ntemplate\nstruct or_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x || y;\n }\n};\n\ntemplate\nstruct equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x == y;\n }\n};\n\ntemplate\nstruct not_equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x != y;\n }\n};\n\ntemplate\nstruct less_functor {\n NUMBIRCH_HOST_DEVICE bool operator()(const T x, const T y) const {\n return x < y;\n }\n};\n\ntemplate\nstruct less_or_equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x <= y;\n }\n};\n\ntemplate\nstruct greater_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x > y;\n }\n};\n\ntemplate\nstruct greater_or_equal_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return x >= y;\n }\n};\n\ntemplate\nstruct abs_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::abs(x);\n }\n};\n\ntemplate,int>>\nstruct acos_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::acos(x);\n }\n};\n\ntemplate,int>>\nstruct asin_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::asin(x);\n }\n};\n\ntemplate,int>>\nstruct atan_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::atan(x);\n }\n};\n\ntemplate\nstruct ceil_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n if constexpr (is_integral_v) {\n return x;\n } else {\n return std::ceil(x);\n }\n }\n};\n\ntemplate,int>>\nstruct cos_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::cos(x);\n }\n};\n\ntemplate,int>>\nstruct cosh_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::cosh(x);\n }\n};\n\ntemplate\nstruct count_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return (x == 0) ? 0 : 1;\n }\n};\n\ntemplate\nstruct diagonal_functor {\n diagonal_functor(const U a) :\n a(a) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE auto operator()(const int i, const int j) const {\n return (i == j) ? T(element(a)) : 0;\n }\n const U a;\n};\n\ntemplate,int>>\nstruct digamma_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return Eigen::numext::digamma(x);\n }\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n T z = 0;\n for (T i = 1; i <= y; ++i) {\n z += Eigen::numext::digamma(x + T(0.5)*(1 - i));\n }\n return z;\n }\n};\n\ntemplate,int>>\nstruct exp_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::exp(x);\n }\n};\n\ntemplate,int>>\nstruct expm1_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::expm1(x);\n }\n};\n\ntemplate\nstruct floor_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n if constexpr (is_integral_v) {\n return x;\n } else {\n return std::floor(x);\n }\n }\n};\n\ntemplate,int>>\nstruct lfact_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::lgamma(x + T(1));\n }\n};\n\ntemplate,int>>\nstruct lfact_grad_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T g, const T x) const {\n return g*Eigen::numext::digamma(x + T(1));\n }\n};\n\ntemplate,int>>\nstruct lgamma_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::lgamma(x);\n }\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n T z = T(0.25)*y*(y - T(1))*std::log(T(PI));\n for (T i = T(1); i <= y; ++i) {\n z += std::lgamma(x + T(0.5)*(T(1) - i));\n }\n return z;\n }\n};\n\ntemplate,int>>\nstruct log_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::log(x);\n }\n};\n\ntemplate,int>>\nstruct log1p_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::log1p(x);\n }\n};\n\ntemplate,int>>\nstruct log_abs_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::log(std::abs(x));\n }\n};\n\ntemplate,int>>\nstruct log_square_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return T(2)*std::log(x);\n }\n};\n\ntemplate,int>>\nstruct rcp_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return T(1)\/x;\n }\n};\n\ntemplate\nstruct rectify_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::max(T(0), x);\n }\n};\n\ntemplate,int>>\nstruct rectify_grad_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T g, const T x) const {\n return (x > T(0)) ? g : T(0);\n }\n};\n\ntemplate\nstruct round_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n if constexpr (is_integral_v) {\n return x;\n } else {\n return std::round(x);\n }\n }\n};\n\ntemplate,int>>\nstruct sin_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::sin(x);\n }\n};\n\ntemplate,int>>\nstruct sinh_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::sinh(x);\n }\n};\n\ntemplate,int>>\nstruct sqrt_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::sqrt(x);\n }\n};\n\ntemplate,int>>\nstruct tan_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::tan(x);\n }\n};\n\ntemplate,int>>\nstruct tanh_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x) const {\n return std::tanh(x);\n }\n};\n\ntemplate\nstruct copysign_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n if constexpr (is_integral_v) {\n \/\/ don't use std::copysign, as it promotes to floating point, which\n \/\/ we don't wish to do here\n return (y >= T(0)) ? std::abs(x) : -std::abs(x);\n } else {\n return std::copysign(x, y);\n }\n }\n};\n\ntemplate,int>>\nstruct gamma_p_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T a, const T x) const {\n return Eigen::numext::igamma(a, x);\n }\n};\n\ntemplate,int>>\nstruct gamma_q_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T a, const T x) const {\n return Eigen::numext::igammac(a, x);\n }\n};\n\ntemplate,int>>\nstruct lbeta_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return std::lgamma(x) + std::lgamma(y) - std::lgamma(x + y);\n }\n};\n\ntemplate,int>>\nstruct lchoose_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const int x, const int y) const {\n return std::lgamma(x + T(1)) - std::lgamma(y + T(1)) -\n std::lgamma(x - y + T(1));\n }\n};\n\ntemplate,int>>\nstruct lchoose_grad_functor {\n NUMBIRCH_HOST_DEVICE pair operator()(const T g, const T x, const T y)\n const {\n T gx = Eigen::numext::digamma(x + T(1)) -\n Eigen::numext::digamma(x - y + T(1));\n T gy = -Eigen::numext::digamma(y + T(1)) +\n Eigen::numext::digamma(x - y + T(1));\n return pair{g*gx, g*gy};\n }\n};\n\ntemplate,int>>\nstruct pow_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T x, const T y) const {\n return std::pow(x, y);\n }\n};\n\ntemplate\nstruct single_functor {\n single_functor(const U k, const V l = 1) :\n k(k), l(l) {\n \/\/\n }\n NUMBIRCH_HOST_DEVICE T operator()(const int i, const int j) const {\n return (i == element(k) - 1 && j == element(l) - 1) ? T(1) : T(0);\n }\n const U k;\n const V l;\n};\n\ntemplate,int>>\nstruct ibeta_functor {\n NUMBIRCH_HOST_DEVICE T operator()(const T a, const T b, const T x) const {\n \/* as of Eigen 3.4.0, the edge cases of a == 0 and b == 0 are not handled\n * internally, see https:\/\/gitlab.com\/libeigen\/eigen\/-\/issues\/2359 *\/\n if (a == T(0) && b != T(0)) {\n return T(1);\n } else if (a != T(0) && b == T(0)) {\n return T(0);\n } else {\n return Eigen::numext::betainc(a, b, x);\n }\n }\n};\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n\/******************** SETTINGS ********************\/\n\/\/ SDIO Settings\n#define BLOCK_SIZE 512ULL \/* SD card block size in Bytes (512 for a normal SD card) *\/\n\n\/\/ Logger settings\n#define RX_BUFFER_NUM_BLOCKS 20ULL \/* 20 blocks * 512 = 10 KB RAM required per buffer*\/\n\n\n\/\/ SD Card size\n#define SDCARD_SIZE\t(8ULL*1024ULL*1024ULL*1024ULL)\n\n\/************** END OF SETTINGS *****************\/\n\n\n\n\n#define BUFF_SIZE (BLOCK_SIZE*RX_BUFFER_NUM_BLOCKS)\n\nvoid read_disk_raw(char* volume_name, uint64_t disk_size);\n\ninline void wordswap(int32_t *i)\n{\n\tuint8_t *p = (uint8_t*) i;\n\tuint8_t tmp = p[0];\n\tp[0] = p[1];\n\tp[1] = tmp;\n\ttmp = p[2];\n\tp[2] = p[3];\n\tp[3] = tmp;\n}\n\nint main(int argc, char** argv)\n{\n printf(\"PARSE DISK:\\n----------\\n\");\n\tprintf(\"highspeedloggerbinaryparser : eg. '\/dev\/sdb' or '\\\\\\\\.\\\\G:' \\n\");\n\tprintf(\"highspeedloggerbinaryparser : eg. foo.diskdump \\n\\n\");\n\n\tif (argc >= 2)\n\t{\n\n\t\tif (argc == 2)\n\t\t{\n\t\t\tread_disk_raw(argv[1], SDCARD_SIZE);\n\t\t\texit(0);\n\t\t}\n\t}\n\telse\n\t{\n\n#ifdef WIN32\n\t\tread_disk_raw(\"\\\\\\\\.\\\\G:\", SDCARD_SIZE);\n\t \/\/ read_disk_raw(\"d:\\\\cessnaLogFull.dd\", SDCARD_SIZE);\n#else\n\t\/\/long long disk_size;\n\t\/\/ioctl(, BLKGETSIZE64, &disk_size);\n\t\tread_disk_raw(\"\/dev\/sdb\", SDCARD_SIZE);\n#endif\n\n\t\texit(0);\n\t}\n\n\texit(-1);\n}\n\n\n#if 0\n\n#define WIN32_LEAN_AND_MEAN\n#define BUFFER_SIZE 32\n\n#include \n\nvoid read_disk_raw(void)\n{\n\tHANDLE hFile; \n\tDWORD dwBytesRead = 0;\n\tchar ReadBuffer[BUFFER_SIZE] = {0};\n\n\thFile = CreateFile(\"\\\\\\\\.\\\\G:\",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);\n\n\tif (hFile == INVALID_HANDLE_VALUE) \n\t{ \n\t\tprintf(\"Could not open file (error %d)\\n\", GetLastError());\n\t\treturn; \n\t}\n\n\t\/\/ Read one character less than the buffer size to save room for\n\t\/\/ the terminating NULL character.\n\n\tif( FALSE == ReadFile(hFile, ReadBuffer, BUFFER_SIZE-2, &dwBytesRead, NULL) )\n\t{\n\t\tprintf(\"Could not read from file (error %d)\\n\", GetLastError());\n\t\tCloseHandle(hFile);\n\t\treturn;\n\t}\n\n\tif (dwBytesRead > 0)\n\t{\n\t\tReadBuffer[dwBytesRead+1]='\\0'; \/\/ NULL character\n\n\t\tprintf(TEXT(\"Text read from %s (%d bytes): \\n\"), dwBytesRead);\n\t\tprintf(\"%s\\n\", ReadBuffer);\n\t}\n\telse\n\t{\n\t\tprintf(TEXT(\"No data read from file %s\\n\"));\n\t}\n\n\tCloseHandle(hFile);\n\n}\n\n#endif\n\n\nvoid scan_all_blocks(FILE* volume, uint64_t disk_size);\n\n\/\/ Read from sector \/\/\nvoid read_disk_raw(char* volume_name, uint64_t disk_size)\n{\n FILE *volume;\n int k = 0;\n \n\tuint64_t sd = disk_size;\n\tsd \/= 1024UL * 1024UL;\n\tprintf(\"\\nExpecting an SD-card of %lu MB.\\n\",sd);\n\n volume = fopen(volume_name, \"r+b\");\n if(!volume)\n {\n printf(\"Cant open Drive '%s'\\n\", volume_name);\n return;\n }\n setbuf(volume, NULL); \/\/ Disable buffering\n\n \n\tprintf(\"\\nSearching for logfiles in '%s': \\n...\\r\",volume_name);\n\n\tscan_all_blocks(volume, disk_size);\n\n fclose(volume);\n }\n\nvoid scan_all_blocks(FILE* volume, uint64_t disk_size)\n{\n char buf[BUFF_SIZE] = {0};\n\n\tint log = -1;\n\tint cnt = 0;\n\n\tFILE* of = 0;\n\n\tuint64_t addr = 0;\n\twhile (addr < disk_size)\n\t{\n\t\tif(_fseeki64(volume, addr, SEEK_SET) != 0)\n\t\t{\n\t\t\tprintf(\"Cant move to sector\\n\");\n\t\t\treturn;\n\t\t}\n \n\t\t\/\/ Read BLOCK\n\t\tsize_t r = fread(buf, 1, BUFF_SIZE, volume);\n\n\t\t\/\/ Start of block must contain \n\t\tif ( ((unsigned char)buf[0] == 0x1a) && ((unsigned char)buf[1] == 0x1b) && ((unsigned char)buf[2] == 0x1c))\n {\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Start of new Logfile\n if ((unsigned char)buf[3] == 0xaa)\n {\n\t\t\t\tint tt = 0;\n\t\t\t\tint nr = 0;\n\t\t\t\ttt = (int) ((uint8_t)buf[6]);\n\t\t\t\tnr = (int) ((uint8_t) buf[5] ) + ((uint16_t) buf[4] )*256;\n\t\t\t\tchar filename[32];\n\t\t\t\tchar logtype[16];\n\t\t\t\tlog++;\n\t\t\t\tswitch(tt)\n\t\t\t\t{\n\t\t\t\tcase 0:\n\t\t\t\t\tsprintf(logtype, \"SPI1\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tsprintf(logtype, \"SPI2\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsprintf(logtype, \"UART2\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tsprintf(logtype, \"UART3\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsprintf(logtype, \"UNKNOWN\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsprintf(filename, \"sd_hs_log_%05d_%s.bin\", log, logtype);\n\t\t\t\tif (of > 0)\n\t\t\t\t{\n\t\t\t\t\tfclose(of);\n\t\t\t\t\tof = 0;\n\t\t\t\t}\n\t\t\t\tof = fopen(filename, \"w+b\");\n\t\t\t\tfwrite(buf,1,BUFF_SIZE,of);\n\t\t\t\tif (log > 0)\n\t\t\t\t\tprintf(\"%d x 10k\\nLog %d [#%d]: type [%x=%s] addr: <%ld> \",cnt, log, nr, tt, logtype, addr\/1024);\n\t\t\t\telse\n\t printf(\"Log %d [#%d]: type [%x=%s] addr: <%ld> \",log, nr, tt, logtype, addr\/1024);\n\t\t\t\tcnt = 0;\n }\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Continued Logfile\n else if ((unsigned char)buf[3] == 0xbb)\n {\n\t\t\t\tcnt++;\n\t\t\t\tif (of > 0)\n\t\t\t\t\tfwrite(buf,1,BUFF_SIZE,of);\n\n }\n else\n {\n\t\t\t\tif (of > 0)\n\t\t\t\t{\n\t\t\t\t\tfclose(of);\n\t\t\t\t\tof = 0;\n\t\t\t\t}\n printf(\"? (%x)\",(unsigned char)buf[3]);\n }\n }\n else\n {\n\t\t\tif (of > 0)\n\t\t\t{\n\t\t\t\tfclose(of);\n\t\t\t\tof = 0;\n\t\t\t}\n\t\t\tif (cnt > 0)\n\t\t\t{\n\t\t\t\tprintf(\"%d x 10k\\nFound End <%ld>\\n\",cnt, addr\/1024);\n\t\t\t\tcnt = 0;\n\t\t\t\tbreak;\n\t\t\t\t\/\/addr = disk_size;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/printf(\"Cnt ==0\\n\");\n\t\t\t}\n \t\t\/\/printf(\".\");\n }\n\n\t\tint f = feof(volume);\n\t\tint e = ferror(volume);\n\n\t\tif (f!=0)\n\t\t{\n\t\t\tprintf(\"%d x 10k\\nEof <%ld>\\n\",cnt, addr\/1024);\n\t\t\tcnt = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\taddr += BUFF_SIZE;\n\n\t\tif (addr >= disk_size) {\n\t\t\tprintf(\"End of disk: cnt=%d <%ld><%ld>\\n\",cnt,addr,disk_size);\n\t\t}\n\t\t\n\t\t\/\/printf(\"\\n %ld: %d %d %d \",addr, f, e, r);\n\t}\n \n \/\/ Print out what wiat in sector \/\/\n \/\/ for(k=0;kask SD card size (Linux only)#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n\/******************** SETTINGS ********************\/\n\/\/ SDIO Settings\n#define BLOCK_SIZE 512ULL \/* SD card block size in Bytes (512 for a normal SD card) *\/\n\n\/\/ Logger settings\n#define RX_BUFFER_NUM_BLOCKS 20ULL \/* 20 blocks * 512 = 10 KB RAM required per buffer*\/\n\n\n\/\/ SD Card size\n#define SDCARD_SIZE\t(8ULL*1024ULL*1024ULL*1024ULL)\n\n\/************** END OF SETTINGS *****************\/\n\n\n\n\n#define BUFF_SIZE (BLOCK_SIZE*RX_BUFFER_NUM_BLOCKS)\n\nvoid read_disk_raw(char* volume_name, uint64_t disk_size);\n\ninline void wordswap(int32_t *i)\n{\n\tuint8_t *p = (uint8_t*) i;\n\tuint8_t tmp = p[0];\n\tp[0] = p[1];\n\tp[1] = tmp;\n\ttmp = p[2];\n\tp[2] = p[3];\n\tp[3] = tmp;\n}\n\nint main(int argc, char** argv)\n{\n printf(\"PARSE DISK:\\n----------\\n\");\n\tprintf(\"highspeedloggerbinaryparser : eg. '\/dev\/sdb' or '\\\\\\\\.\\\\G:' \\n\");\n\tprintf(\"highspeedloggerbinaryparser : eg. foo.diskdump \\n\\n\");\n\n\tif (argc >= 2)\n\t{\n\n\t\tif (argc == 2)\n\t\t{\n\t\t\tread_disk_raw(argv[1], SDCARD_SIZE);\n\t\t\texit(0);\n\t\t}\n\t}\n\telse\n\t{\n\n#ifdef WIN32\n\t\tread_disk_raw(\"\\\\\\\\.\\\\G:\", SDCARD_SIZE);\n\t \/\/ read_disk_raw(\"d:\\\\cessnaLogFull.dd\", SDCARD_SIZE);\n#else\n\t\tread_disk_raw(\"\/dev\/sdb\", SDCARD_SIZE);\n#endif\n\n\t\texit(0);\n\t}\n\n\texit(-1);\n}\n\n\n#if 0\n\n#define WIN32_LEAN_AND_MEAN\n#define BUFFER_SIZE 32\n\n#include \n\nvoid read_disk_raw(void)\n{\n\tHANDLE hFile; \n\tDWORD dwBytesRead = 0;\n\tchar ReadBuffer[BUFFER_SIZE] = {0};\n\n\thFile = CreateFile(\"\\\\\\\\.\\\\G:\",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);\n\n\tif (hFile == INVALID_HANDLE_VALUE) \n\t{ \n\t\tprintf(\"Could not open file (error %d)\\n\", GetLastError());\n\t\treturn; \n\t}\n\n\t\/\/ Read one character less than the buffer size to save room for\n\t\/\/ the terminating NULL character.\n\n\tif( FALSE == ReadFile(hFile, ReadBuffer, BUFFER_SIZE-2, &dwBytesRead, NULL) )\n\t{\n\t\tprintf(\"Could not read from file (error %d)\\n\", GetLastError());\n\t\tCloseHandle(hFile);\n\t\treturn;\n\t}\n\n\tif (dwBytesRead > 0)\n\t{\n\t\tReadBuffer[dwBytesRead+1]='\\0'; \/\/ NULL character\n\n\t\tprintf(TEXT(\"Text read from %s (%d bytes): \\n\"), dwBytesRead);\n\t\tprintf(\"%s\\n\", ReadBuffer);\n\t}\n\telse\n\t{\n\t\tprintf(TEXT(\"No data read from file %s\\n\"));\n\t}\n\n\tCloseHandle(hFile);\n\n}\n\n#endif\n\n\nvoid scan_all_blocks(FILE* volume, uint64_t disk_size);\n\n\/\/ Read from sector \/\/\nvoid read_disk_raw(char* volume_name, uint64_t disk_size)\n{\n FILE *volume;\n int k = 0;\n \n volume = fopen(volume_name, \"r+b\");\n if(!volume)\n {\n printf(\"Cant open Drive '%s'\\n\", volume_name);\n return;\n }\n setbuf(volume, NULL); \/\/ Disable buffering\n\n#ifdef WIN32\n\tuint64_t sd = disk_size;\n\tsd \/= 1024UL * 1024UL;\n\tprintf(\"\\nExpecting an SD-card of %lu MB.\\n\",sd);\n#else\n\tlong long sdcard_disk_size;\n\tioctl(volume, BLKGETSIZE64, &sdcard_disk_size);\n\tdisk_size \/= 1024ULL * 1024 ULL;\n\tprintf(\"Found an SG card of %lld:\",sdcard_disk_size);\n#endif\n\n\n\n\tprintf(\"\\nSearching for logfiles in '%s': \\n...\\r\",volume_name);\n\n\tscan_all_blocks(volume, disk_size);\n\n fclose(volume);\n }\n\nvoid scan_all_blocks(FILE* volume, uint64_t disk_size)\n{\n char buf[BUFF_SIZE] = {0};\n\n\tint log = -1;\n\tint cnt = 0;\n\n\tFILE* of = 0;\n\n\tuint64_t addr = 0;\n\twhile (addr < disk_size)\n\t{\n\t\tif(_fseeki64(volume, addr, SEEK_SET) != 0)\n\t\t{\n\t\t\tprintf(\"Cant move to sector\\n\");\n\t\t\treturn;\n\t\t}\n \n\t\t\/\/ Read BLOCK\n\t\tsize_t r = fread(buf, 1, BUFF_SIZE, volume);\n\n\t\t\/\/ Start of block must contain \n\t\tif ( ((unsigned char)buf[0] == 0x1a) && ((unsigned char)buf[1] == 0x1b) && ((unsigned char)buf[2] == 0x1c))\n {\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Start of new Logfile\n if ((unsigned char)buf[3] == 0xaa)\n {\n\t\t\t\tint tt = 0;\n\t\t\t\tint nr = 0;\n\t\t\t\ttt = (int) ((uint8_t)buf[6]);\n\t\t\t\tnr = (int) ((uint8_t) buf[5] ) + ((uint16_t) buf[4] )*256;\n\t\t\t\tchar filename[32];\n\t\t\t\tchar logtype[16];\n\t\t\t\tlog++;\n\t\t\t\tswitch(tt)\n\t\t\t\t{\n\t\t\t\tcase 0:\n\t\t\t\t\tsprintf(logtype, \"SPI1\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tsprintf(logtype, \"SPI2\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tsprintf(logtype, \"UART2\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\n\t\t\t\t\tsprintf(logtype, \"UART3\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tsprintf(logtype, \"UNKNOWN\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsprintf(filename, \"sd_hs_log_%05d_%s.bin\", log, logtype);\n\t\t\t\tif (of > 0)\n\t\t\t\t{\n\t\t\t\t\tfclose(of);\n\t\t\t\t\tof = 0;\n\t\t\t\t}\n\t\t\t\tof = fopen(filename, \"w+b\");\n\t\t\t\tfwrite(buf,1,BUFF_SIZE,of);\n\t\t\t\tif (log > 0)\n\t\t\t\t\tprintf(\"%d x 10k\\nLog %d [#%d]: type [%x=%s] addr: <%ld> \",cnt, log, nr, tt, logtype, addr\/1024);\n\t\t\t\telse\n\t printf(\"Log %d [#%d]: type [%x=%s] addr: <%ld> \",log, nr, tt, logtype, addr\/1024);\n\t\t\t\tcnt = 0;\n }\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Continued Logfile\n else if ((unsigned char)buf[3] == 0xbb)\n {\n\t\t\t\tcnt++;\n\t\t\t\tif (of > 0)\n\t\t\t\t\tfwrite(buf,1,BUFF_SIZE,of);\n\n }\n else\n {\n\t\t\t\tif (of > 0)\n\t\t\t\t{\n\t\t\t\t\tfclose(of);\n\t\t\t\t\tof = 0;\n\t\t\t\t}\n printf(\"? (%x)\",(unsigned char)buf[3]);\n }\n }\n else\n {\n\t\t\tif (of > 0)\n\t\t\t{\n\t\t\t\tfclose(of);\n\t\t\t\tof = 0;\n\t\t\t}\n\t\t\tif (cnt > 0)\n\t\t\t{\n\t\t\t\tprintf(\"%d x 10k\\nFound End <%ld>\\n\",cnt, addr\/1024);\n\t\t\t\tcnt = 0;\n\t\t\t\tbreak;\n\t\t\t\t\/\/addr = disk_size;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/printf(\"Cnt ==0\\n\");\n\t\t\t}\n \t\t\/\/printf(\".\");\n }\n\n\t\tint f = feof(volume);\n\t\tint e = ferror(volume);\n\n\t\tif (f!=0)\n\t\t{\n\t\t\tprintf(\"%d x 10k\\nEof <%ld>\\n\",cnt, addr\/1024);\n\t\t\tcnt = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\taddr += BUFF_SIZE;\n\n\t\tif (addr >= disk_size) {\n\t\t\tprintf(\"End of disk: cnt=%d <%ld><%ld>\\n\",cnt,addr,disk_size);\n\t\t}\n\t\t\n\t\t\/\/printf(\"\\n %ld: %d %d %d \",addr, f, e, r);\n\t}\n \n \/\/ Print out what wiat in sector \/\/\n \/\/ for(k=0;k"} {"text":"Don't show pre-sm_20 CUDA cards in the device list<|endoftext|>"} {"text":"\/\/ stdafx1.cpp : source file that includes just the standard includes\n\/\/ stdafx1.pch will be the pre-compiled header\n\/\/ stdafx1.obj will contain the pre-compiled type information\n\n#include \"stdafx2.h\"\n\n#ifdef _ATL_STATIC_REGISTRY\n#include \n#include \n#endif\n\n#include \nINTEGRATION: CWS sdk04 (1.1.62); FILE MERGED 2003\/06\/24 11:10:03 jsc 1.1.62.1: #110313# insert source license header\/*************************************************************************\n *\n * $RCSfile: StdAfx2.cpp,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-06-30 15:50:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * the BSD license.\n *\n * Copyright (c) 2003 by Sun Microsystems, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Sun Microsystems, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *************************************************************************\/\n\n\/\/ stdafx1.cpp : source file that includes just the standard includes\n\/\/ stdafx1.pch will be the pre-compiled header\n\/\/ stdafx1.obj will contain the pre-compiled type information\n\n#include \"stdafx2.h\"\n\n#ifdef _ATL_STATIC_REGISTRY\n#include \n#include \n#endif\n\n#include \n<|endoftext|>"} {"text":"\n#include \"FaceTracker.hpp\"\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace YerFace {\n\nFaceTracker::FaceTracker(string myClassifierFileName, FrameDerivatives *myFrameDerivatives, float myTrackingBoxPercentage, float myMaxFaceSizePercentage, int myOpticalTrackStaleFramesInterval) {\n\tclassifierFileName = myClassifierFileName;\n\tframeDerivatives = myFrameDerivatives;\n\ttrackerState = DETECTING;\n\tclassificationBoxSet = false;\n\ttrackingBoxSet = false;\n\n\ttrackingBoxPercentage = myTrackingBoxPercentage;\n\tif(trackingBoxPercentage <= 0.0 || trackingBoxPercentage > 1.0) {\n\t\tthrow invalid_argument(\"trackingBoxPercentage is out of range.\");\n\t}\n\tmaxFaceSizePercentage = myMaxFaceSizePercentage;\n\tif(maxFaceSizePercentage <= 0.0 || maxFaceSizePercentage > 1.0) {\n\t\tthrow invalid_argument(\"maxFaceSizePercentage is out of range.\");\n\t}\n\topticalTrackStaleFramesInterval = myOpticalTrackStaleFramesInterval;\n\tif(opticalTrackStaleFramesInterval <= 0) {\n\t\tthrow invalid_argument(\"opticalTrackStaleFramesInterval is out of range.\");\n\t}\n\tif(!cascadeClassifier.load(classifierFileName)) {\n\t\tthrow invalid_argument(\"Unable to load specified classifier.\");\n\t}\n\tfprintf(stderr, \"FaceTracker object constructed and ready to go!\\n\");\n}\n\nTrackerState FaceTracker::processCurrentFrame(void) {\n\tif(trackerState == DETECTING || trackerState == LOST || trackerState == STALE) {\n\t\tclassificationBoxSet = false;\n\t\tstd::vector faces;\n\t\tMat classificationFrame = frameDerivatives->getClassificationFrame();\n\t\tdouble classificationFrameArea = (double)classificationFrame.size().area();\n\t\tdouble maxFaceSize = sqrt(classificationFrameArea * maxFaceSizePercentage);\n\t\tcascadeClassifier.detectMultiScale(classificationFrame, faces, 1.1, 3, 0|CASCADE_SCALE_IMAGE, Size(maxFaceSize, maxFaceSize));\n\n\t\tint largestFace = -1;\n\t\tint largestFaceArea = -1;\n\t\tfor( size_t i = 0; i < faces.size(); i++ ) {\n\t\t\tif(faces[i].area() > largestFaceArea) {\n\t\t\t\tlargestFace = i;\n\t\t\t\tlargestFaceArea = faces[i].area();\n\t\t\t}\n\t\t}\n\t\tif(largestFace >= 0) {\n\t\t\tclassificationBoxSet = true;\n\t\t\tdouble classificationScaleFactor = frameDerivatives->getClassificationScaleFactor();\n\t\t\tclassificationBox = faces[largestFace];\n\t\t\tclassificationBoxNormalSize = Rect(\n\t\t\t\t(double)classificationBox.x \/ classificationScaleFactor,\n\t\t\t\t(double)classificationBox.y \/ classificationScaleFactor,\n\t\t\t\t(double)classificationBox.width \/ classificationScaleFactor,\n\t\t\t\t(double)classificationBox.height \/ classificationScaleFactor);\n\t\t\t\/\/Switch to TRACKING\n\t\t\ttrackerState = TRACKING;\n\t\t\t#if (CV_MINOR_VERSION < 3)\n\t\t\ttracker = Tracker::create(\"KCF\");\n\t\t\t#else\n\t\t\ttracker = TrackerKCF::create();\n\t\t\t#endif\n\t\t\tdouble trackingBoxWidth = (double)classificationBoxNormalSize.width * trackingBoxPercentage;\n\t\t\tdouble trackingBoxHeight = (double)classificationBoxNormalSize.height * trackingBoxPercentage;\n\t\t\tRect trackingBox = Rect(\n\t\t\t\t(double)classificationBoxNormalSize.x + (((double)classificationBoxNormalSize.width - trackingBoxWidth) \/ 2.0),\n\t\t\t\t(double)classificationBoxNormalSize.y + (((double)classificationBoxNormalSize.height - trackingBoxHeight) \/ 2.0),\n\t\t\t\ttrackingBoxWidth,\n\t\t\t\ttrackingBoxHeight);\n\t\t\ttracker->init(frameDerivatives->getCurrentFrame(), trackingBox);\n\t\t\tstaleCounter = opticalTrackStaleFramesInterval;\n\t\t}\n\t} else if(trackerState == TRACKING) {\n\t\tbool trackSuccess = tracker->update(frameDerivatives->getCurrentFrame(), trackingBox);\n\t\tif(!trackSuccess) {\n\t\t\tfprintf(stderr, \"FaceTracker WARNING! Track lost. Will keep searching...\\n\");\n\t\t\ttrackingBoxSet = false;\n\t\t\ttrackerState = LOST;\n\t\t\t\/\/Attempt to re-process this same frame in LOST mode.\n\t\t\treturn this->processCurrentFrame();\n\t\t} else {\n\t\t\ttrackingBoxSet = true;\n\t\t\tstaleCounter--;\n\t\t\tif(staleCounter <= 0) {\n\t\t\t\ttrackerState = STALE;\n\t\t\t}\n\t\t}\n\t}\n\treturn trackerState;\n}\n\nvoid FaceTracker::renderPreviewHUD(void) {\n\tMat frame = frameDerivatives->getPreviewFrame();\n\tif(classificationBoxSet) {\n\t\trectangle(frame, classificationBoxNormalSize, Scalar( 0, 255, 0 ), 1, 0);\n\t}\n\tif(trackingBoxSet) {\n\t\trectangle(frame, trackingBox, Scalar( 255, 0, 0 ), 1, 0);\n\t}\n}\n\nTrackerState FaceTracker::getTrackerState(void) {\n\treturn trackerState;\n}\n\n}; \/\/namespace YerFace\nfix an issue where stale state would prevent optical tracking from proceeding\n#include \"FaceTracker.hpp\"\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace YerFace {\n\nFaceTracker::FaceTracker(string myClassifierFileName, FrameDerivatives *myFrameDerivatives, float myTrackingBoxPercentage, float myMaxFaceSizePercentage, int myOpticalTrackStaleFramesInterval) {\n\tclassifierFileName = myClassifierFileName;\n\tframeDerivatives = myFrameDerivatives;\n\ttrackerState = DETECTING;\n\tclassificationBoxSet = false;\n\ttrackingBoxSet = false;\n\n\ttrackingBoxPercentage = myTrackingBoxPercentage;\n\tif(trackingBoxPercentage <= 0.0 || trackingBoxPercentage > 1.0) {\n\t\tthrow invalid_argument(\"trackingBoxPercentage is out of range.\");\n\t}\n\tmaxFaceSizePercentage = myMaxFaceSizePercentage;\n\tif(maxFaceSizePercentage <= 0.0 || maxFaceSizePercentage > 1.0) {\n\t\tthrow invalid_argument(\"maxFaceSizePercentage is out of range.\");\n\t}\n\topticalTrackStaleFramesInterval = myOpticalTrackStaleFramesInterval;\n\tif(opticalTrackStaleFramesInterval <= 0) {\n\t\tthrow invalid_argument(\"opticalTrackStaleFramesInterval is out of range.\");\n\t}\n\tif(!cascadeClassifier.load(classifierFileName)) {\n\t\tthrow invalid_argument(\"Unable to load specified classifier.\");\n\t}\n\tfprintf(stderr, \"FaceTracker object constructed and ready to go!\\n\");\n}\n\nTrackerState FaceTracker::processCurrentFrame(void) {\n\tif(trackerState == DETECTING || trackerState == LOST || trackerState == STALE) {\n\t\tclassificationBoxSet = false;\n\t\tstd::vector faces;\n\t\tMat classificationFrame = frameDerivatives->getClassificationFrame();\n\t\tdouble classificationFrameArea = (double)classificationFrame.size().area();\n\t\tdouble maxFaceSize = sqrt(classificationFrameArea * maxFaceSizePercentage);\n\t\tcascadeClassifier.detectMultiScale(classificationFrame, faces, 1.1, 3, 0|CASCADE_SCALE_IMAGE, Size(maxFaceSize, maxFaceSize));\n\n\t\tint largestFace = -1;\n\t\tint largestFaceArea = -1;\n\t\tfor( size_t i = 0; i < faces.size(); i++ ) {\n\t\t\tif(faces[i].area() > largestFaceArea) {\n\t\t\t\tlargestFace = i;\n\t\t\t\tlargestFaceArea = faces[i].area();\n\t\t\t}\n\t\t}\n\t\tif(largestFace >= 0) {\n\t\t\tclassificationBoxSet = true;\n\t\t\tdouble classificationScaleFactor = frameDerivatives->getClassificationScaleFactor();\n\t\t\tclassificationBox = faces[largestFace];\n\t\t\tclassificationBoxNormalSize = Rect(\n\t\t\t\t(double)classificationBox.x \/ classificationScaleFactor,\n\t\t\t\t(double)classificationBox.y \/ classificationScaleFactor,\n\t\t\t\t(double)classificationBox.width \/ classificationScaleFactor,\n\t\t\t\t(double)classificationBox.height \/ classificationScaleFactor);\n\t\t\t\/\/Switch to TRACKING\n\t\t\ttrackerState = TRACKING;\n\t\t\t#if (CV_MINOR_VERSION < 3)\n\t\t\ttracker = Tracker::create(\"KCF\");\n\t\t\t#else\n\t\t\ttracker = TrackerKCF::create();\n\t\t\t#endif\n\t\t\tdouble trackingBoxWidth = (double)classificationBoxNormalSize.width * trackingBoxPercentage;\n\t\t\tdouble trackingBoxHeight = (double)classificationBoxNormalSize.height * trackingBoxPercentage;\n\t\t\tRect trackingBox = Rect(\n\t\t\t\t(double)classificationBoxNormalSize.x + (((double)classificationBoxNormalSize.width - trackingBoxWidth) \/ 2.0),\n\t\t\t\t(double)classificationBoxNormalSize.y + (((double)classificationBoxNormalSize.height - trackingBoxHeight) \/ 2.0),\n\t\t\t\ttrackingBoxWidth,\n\t\t\t\ttrackingBoxHeight);\n\t\t\ttracker->init(frameDerivatives->getCurrentFrame(), trackingBox);\n\t\t\tstaleCounter = opticalTrackStaleFramesInterval;\n\t\t}\n\t}\n\tif(trackerState == TRACKING || trackerState == STALE) {\n\t\tbool trackSuccess = tracker->update(frameDerivatives->getCurrentFrame(), trackingBox);\n\t\tif(!trackSuccess) {\n\t\t\tfprintf(stderr, \"FaceTracker WARNING! Track lost. Will keep searching...\\n\");\n\t\t\ttrackingBoxSet = false;\n\t\t\ttrackerState = LOST;\n\t\t\t\/\/Attempt to re-process this same frame in LOST mode.\n\t\t\treturn this->processCurrentFrame();\n\t\t} else {\n\t\t\ttrackingBoxSet = true;\n\t\t\tstaleCounter--;\n\t\t\tif(staleCounter <= 0) {\n\t\t\t\ttrackerState = STALE;\n\t\t\t}\n\t\t}\n\t}\n\treturn trackerState;\n}\n\nvoid FaceTracker::renderPreviewHUD(void) {\n\tMat frame = frameDerivatives->getPreviewFrame();\n\tif(classificationBoxSet) {\n\t\trectangle(frame, classificationBoxNormalSize, Scalar( 0, 255, 0 ), 1, 0);\n\t}\n\tif(trackingBoxSet) {\n\t\trectangle(frame, trackingBox, Scalar( 255, 0, 0 ), 1, 0);\n\t}\n}\n\nTrackerState FaceTracker::getTrackerState(void) {\n\treturn trackerState;\n}\n\n}; \/\/namespace YerFace\n<|endoftext|>"} {"text":"\/\/ Texture.hh for Fluxbox Window Manager \n\/\/ Copyright (c) 2002 Henrik Kinnunen (fluxgen@users.sourceforge.net)\n\/\/\n\/\/ from Image.cc for Blackbox - an X11 Window manager\n\/\/ Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: Texture.cc,v 1.6 2003\/08\/12 11:44:19 fluxgen Exp $\n\n#include \"Texture.hh\"\n\n#include \n#include \n\nnamespace FbTk {\n\nvoid Texture::setFromString(const char * const texture_str) {\n if (texture_str == 0)\n return;\n int t_len = strlen(texture_str) + 1;\n char *ts = new char[t_len];\n strcpy(ts, texture_str);\n\n \/\/ to lower\n for (size_t byte_pos = 0; byte_pos < strlen(ts); ++byte_pos)\n ts[byte_pos] = tolower(ts[byte_pos]);\n\n if (strstr(ts, \"parentrelative\")) {\n setType(Texture::PARENTRELATIVE);\n } else {\n setType(Texture::NONE);\n\n if (strstr(ts, \"solid\"))\n addType(Texture::SOLID);\n else if (strstr(ts, \"gradient\")) {\n addType(Texture::GRADIENT);\n if (strstr(ts, \"crossdiagonal\"))\n addType(Texture::CROSSDIAGONAL);\n else if (strstr(ts, \"rectangle\"))\n addType(Texture::RECTANGLE);\n else if (strstr(ts, \"pyramid\"))\n addType(Texture::PYRAMID);\n else if (strstr(ts, \"pipecross\"))\n addType(Texture::PIPECROSS);\n else if (strstr(ts, \"elliptic\"))\n addType(Texture::ELLIPTIC);\n else if (strstr(ts, \"diagonal\"))\n addType(Texture::DIAGONAL);\n else if (strstr(ts, \"horizontal\"))\n addType(Texture::HORIZONTAL);\n else if (strstr(ts, \"vertical\"))\n addType(Texture::VERTICAL);\n else\n addType(Texture::DIAGONAL);\n } else\n addType(Texture::SOLID);\n\n if (strstr(ts, \"raised\"))\n addType(Texture::RAISED);\n else if (strstr(ts, \"sunken\"))\n addType(Texture::SUNKEN);\n else if (strstr(ts, \"flat\"))\n addType(Texture::FLAT);\n else\n addType(Texture::RAISED);\n\n if (! (type() & Texture::FLAT))\n if (strstr(ts, \"bevel2\"))\n addType(Texture::BEVEL2);\n else\n addType(Texture::BEVEL1);\n\n if (strstr(ts, \"interlaced\"))\n addType(Texture::INTERLACED);\n\n if (strstr(ts, \"tiled\"))\n addType(Texture::TILED);\n }\n\n delete [] ts;\n}\n\n}; \/\/ end namespace FbTk\nadded missing invert type\/\/ Texture.hh for Fluxbox Window Manager \n\/\/ Copyright (c) 2002 Henrik Kinnunen (fluxgen@users.sourceforge.net)\n\/\/\n\/\/ from Image.cc for Blackbox - an X11 Window manager\n\/\/ Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n\/\/ $Id: Texture.cc,v 1.7 2004\/01\/11 20:33:24 fluxgen Exp $\n\n#include \"Texture.hh\"\n\n#include \n#include \n\nnamespace FbTk {\n\nvoid Texture::setFromString(const char * const texture_str) {\n if (texture_str == 0)\n return;\n int t_len = strlen(texture_str) + 1;\n char *ts = new char[t_len];\n strcpy(ts, texture_str);\n\n \/\/ to lower\n for (size_t byte_pos = 0; byte_pos < strlen(ts); ++byte_pos)\n ts[byte_pos] = tolower(ts[byte_pos]);\n\n if (strstr(ts, \"parentrelative\")) {\n setType(Texture::PARENTRELATIVE);\n } else {\n setType(Texture::NONE);\n\n if (strstr(ts, \"solid\"))\n addType(Texture::SOLID);\n else if (strstr(ts, \"gradient\")) {\n addType(Texture::GRADIENT);\n if (strstr(ts, \"crossdiagonal\"))\n addType(Texture::CROSSDIAGONAL);\n else if (strstr(ts, \"rectangle\"))\n addType(Texture::RECTANGLE);\n else if (strstr(ts, \"pyramid\"))\n addType(Texture::PYRAMID);\n else if (strstr(ts, \"pipecross\"))\n addType(Texture::PIPECROSS);\n else if (strstr(ts, \"elliptic\"))\n addType(Texture::ELLIPTIC);\n else if (strstr(ts, \"diagonal\"))\n addType(Texture::DIAGONAL);\n else if (strstr(ts, \"horizontal\"))\n addType(Texture::HORIZONTAL);\n else if (strstr(ts, \"vertical\"))\n addType(Texture::VERTICAL);\n else\n addType(Texture::DIAGONAL);\n } else\n addType(Texture::SOLID);\n\n if (strstr(ts, \"raised\"))\n addType(Texture::RAISED);\n else if (strstr(ts, \"sunken\"))\n addType(Texture::SUNKEN);\n else if (strstr(ts, \"flat\"))\n addType(Texture::FLAT);\n else if (strstr(ts, \"invert\"))\n addType(Texture::INVERT);\n else\n addType(Texture::RAISED);\n\n if (! (type() & Texture::FLAT))\n if (strstr(ts, \"bevel2\"))\n addType(Texture::BEVEL2);\n else\n addType(Texture::BEVEL1);\n\n if (strstr(ts, \"interlaced\"))\n addType(Texture::INTERLACED);\n\n if (strstr(ts, \"tiled\"))\n addType(Texture::TILED);\n }\n\n delete [] ts;\n}\n\n}; \/\/ end namespace FbTk\n<|endoftext|>"} {"text":"\/*\n * Open Chinese Convert\n *\n * Copyright 2010-2013 BYVoid \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"..\/dictionary\/datrie.h\"\n#include \"..\/dictionary\/text.h\"\n#include \"..\/dict_group.h\"\n#include \"..\/encoding.h\"\n#include \"..\/utils.h\"\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\n\n#ifndef VERSION\n#define VERSION \"\"\n#endif\n\n#define DATRIE_SIZE 1000000\n#define DATRIE_WORD_MAX_COUNT 500000\n#define BUFFER_SIZE 1024\n\nstruct Value {\n string value;\n size_t cursor;\n Value(string value_, size_t cursor_) : value(value_), cursor(cursor_) {\n }\n};\n\nstruct Entry {\n string key;\n vector valueIndexes;\n};\n\nvector lexicon;\nvector values;\nDarts::DoubleArray dict;\n\nsize_t lexicon_index_length, lexicon_cursor_end;\n\nvoid make() {\n vector keys;\n vector valueIndexes;\n keys.reserve(lexicon.size());\n for (size_t i = 0; i < lexicon.size(); i++) {\n keys.push_back(lexicon[i].key.c_str());\n }\n dict.build(lexicon.size(), &keys[0]);\n}\n\nint cmp(const void* a, const void* b) {\n return ucs4cmp(((const TextEntry*)a)->key, ((const TextEntry*)b)->key);\n}\n\nvoid init(const char* filename) {\n DictGroup* DictGroup = dict_group_new(NULL);\n if (dict_group_load(DictGroup, filename,\n OPENCC_DICTIONARY_TYPE_TEXT) == -1) {\n dictionary_perror(\"Dictionary loading error\");\n fprintf(stderr, _(\"\\n\"));\n exit(1);\n }\n Dict* dict_abs = dict_group_get_dict(DictGroup, 0);\n if (dict_abs == (Dict*)-1) {\n dictionary_perror(\"Dictionary loading error\");\n fprintf(stderr, _(\"\\n\"));\n exit(1);\n }\n static TextEntry tlexicon[DATRIE_WORD_MAX_COUNT];\n \/* TODO add datrie support *\/\n Dict* dictionary = dict_abs->dict;\n size_t lexicon_count = dict_text_get_lexicon(dictionary, tlexicon);\n qsort(tlexicon, lexicon_count, sizeof(tlexicon[0]), cmp);\n size_t lexicon_cursor = 0;\n lexicon.resize(lexicon_count);\n for (size_t i = 0; i < lexicon_count; i++) {\n char* utf8_temp = ucs4_to_utf8(tlexicon[i].key, (size_t)-1);\n lexicon[i].key = utf8_temp;\n free(utf8_temp);\n size_t value_count;\n for (value_count = 0; tlexicon[i].value[value_count] != NULL; value_count++) {}\n for (size_t j = 0; j < value_count; j++) {\n lexicon[i].valueIndexes.push_back(values.size());\n char* utf8_temp = ucs4_to_utf8(tlexicon[i].value[j], (size_t)-1);\n values.push_back(Value(utf8_temp, lexicon_cursor));\n free(utf8_temp);\n lexicon_cursor += ucs4len(tlexicon[i].value[j]) + 1;\n }\n lexicon_index_length += value_count + 1;\n }\n lexicon_cursor_end = lexicon_cursor;\n}\n\nvoid output(const char* file_name) {\n dict.save(file_name);\n size_t dartsSize = dict.total_size();\n \n \/*\n FILE* fp = fopen(file_name, \"wb\");\n if (!fp) {\n fprintf(stderr, _(\"Can not write file: %s\\n\"), file_name);\n exit(1);\n }\n uint32_t i, item_count;\n for (i = DATRIE_SIZE - 1; i > 0; i--) {\n if (dat[i].parent != DATRIE_UNUSED) {\n break;\n }\n }\n item_count = i + 1;\n fwrite(\"OPENCCDATRIE\", sizeof(char), strlen(\"OPENCCDATRIE\"), fp);\n \/\/ 詞彙表長度\n fwrite(&lexicon_cursor_end, sizeof(uint32_t), 1, fp);\n for (i = 0; i < lexicon_count; i++) {\n size_t j;\n for (j = 0; j < lexicon[i].value_count; j++) {\n fwrite(lexicon[i].value[j].pointer, sizeof(ucs4_t),\n ucs4len(lexicon[i].value[j].pointer) + 1, fp);\n }\n }\n \/\/ 詞彙索引表長度\n fwrite(&lexicon_index_length, sizeof(uint32_t), 1, fp);\n for (i = 0; i < lexicon_count; i++) {\n size_t j;\n for (j = 0; j < lexicon[i].value_count; j++) {\n fwrite(&lexicon[i].value[j].cursor, sizeof(uint32_t), 1, fp);\n }\n uint32_t dem = (uint32_t)-1;\n fwrite(&dem, sizeof(uint32_t), 1, fp); \/\/分隔符\n }\n fwrite(&lexicon_count, sizeof(uint32_t), 1, fp);\n fwrite(&item_count, sizeof(uint32_t), 1, fp);\n fwrite(dat, sizeof(dat[0]), item_count, fp);\n fclose(fp);\n *\/\n}\n\n#ifdef DEBUG_WRITE_TEXT\nvoid write_text_file() {\n FILE* fp;\n int i;\n fp = fopen(\"datrie.txt\", \"w\");\n fprintf(fp, \"%d\\n\", lexicon_count);\n for (i = 0; i < lexicon_count; i++) {\n char* buff = ucs4_to_utf8(lexicon[i].value, (size_t)-1);\n fprintf(fp, \"%s\\n\", buff);\n free(buff);\n }\n for (i = 0; i < DATRIE_SIZE; i++) {\n if (dat[i].parent != DATRIE_UNUSED) {\n fprintf(fp, \"%d %d %d %d\\n\", i, dat[i].base, dat[i].parent, dat[i].word);\n }\n }\n fclose(fp);\n}\n\n#endif \/* ifdef DEBUG_WRITE_TEXT *\/\n\nvoid show_version() {\n printf(_(\"\\nOpen Chinese Convert (OpenCC) Dictionary Tool\\nVersion %s\\n\\n\"),\n VERSION);\n}\n\nvoid show_usage() {\n show_version();\n printf(_(\"Usage:\\n\"));\n printf(_(\" opencc_dict -i input_file -o output_file\\n\\n\"));\n printf(_(\" -i input_file\\n\"));\n printf(_(\" Read data from input_file.\\n\"));\n printf(_(\" -o output_file\\n\"));\n printf(_(\" Write converted data to output_file.\\n\"));\n printf(_(\"\\n\"));\n printf(_(\"\\n\"));\n}\n\nint main(int argc, char** argv) {\n static int oc;\n static char input_file[BUFFER_SIZE], output_file[BUFFER_SIZE];\n int input_file_specified = 0, output_file_specified = 0;\n\n#ifdef ENABLE_GETTEXT\n setlocale(LC_ALL, \"\");\n bindtextdomain(PACKAGE_NAME, LOCALEDIR);\n#endif \/* ifdef ENABLE_GETTEXT *\/\n while ((oc = getopt(argc, argv, \"vh-:i:o:\")) != -1) {\n switch (oc) {\n case 'v':\n show_version();\n return 0;\n case 'h':\n case '?':\n show_usage();\n return 0;\n case '-':\n if (strcmp(optarg, \"version\") == 0) {\n show_version();\n } else {\n show_usage();\n }\n return 0;\n case 'i':\n strcpy(input_file, optarg);\n input_file_specified = 1;\n break;\n case 'o':\n strcpy(output_file, optarg);\n output_file_specified = 1;\n break;\n }\n }\n if (!input_file_specified) {\n fprintf(stderr, _(\"Please specify input file using -i.\\n\"));\n show_usage();\n return 1;\n }\n if (!output_file_specified) {\n fprintf(stderr, _(\"Please specify output file using -o.\\n\"));\n show_usage();\n return 1;\n }\n init(input_file);\n make();\n output(output_file);\n#ifdef DEBUG_WRITE_TEXT\n write_text_file();\n#endif \/* ifdef DEBUG_WRITE_TEXT *\/\n return 0;\n}\nSerialization opencc dictionary with darts\/*\n * Open Chinese Convert\n *\n * Copyright 2010-2013 BYVoid \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"..\/dictionary\/datrie.h\"\n#include \"..\/dictionary\/text.h\"\n#include \"..\/dict_group.h\"\n#include \"..\/encoding.h\"\n#include \"..\/utils.h\"\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\n\n#ifndef VERSION\n#define VERSION \"\"\n#endif\n\n#define DATRIE_SIZE 1000000\n#define DATRIE_WORD_MAX_COUNT 500000\n#define BUFFER_SIZE 1024\n\nconst char* OCDHEADER = \"OPENCCDICTIONARY1\";\n\nstruct Value {\n string value;\n size_t cursor;\n Value(string value_, size_t cursor_) : value(value_), cursor(cursor_) {\n }\n};\n\nstruct Entry {\n string key;\n vector valueIndexes;\n};\n\nvector lexicon;\nvector values;\nDarts::DoubleArray dict;\n\nvoid make() {\n vector keys;\n vector valueIndexes;\n keys.reserve(lexicon.size());\n for (size_t i = 0; i < lexicon.size(); i++) {\n keys.push_back(lexicon[i].key.c_str());\n }\n dict.build(lexicon.size(), &keys[0]);\n}\n\nint cmp(const void* a, const void* b) {\n return ucs4cmp(((const TextEntry*)a)->key, ((const TextEntry*)b)->key);\n}\n\nvoid init(const char* filename) {\n DictGroup* DictGroup = dict_group_new(NULL);\n if (dict_group_load(DictGroup, filename,\n OPENCC_DICTIONARY_TYPE_TEXT) == -1) {\n dictionary_perror(\"Dictionary loading error\");\n fprintf(stderr, _(\"\\n\"));\n exit(1);\n }\n Dict* dict_abs = dict_group_get_dict(DictGroup, 0);\n if (dict_abs == (Dict*)-1) {\n dictionary_perror(\"Dictionary loading error\");\n fprintf(stderr, _(\"\\n\"));\n exit(1);\n }\n static TextEntry tlexicon[DATRIE_WORD_MAX_COUNT];\n \/* TODO add datrie support *\/\n Dict* dictionary = dict_abs->dict;\n size_t lexicon_count = dict_text_get_lexicon(dictionary, tlexicon);\n qsort(tlexicon, lexicon_count, sizeof(tlexicon[0]), cmp);\n size_t lexicon_cursor = 0;\n lexicon.resize(lexicon_count);\n for (size_t i = 0; i < lexicon_count; i++) {\n char* utf8_temp = ucs4_to_utf8(tlexicon[i].key, (size_t)-1);\n lexicon[i].key = utf8_temp;\n free(utf8_temp);\n size_t value_count;\n for (value_count = 0; tlexicon[i].value[value_count] != NULL; value_count++) {}\n for (size_t j = 0; j < value_count; j++) {\n lexicon[i].valueIndexes.push_back(values.size());\n char* utf8_temp = ucs4_to_utf8(tlexicon[i].value[j], (size_t)-1);\n values.push_back(Value(utf8_temp, lexicon_cursor));\n lexicon_cursor += strlen(utf8_temp);\n free(utf8_temp);\n }\n }\n}\n\nvoid output(const char* file_name) {\n FILE* fp = fopen(file_name, \"wb\");\n if (!fp) {\n fprintf(stderr, _(\"Can not write file: %s\\n\"), file_name);\n exit(1);\n }\n \/*\n Binary Structure\n [OCDHEADER]\n [number of keys]\n size_t\n [number of values]\n size_t\n [bytes of values]\n size_t\n [bytes of darts]\n size_t\n [key indexes]\n size_t(index of first value) * [number of keys]\n [value indexes]\n size_t(index of first char) * [number of values]\n [value data]\n char * [bytes of values]\n [darts]\n char * [bytes of darts]\n *\/\n size_t numKeys = lexicon.size();\n size_t numValues = values.size();\n size_t dartsSize = dict.total_size();\n \n fwrite(OCDHEADER, sizeof(char), strlen(OCDHEADER), fp);\n fwrite(&numKeys, sizeof(size_t), 1, fp);\n fwrite(&numValues, sizeof(size_t), 1, fp);\n fwrite(&dartsSize, sizeof(size_t), 1, fp);\n \n \/\/ key indexes\n for (size_t i = 0; i < numKeys; i++) {\n size_t index = lexicon[i].valueIndexes[0];\n fwrite(&index, sizeof(size_t), 1, fp);\n }\n \n \/\/ value indexes\n for (size_t i = 0; i < numValues; i++) {\n size_t index = values[i].cursor;\n fwrite(&index, sizeof(size_t), 1, fp);\n }\n \n \/\/ value data\n for (size_t i = 0; i < numValues; i++) {\n const char* value = values[i].value.c_str();\n fwrite(value, sizeof(char), strlen(value), fp);\n }\n \n \/\/ darts\n fwrite(dict.array(), sizeof(char), dartsSize, fp);\n \n fclose(fp);\n}\n\n#ifdef DEBUG_WRITE_TEXT\nvoid write_text_file() {\n FILE* fp;\n int i;\n fp = fopen(\"datrie.txt\", \"w\");\n fprintf(fp, \"%d\\n\", lexicon_count);\n for (i = 0; i < lexicon_count; i++) {\n char* buff = ucs4_to_utf8(lexicon[i].value, (size_t)-1);\n fprintf(fp, \"%s\\n\", buff);\n free(buff);\n }\n for (i = 0; i < DATRIE_SIZE; i++) {\n if (dat[i].parent != DATRIE_UNUSED) {\n fprintf(fp, \"%d %d %d %d\\n\", i, dat[i].base, dat[i].parent, dat[i].word);\n }\n }\n fclose(fp);\n}\n\n#endif \/* ifdef DEBUG_WRITE_TEXT *\/\n\nvoid show_version() {\n printf(_(\"\\nOpen Chinese Convert (OpenCC) Dictionary Tool\\nVersion %s\\n\\n\"),\n VERSION);\n}\n\nvoid show_usage() {\n show_version();\n printf(_(\"Usage:\\n\"));\n printf(_(\" opencc_dict -i input_file -o output_file\\n\\n\"));\n printf(_(\" -i input_file\\n\"));\n printf(_(\" Read data from input_file.\\n\"));\n printf(_(\" -o output_file\\n\"));\n printf(_(\" Write converted data to output_file.\\n\"));\n printf(_(\"\\n\"));\n printf(_(\"\\n\"));\n}\n\nint main(int argc, char** argv) {\n static int oc;\n static char input_file[BUFFER_SIZE], output_file[BUFFER_SIZE];\n int input_file_specified = 0, output_file_specified = 0;\n\n#ifdef ENABLE_GETTEXT\n setlocale(LC_ALL, \"\");\n bindtextdomain(PACKAGE_NAME, LOCALEDIR);\n#endif \/* ifdef ENABLE_GETTEXT *\/\n while ((oc = getopt(argc, argv, \"vh-:i:o:\")) != -1) {\n switch (oc) {\n case 'v':\n show_version();\n return 0;\n case 'h':\n case '?':\n show_usage();\n return 0;\n case '-':\n if (strcmp(optarg, \"version\") == 0) {\n show_version();\n } else {\n show_usage();\n }\n return 0;\n case 'i':\n strcpy(input_file, optarg);\n input_file_specified = 1;\n break;\n case 'o':\n strcpy(output_file, optarg);\n output_file_specified = 1;\n break;\n }\n }\n if (!input_file_specified) {\n fprintf(stderr, _(\"Please specify input file using -i.\\n\"));\n show_usage();\n return 1;\n }\n if (!output_file_specified) {\n fprintf(stderr, _(\"Please specify output file using -o.\\n\"));\n show_usage();\n return 1;\n }\n init(input_file);\n make();\n output(output_file);\n#ifdef DEBUG_WRITE_TEXT\n write_text_file();\n#endif \/* ifdef DEBUG_WRITE_TEXT *\/\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_FEATURES_IMPL_FEATURE_H_\n#define PCL_FEATURES_IMPL_FEATURE_H_\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ninline void\npcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,\n const Eigen::Vector4f &point,\n Eigen::Vector4f &plane_parameters, float &curvature)\n{\n solvePlaneParameters (covariance_matrix, plane_parameters [0], plane_parameters [1], plane_parameters [2], curvature);\n\n plane_parameters[3] = 0;\n \/\/ Hessian form (D = nc . p_plane (centroid here) + p)\n plane_parameters[3] = -1 * plane_parameters.dot (point);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ninline void\npcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,\n float &nx, float &ny, float &nz, float &curvature)\n{\n \/\/ Avoid getting hung on Eigen's optimizers\n\/\/ for (int i = 0; i < 9; ++i)\n\/\/ if (!pcl_isfinite (covariance_matrix.coeff (i)))\n\/\/ {\n\/\/ \/\/PCL_WARN (\"[pcl::solvePlaneParameteres] Covariance matrix has NaN\/Inf values!\\n\");\n\/\/ nx = ny = nz = curvature = std::numeric_limits::quiet_NaN ();\n\/\/ return;\n\/\/ }\n \/\/ Extract the smallest eigenvalue and its eigenvector\n EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value;\n EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;\n pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);\n\n nx = eigen_vector [0];\n ny = eigen_vector [1];\n nz = eigen_vector [2];\n\n \/\/ Compute the curvature surface change\n float eig_sum = covariance_matrix.coeff (0) + covariance_matrix.coeff (4) + covariance_matrix.coeff (8);\n if (eig_sum != 0)\n curvature = fabsf (eigen_value \/ eig_sum);\n else\n curvature = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::Feature::initCompute ()\n{\n if (!PCLBase::initCompute ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] Init failed.\\n\", getClassName ().c_str ());\n return (false);\n }\n\n \/\/ If the dataset is empty, just return\n if (input_->points.empty ())\n {\n PCL_ERROR (\"[pcl::%s::compute] input_ is empty!\\n\", getClassName ().c_str ());\n \/\/ Cleanup\n deinitCompute ();\n return (false);\n }\n\n \/\/ If no search surface has been defined, use the input dataset as the search surface itself\n if (!surface_)\n {\n fake_surface_ = true;\n surface_ = input_;\n }\n\n \/\/ Check if a space search locator was given\n if (!tree_)\n {\n if (surface_->isOrganized () && input_->isOrganized ())\n tree_.reset (new pcl::search::OrganizedNeighbor ());\n else\n tree_.reset (new pcl::search::KdTree (false));\n }\n \/\/ Send the surface dataset to the spatial locator\n tree_->setInputCloud (surface_);\n\n \/\/ Do a fast check to see if the search parameters are well defined\n if (search_radius_ != 0.0)\n {\n if (k_ != 0)\n {\n PCL_ERROR (\"[pcl::%s::compute] \", getClassName ().c_str ());\n PCL_ERROR (\"Both radius (%f) and K (%d) defined! \", search_radius_, k_);\n PCL_ERROR (\"Set one of them to zero first and then re-run compute ().\\n\");\n \/\/ Cleanup\n deinitCompute ();\n return (false);\n }\n else \/\/ Use the radiusSearch () function\n {\n search_parameter_ = search_radius_;\n if (surface_ == input_) \/\/ if the two surfaces are the same\n {\n \/\/ Declare the search locator definition\n int (KdTree::*radiusSearch)(int index, double radius, std::vector &k_indices,\n std::vector &k_distances, unsigned int max_nn) const = &KdTree::radiusSearch;\n search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, 0);\n }\n\n \/\/ Declare the search locator definition\n int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius,\n std::vector &k_indices, std::vector &k_distances,\n unsigned int max_nn) const = &pcl::search::Search::radiusSearch;\n search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, 0);\n }\n }\n else\n {\n if (k_ != 0) \/\/ Use the nearestKSearch () function\n {\n search_parameter_ = k_;\n if (surface_ == input_) \/\/ if the two surfaces are the same\n {\n \/\/ Declare the search locator definition\n int (KdTree::*nearestKSearch)(int index, int k, std::vector &k_indices,\n std::vector &k_distances) const = &KdTree::nearestKSearch;\n search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4);\n }\n \/\/ Declare the search locator definition\n int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector &k_indices,\n std::vector &k_distances) const = &KdTree::nearestKSearch;\n search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5);\n }\n else\n {\n PCL_ERROR (\"[pcl::%s::compute] Neither radius nor K defined! \", getClassName ().c_str ());\n PCL_ERROR (\"Set one of them to a positive number first and then re-run compute ().\\n\");\n \/\/ Cleanup\n deinitCompute ();\n return (false);\n }\n }\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::Feature::deinitCompute ()\n{\n \/\/ Reset the surface\n if (fake_surface_)\n {\n surface_.reset ();\n fake_surface_ = false;\n }\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::Feature::compute (PointCloudOut &output)\n{\n if (!initCompute ())\n {\n output.width = output.height = 0;\n output.points.clear ();\n return;\n }\n\n \/\/ Copy the header\n output.header = input_->header;\n\n \/\/ Resize the output dataset\n if (output.points.size () != indices_->size ())\n output.points.resize (indices_->size ());\n \/\/ Check if the output will be computed for all points or only a subset\n if (indices_->size () != input_->points.size ())\n {\n output.width = static_cast (indices_->size ());\n output.height = 1;\n }\n else\n {\n output.width = input_->width;\n output.height = input_->height;\n }\n output.is_dense = input_->is_dense;\n\n \/\/ Perform the actual feature computation\n computeFeature (output);\n\n deinitCompute ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::Feature::computeEigen (pcl::PointCloud &output)\n{\n if (!initCompute ())\n {\n output.width = output.height = 0;\n output.points.resize (0, 0);\n return;\n }\n\n \/\/ Copy the properties\n\/\/#ifndef USE_ROS\n\/\/ output.properties.acquisition_time = input_->header.stamp;\n\/\/#endif\n output.properties.sensor_origin = input_->sensor_origin_;\n output.properties.sensor_orientation = input_->sensor_orientation_;\n\n \/\/ Check if the output will be computed for all points or only a subset\n if (indices_->size () != input_->points.size ())\n {\n output.width = static_cast (indices_->size ());\n output.height = 1;\n }\n else\n {\n output.width = input_->width;\n output.height = input_->height;\n }\n\n output.is_dense = input_->is_dense;\n\n \/\/ Perform the actual feature computation\n computeFeatureEigen (output);\n\n deinitCompute ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::FeatureFromNormals::initCompute ()\n{\n if (!Feature::initCompute ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] Init failed.\\n\", getClassName ().c_str ());\n return (false);\n }\n\n \/\/ Check if input normals are set\n if (!normals_)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] No input dataset containing normals was given!\\n\", getClassName ().c_str ());\n Feature::deinitCompute ();\n return (false);\n }\n\n \/\/ Check if the size of normals is the same as the size of the surface\n if (normals_->points.size () != surface_->points.size ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] \", getClassName ().c_str ());\n PCL_ERROR (\"The number of points in the input dataset (%u) differs from \", surface_->points.size ());\n PCL_ERROR (\"the number of points in the dataset containing the normals (%u)!\\n\", normals_->points.size ());\n Feature::deinitCompute ();\n return (false);\n }\n\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::FeatureFromLabels::initCompute ()\n{\n if (!Feature::initCompute ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] Init failed.\\n\", getClassName ().c_str ());\n return (false);\n }\n\n \/\/ Check if input normals are set\n if (!labels_)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] No input dataset containing labels was given!\\n\", getClassName ().c_str ());\n Feature::deinitCompute ();\n return (false);\n }\n\n \/\/ Check if the size of normals is the same as the size of the surface\n if (labels_->points.size () != surface_->points.size ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the labels!\\n\", getClassName ().c_str ());\n Feature::deinitCompute ();\n return (false);\n }\n\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::FeatureWithLocalReferenceFrames::initLocalReferenceFrames (const PointCloudInConstPtr& input,\n const LRFEstimationPtr& lrf_estimation)\n{\n \/\/ Check if input frames are set\n if (!frames_)\n {\n if (!lrf_estimation)\n {\n PCL_ERROR (\"[initLocalReferenceFrames] No input dataset containing reference frames was given!\\n\");\n return (false);\n } else\n {\n PCL_WARN (\"[initLocalReferenceFrames] No input dataset containing reference frames was given! Default computation with %s\\n\", lrf_estimation->getClassName ());\n lrf_estimation->compute (*frames_);\n }\n }\n\n \/\/ Check if the size of frames is the same as the size of the input cloud\n if (frames_->points.size () != input->points.size ())\n {\n if (!lrf_estimation)\n {\n PCL_ERROR (\"[initLocalReferenceFrames] The number of points in the input dataset differs from the number of points in the dataset containing the reference frames!\\n\");\n return (false);\n } else\n {\n PCL_WARN (\"[initLocalReferenceFrames] The number of points in the input dataset differs from the number of points in the dataset containing the reference frames! Default computation with %s\\n\", lrf_estimation->getClassName ());\n lrf_estimation->compute (*frames_);\n }\n }\n\n return (true);\n}\n\n#endif \/\/#ifndef PCL_FEATURES_IMPL_FEATURE_H_\n\nFeatureWithLocalReferenceFrames: Minor bugs fixed\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_FEATURES_IMPL_FEATURE_H_\n#define PCL_FEATURES_IMPL_FEATURE_H_\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ninline void\npcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,\n const Eigen::Vector4f &point,\n Eigen::Vector4f &plane_parameters, float &curvature)\n{\n solvePlaneParameters (covariance_matrix, plane_parameters [0], plane_parameters [1], plane_parameters [2], curvature);\n\n plane_parameters[3] = 0;\n \/\/ Hessian form (D = nc . p_plane (centroid here) + p)\n plane_parameters[3] = -1 * plane_parameters.dot (point);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ninline void\npcl::solvePlaneParameters (const Eigen::Matrix3f &covariance_matrix,\n float &nx, float &ny, float &nz, float &curvature)\n{\n \/\/ Avoid getting hung on Eigen's optimizers\n\/\/ for (int i = 0; i < 9; ++i)\n\/\/ if (!pcl_isfinite (covariance_matrix.coeff (i)))\n\/\/ {\n\/\/ \/\/PCL_WARN (\"[pcl::solvePlaneParameteres] Covariance matrix has NaN\/Inf values!\\n\");\n\/\/ nx = ny = nz = curvature = std::numeric_limits::quiet_NaN ();\n\/\/ return;\n\/\/ }\n \/\/ Extract the smallest eigenvalue and its eigenvector\n EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value;\n EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;\n pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);\n\n nx = eigen_vector [0];\n ny = eigen_vector [1];\n nz = eigen_vector [2];\n\n \/\/ Compute the curvature surface change\n float eig_sum = covariance_matrix.coeff (0) + covariance_matrix.coeff (4) + covariance_matrix.coeff (8);\n if (eig_sum != 0)\n curvature = fabsf (eigen_value \/ eig_sum);\n else\n curvature = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::Feature::initCompute ()\n{\n if (!PCLBase::initCompute ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] Init failed.\\n\", getClassName ().c_str ());\n return (false);\n }\n\n \/\/ If the dataset is empty, just return\n if (input_->points.empty ())\n {\n PCL_ERROR (\"[pcl::%s::compute] input_ is empty!\\n\", getClassName ().c_str ());\n \/\/ Cleanup\n deinitCompute ();\n return (false);\n }\n\n \/\/ If no search surface has been defined, use the input dataset as the search surface itself\n if (!surface_)\n {\n fake_surface_ = true;\n surface_ = input_;\n }\n\n \/\/ Check if a space search locator was given\n if (!tree_)\n {\n if (surface_->isOrganized () && input_->isOrganized ())\n tree_.reset (new pcl::search::OrganizedNeighbor ());\n else\n tree_.reset (new pcl::search::KdTree (false));\n }\n \/\/ Send the surface dataset to the spatial locator\n tree_->setInputCloud (surface_);\n\n \/\/ Do a fast check to see if the search parameters are well defined\n if (search_radius_ != 0.0)\n {\n if (k_ != 0)\n {\n PCL_ERROR (\"[pcl::%s::compute] \", getClassName ().c_str ());\n PCL_ERROR (\"Both radius (%f) and K (%d) defined! \", search_radius_, k_);\n PCL_ERROR (\"Set one of them to zero first and then re-run compute ().\\n\");\n \/\/ Cleanup\n deinitCompute ();\n return (false);\n }\n else \/\/ Use the radiusSearch () function\n {\n search_parameter_ = search_radius_;\n if (surface_ == input_) \/\/ if the two surfaces are the same\n {\n \/\/ Declare the search locator definition\n int (KdTree::*radiusSearch)(int index, double radius, std::vector &k_indices,\n std::vector &k_distances, unsigned int max_nn) const = &KdTree::radiusSearch;\n search_method_ = boost::bind (radiusSearch, boost::ref (tree_), _1, _2, _3, _4, 0);\n }\n\n \/\/ Declare the search locator definition\n int (KdTree::*radiusSearchSurface)(const PointCloudIn &cloud, int index, double radius,\n std::vector &k_indices, std::vector &k_distances,\n unsigned int max_nn) const = &pcl::search::Search::radiusSearch;\n search_method_surface_ = boost::bind (radiusSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5, 0);\n }\n }\n else\n {\n if (k_ != 0) \/\/ Use the nearestKSearch () function\n {\n search_parameter_ = k_;\n if (surface_ == input_) \/\/ if the two surfaces are the same\n {\n \/\/ Declare the search locator definition\n int (KdTree::*nearestKSearch)(int index, int k, std::vector &k_indices,\n std::vector &k_distances) const = &KdTree::nearestKSearch;\n search_method_ = boost::bind (nearestKSearch, boost::ref (tree_), _1, _2, _3, _4);\n }\n \/\/ Declare the search locator definition\n int (KdTree::*nearestKSearchSurface)(const PointCloudIn &cloud, int index, int k, std::vector &k_indices,\n std::vector &k_distances) const = &KdTree::nearestKSearch;\n search_method_surface_ = boost::bind (nearestKSearchSurface, boost::ref (tree_), _1, _2, _3, _4, _5);\n }\n else\n {\n PCL_ERROR (\"[pcl::%s::compute] Neither radius nor K defined! \", getClassName ().c_str ());\n PCL_ERROR (\"Set one of them to a positive number first and then re-run compute ().\\n\");\n \/\/ Cleanup\n deinitCompute ();\n return (false);\n }\n }\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::Feature::deinitCompute ()\n{\n \/\/ Reset the surface\n if (fake_surface_)\n {\n surface_.reset ();\n fake_surface_ = false;\n }\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::Feature::compute (PointCloudOut &output)\n{\n if (!initCompute ())\n {\n output.width = output.height = 0;\n output.points.clear ();\n return;\n }\n\n \/\/ Copy the header\n output.header = input_->header;\n\n \/\/ Resize the output dataset\n if (output.points.size () != indices_->size ())\n output.points.resize (indices_->size ());\n \/\/ Check if the output will be computed for all points or only a subset\n if (indices_->size () != input_->points.size ())\n {\n output.width = static_cast (indices_->size ());\n output.height = 1;\n }\n else\n {\n output.width = input_->width;\n output.height = input_->height;\n }\n output.is_dense = input_->is_dense;\n\n \/\/ Perform the actual feature computation\n computeFeature (output);\n\n deinitCompute ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate void\npcl::Feature::computeEigen (pcl::PointCloud &output)\n{\n if (!initCompute ())\n {\n output.width = output.height = 0;\n output.points.resize (0, 0);\n return;\n }\n\n \/\/ Copy the properties\n\/\/#ifndef USE_ROS\n\/\/ output.properties.acquisition_time = input_->header.stamp;\n\/\/#endif\n output.properties.sensor_origin = input_->sensor_origin_;\n output.properties.sensor_orientation = input_->sensor_orientation_;\n\n \/\/ Check if the output will be computed for all points or only a subset\n if (indices_->size () != input_->points.size ())\n {\n output.width = static_cast (indices_->size ());\n output.height = 1;\n }\n else\n {\n output.width = input_->width;\n output.height = input_->height;\n }\n\n output.is_dense = input_->is_dense;\n\n \/\/ Perform the actual feature computation\n computeFeatureEigen (output);\n\n deinitCompute ();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::FeatureFromNormals::initCompute ()\n{\n if (!Feature::initCompute ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] Init failed.\\n\", getClassName ().c_str ());\n return (false);\n }\n\n \/\/ Check if input normals are set\n if (!normals_)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] No input dataset containing normals was given!\\n\", getClassName ().c_str ());\n Feature::deinitCompute ();\n return (false);\n }\n\n \/\/ Check if the size of normals is the same as the size of the surface\n if (normals_->points.size () != surface_->points.size ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] \", getClassName ().c_str ());\n PCL_ERROR (\"The number of points in the input dataset (%u) differs from \", surface_->points.size ());\n PCL_ERROR (\"the number of points in the dataset containing the normals (%u)!\\n\", normals_->points.size ());\n Feature::deinitCompute ();\n return (false);\n }\n\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::FeatureFromLabels::initCompute ()\n{\n if (!Feature::initCompute ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] Init failed.\\n\", getClassName ().c_str ());\n return (false);\n }\n\n \/\/ Check if input normals are set\n if (!labels_)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] No input dataset containing labels was given!\\n\", getClassName ().c_str ());\n Feature::deinitCompute ();\n return (false);\n }\n\n \/\/ Check if the size of normals is the same as the size of the surface\n if (labels_->points.size () != surface_->points.size ())\n {\n PCL_ERROR (\"[pcl::%s::initCompute] The number of points in the input dataset differs from the number of points in the dataset containing the labels!\\n\", getClassName ().c_str ());\n Feature::deinitCompute ();\n return (false);\n }\n\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate bool\npcl::FeatureWithLocalReferenceFrames::initLocalReferenceFrames (const PointCloudInConstPtr& input,\n const LRFEstimationPtr& lrf_estimation)\n{\n \/\/ Check if input frames are set\n if (!frames_)\n {\n if (!lrf_estimation)\n {\n PCL_ERROR (\"[initLocalReferenceFrames] No input dataset containing reference frames was given!\\n\");\n return (false);\n } else\n {\n PCL_WARN (\"[initLocalReferenceFrames] No input dataset containing reference frames was given! Proceed using default\\n\");\n PointCloudLRFPtr default_frames (new PointCloudLRF());\n lrf_estimation->compute (*default_frames);\n frames_ = default_frames;\n }\n }\n\n \/\/ Check if the size of frames is the same as the size of the input cloud\n if (frames_->points.size () != input->points.size ())\n {\n if (!lrf_estimation)\n {\n PCL_ERROR (\"[initLocalReferenceFrames] The number of points in the input dataset differs from the number of points in the dataset containing the reference frames!\\n\");\n return (false);\n } else\n {\n PCL_WARN (\"[initLocalReferenceFrames] The number of points in the input dataset differs from the number of points in the dataset containing the reference frames! Proceed using default\\n\");\n PointCloudLRFPtr default_frames (new PointCloudLRF());\n lrf_estimation->compute (*default_frames);\n frames_ = default_frames;\n }\n }\n\n return (true);\n}\n\n#endif \/\/#ifndef PCL_FEATURES_IMPL_FEATURE_H_\n\n<|endoftext|>"} {"text":"#65293# don't use namespace svxform her for svx_light<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2015, Youssef Kashef\n\/\/ Copyright (c) 2015, ELM Library Project\n\/\/ 3-clause BSD License\n\/\/\n\/\/M*\/\n\/** @file Implement greedy projection triangulation\n *\/\n#include \"elm\/layers\/triangulation.h\"\n\n#ifdef __WITH_PCL \/\/ the layer is otherwise implemented as unsupported\n\n#include \n#include \n#include \n#include \n#include \/\/ for eigen2cv(), must be preceeded definitio of Eigen either PCL or #include \n\n#include \"elm\/core\/defs.h\"\n#include \"elm\/core\/exception.h\"\n#include \"elm\/core\/featuredata.h\"\n#include \"elm\/core\/graph\/adjacency.h\"\n#include \"elm\/core\/inputname.h\"\n#include \"elm\/core\/layerconfig.h\"\n#include \"elm\/core\/signal.h\"\n#include \"elm\/ts\/layerattr_.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace pcl;\nusing namespace elm;\n\n\/\/ initialize paramter keys\nconst string Triangulation::PARAM_SEARCH_RADIUS = \"radius\";\nconst string Triangulation::PARAM_MU = \"mu\";\nconst string Triangulation::PARAM_MAX_NN = \"max_nn\";\nconst string Triangulation::PARAM_MAX_SURFACE_ANGLE = \"max_surface_angle\";\nconst string Triangulation::PARAM_MIN_ANGLE = \"min_angle\";\nconst string Triangulation::PARAM_MAX_ANGLE = \"max_angle\";\nconst string Triangulation::PARAM_IS_NORMAL_CONSISTENT = \"normal_consistency\";\n\n\/\/ initialize default float paramter values\nconst float Triangulation::DEFAULT_SEARCH_RADIUS = 0.025f;\nconst float Triangulation::DEFAULT_MU = 2.5f;\nconst float Triangulation::DEFAULT_MAX_SURFACE_ANGLE = ELM_PI2 \/ 2.f;\nconst float Triangulation::DEFAULT_MIN_ANGLE = CV_PI \/ 18.f;\nconst float Triangulation::DEFAULT_MAX_ANGLE = 2 * CV_PI \/ 3.f;\nconst int Triangulation::DEFAULT_MAX_NN = 100; \/\/\/< maximum neighrest neighbors\nconst bool Triangulation::DEFAULT_IS_NORMAL_CONSISTENCY = false;\n\n\/\/ initialize I\/O names\nconst string Triangulation::KEY_INPUT_POINT_CLOUD = \"cloud\";\nconst string Triangulation::KEY_OUTPUT_VERTICES = \"vertices\";\nconst string Triangulation::KEY_OUTPUT_OPT_ADJACENCY = \"adjacency\";\n\n\/** @todo why does define guard lead to undefined reference error?\n *\/\n\/\/#ifdef __WITH_GTEST\n#include \ntemplate <>\nelm::MapIONames LayerAttr_::io_pairs = boost::assign::map_list_of\n ELM_ADD_INPUT_PAIR(Triangulation::KEY_INPUT_POINT_CLOUD)\n ELM_ADD_OUTPUT_PAIR(Triangulation::KEY_OUTPUT_VERTICES)\n ;\n\/\/#endif\n\nTriangulation::Triangulation()\n : base_Layer()\n{\n}\n\nvoid Triangulation::Clear()\n{\n gp3 = pcl::GreedyProjectionTriangulation();\n}\n\nvoid Triangulation::Reconfigure(const LayerConfig &cfg)\n{\n PTree p = cfg.Params();\n\n float search_radius = p.get(PARAM_SEARCH_RADIUS, DEFAULT_SEARCH_RADIUS);\n\n float mu = p.get( PARAM_MU, DEFAULT_MU);\n int max_nn = p.get( PARAM_MAX_NN, DEFAULT_MAX_NN);\n float max_surface_angle = p.get( PARAM_MAX_SURFACE_ANGLE, DEFAULT_MAX_SURFACE_ANGLE);\n float min_angle = p.get( PARAM_MIN_ANGLE, DEFAULT_MIN_ANGLE);\n float max_angle = p.get( PARAM_MAX_ANGLE, DEFAULT_MAX_ANGLE);\n bool is_normal_consistency = p.get(PARAM_IS_NORMAL_CONSISTENT, DEFAULT_IS_NORMAL_CONSISTENCY);\n\n \/\/ Set the maximum distance between connected points (maximum edge length)\n gp3.setSearchRadius(search_radius);\n\n \/\/ Set typical values for the parameters\n gp3.setMu(mu);\n gp3.setMaximumNearestNeighbors(max_nn);\n gp3.setMaximumSurfaceAngle(max_surface_angle);\n gp3.setMinimumAngle(min_angle);\n gp3.setMaximumAngle(max_angle);\n gp3.setNormalConsistency(is_normal_consistency);\n}\n\nvoid Triangulation::InputNames(const LayerInputNames &io)\n{\n name_src_cloud_ = io.Input(KEY_INPUT_POINT_CLOUD);\n}\n\nvoid Triangulation::OutputNames(const LayerOutputNames &io)\n{\n name_vertices_ = io.Output(KEY_OUTPUT_VERTICES);\n name_opt_adj_ = io.OutputOpt(KEY_OUTPUT_OPT_ADJACENCY);\n}\n\nvoid Triangulation::Activate(const Signal &signal)\n{\n CloudXYZPtr cld_in = signal.MostRecent(name_src_cloud_).get();\n if(cld_in->empty()) {\n\n ELM_THROW_BAD_DIMS(\"Cannot Activate Triangulation layer with empty input point cloud.\");\n }\n\n \/\/ Normal estimation*\n NormalEstimation norml_est;\n PointCloud::Ptr normals(new PointCloud);\n search::KdTree::Ptr tree(new search::KdTree);\n\n tree->setInputCloud(cld_in);\n norml_est.setInputCloud(cld_in);\n norml_est.setSearchMethod(tree);\n norml_est.setKSearch(20);\n norml_est.compute(*normals);\n \/\/* normals should now contain the point normals + surface curvatures\n\n \/\/ Concatenate the XYZ and normal fields*\n PointCloud::Ptr cloud_with_normals(new PointCloud);\n concatenateFields(*cld_in, *normals, *cloud_with_normals);\n \/\/* cloud_with_normals = cloud + normals\n\n \/\/ Create search tree*\n search::KdTree::Ptr tree2(new search::KdTree);\n tree2->setInputCloud(cloud_with_normals);\n\n \/\/ Get result\n gp3.setInputCloud(cloud_with_normals);\n gp3.setSearchMethod(tree2);\n\n \/\/ PolygonMesh triangles;\n \/\/ gp3.reconstruct(triangles);\n\n std::vector vertices;\n gp3.reconstruct(vertices);\n\n vertices_ = VecVertices2Mat(vertices, false);\n\n if(name_opt_adj_) {\n\n TriangulatedCloudToAdjacency(cld_in, vertices, adj_);\n }\n}\n\nvoid Triangulation::Response(Signal &signal)\n{\n \/\/ Additional vertex information\n\/\/ vector parts = gp3.getPartIDs();\n\/\/ vector states = gp3.getPointStates();\n\n signal.Append(name_vertices_, vertices_);\n\n if(name_opt_adj_) {\n\n signal.Append(name_opt_adj_.get(), adj_);\n }\n}\n\n#endif \/\/ __WITH_PCL\nremove unused includes and reuce code clutter\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2015, Youssef Kashef\n\/\/ Copyright (c) 2015, ELM Library Project\n\/\/ 3-clause BSD License\n\/\/\n\/\/M*\/\n\/** @file Implement greedy projection triangulation\n *\/\n#include \"elm\/layers\/triangulation.h\"\n\n#ifdef __WITH_PCL \/\/ the layer is otherwise implemented as unsupported\n\n#include \n#include \n#include \n\/\/#include \/\/ for eigen2cv(), must be preceeded definitio of Eigen either PCL or #include \n\n#include \"elm\/core\/defs.h\" \/\/ ELM_PI2\n#include \"elm\/core\/exception.h\"\n#include \"elm\/core\/featuredata.h\"\n#include \"elm\/core\/graph\/adjacency.h\"\n#include \"elm\/core\/inputname.h\"\n#include \"elm\/core\/layerconfig.h\"\n#include \"elm\/core\/signal.h\"\n#include \"elm\/ts\/layerattr_.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace pcl;\nusing namespace elm;\n\n\/\/ initialize paramter keys\nconst string Triangulation::PARAM_SEARCH_RADIUS = \"radius\";\nconst string Triangulation::PARAM_MU = \"mu\";\nconst string Triangulation::PARAM_MAX_NN = \"max_nn\";\nconst string Triangulation::PARAM_MAX_SURFACE_ANGLE = \"max_surface_angle\";\nconst string Triangulation::PARAM_MIN_ANGLE = \"min_angle\";\nconst string Triangulation::PARAM_MAX_ANGLE = \"max_angle\";\nconst string Triangulation::PARAM_IS_NORMAL_CONSISTENT = \"normal_consistency\";\n\n\/\/ initialize default float paramter values\nconst float Triangulation::DEFAULT_SEARCH_RADIUS = 0.025f;\nconst float Triangulation::DEFAULT_MU = 2.5f;\nconst float Triangulation::DEFAULT_MAX_SURFACE_ANGLE = ELM_PI2 \/ 2.f;\nconst float Triangulation::DEFAULT_MIN_ANGLE = CV_PI \/ 18.f;\nconst float Triangulation::DEFAULT_MAX_ANGLE = 2 * CV_PI \/ 3.f;\nconst int Triangulation::DEFAULT_MAX_NN = 100; \/\/\/< maximum neighrest neighbors\nconst bool Triangulation::DEFAULT_IS_NORMAL_CONSISTENCY = false;\n\n\/\/ initialize I\/O names\nconst string Triangulation::KEY_INPUT_POINT_CLOUD = \"cloud\";\nconst string Triangulation::KEY_OUTPUT_VERTICES = \"vertices\";\nconst string Triangulation::KEY_OUTPUT_OPT_ADJACENCY = \"adjacency\";\n\n#include \ntemplate <>\nelm::MapIONames LayerAttr_::io_pairs = boost::assign::map_list_of\n ELM_ADD_INPUT_PAIR(Triangulation::KEY_INPUT_POINT_CLOUD)\n ELM_ADD_OUTPUT_PAIR(Triangulation::KEY_OUTPUT_VERTICES)\n ;\n\nTriangulation::Triangulation()\n : base_Layer()\n{\n}\n\nvoid Triangulation::Clear()\n{\n gp3 = pcl::GreedyProjectionTriangulation();\n}\n\nvoid Triangulation::Reconfigure(const LayerConfig &cfg)\n{\n PTree p = cfg.Params();\n\n float search_radius = p.get(PARAM_SEARCH_RADIUS, DEFAULT_SEARCH_RADIUS);\n\n float mu = p.get( PARAM_MU, DEFAULT_MU);\n int max_nn = p.get( PARAM_MAX_NN, DEFAULT_MAX_NN);\n float max_surface_angle = p.get( PARAM_MAX_SURFACE_ANGLE, DEFAULT_MAX_SURFACE_ANGLE);\n float min_angle = p.get( PARAM_MIN_ANGLE, DEFAULT_MIN_ANGLE);\n float max_angle = p.get( PARAM_MAX_ANGLE, DEFAULT_MAX_ANGLE);\n bool is_normal_consistency = p.get(PARAM_IS_NORMAL_CONSISTENT, DEFAULT_IS_NORMAL_CONSISTENCY);\n\n \/\/ Set the maximum distance between connected points (maximum edge length)\n gp3.setSearchRadius(search_radius);\n\n \/\/ Set typical values for the parameters\n gp3.setMu(mu);\n gp3.setMaximumNearestNeighbors(max_nn);\n gp3.setMaximumSurfaceAngle(max_surface_angle);\n gp3.setMinimumAngle(min_angle);\n gp3.setMaximumAngle(max_angle);\n gp3.setNormalConsistency(is_normal_consistency);\n}\n\nvoid Triangulation::InputNames(const LayerInputNames &io)\n{\n name_src_cloud_ = io.Input(KEY_INPUT_POINT_CLOUD);\n}\n\nvoid Triangulation::OutputNames(const LayerOutputNames &io)\n{\n name_vertices_ = io.Output(KEY_OUTPUT_VERTICES);\n name_opt_adj_ = io.OutputOpt(KEY_OUTPUT_OPT_ADJACENCY);\n}\n\nvoid Triangulation::Activate(const Signal &signal)\n{\n CloudXYZPtr cld_in = signal.MostRecent(name_src_cloud_).get();\n if(cld_in->empty()) {\n\n ELM_THROW_BAD_DIMS(\"Cannot Activate Triangulation layer with empty input point cloud.\");\n }\n\n \/\/ Normal estimation\n NormalEstimation norml_est;\n PointCloud::Ptr normals(new PointCloud);\n search::KdTree::Ptr tree(new search::KdTree);\n\n tree->setInputCloud(cld_in);\n norml_est.setInputCloud(cld_in);\n norml_est.setSearchMethod(tree);\n norml_est.setKSearch(20);\n norml_est.compute(*normals);\n \/\/ normals should now contain the point normals + surface curvatures\n\n \/\/ Concatenate the XYZ and normal fields*\n PointCloud::Ptr cloud_with_normals(new PointCloud);\n concatenateFields(*cld_in, *normals, *cloud_with_normals);\n\n \/\/ Create search tree*\n search::KdTree::Ptr tree2(new search::KdTree);\n tree2->setInputCloud(cloud_with_normals);\n\n \/\/ Get result\n gp3.setInputCloud(cloud_with_normals);\n gp3.setSearchMethod(tree2);\n\n std::vector vertices;\n gp3.reconstruct(vertices);\n\n vertices_ = VecVertices2Mat(vertices, false);\n\n if(name_opt_adj_) {\n\n TriangulatedCloudToAdjacency(cld_in, vertices, adj_);\n }\n}\n\nvoid Triangulation::Response(Signal &signal)\n{\n \/\/ Additional vertex information\n\/\/ vector parts = gp3.getPartIDs();\n\/\/ vector states = gp3.getPointStates();\n\n signal.Append(name_vertices_, vertices_);\n\n if(name_opt_adj_) {\n\n signal.Append(name_opt_adj_.get(), adj_);\n }\n}\n\n#endif \/\/ __WITH_PCL\n<|endoftext|>"} {"text":"\/\/ System Dependencies\n#include \n#include \n\n\/\/ External Dependencies\n#include \"..\/..\/core\/include\/spinlock.h\"\n#include \"..\/..\/core\/include\/system.h\"\n\n\/\/ Module Dependencies\n#include \"componentadapterproperties.h\"\n#include \"..\/include\/componentadapter.h\"\n#include \"..\/include\/webview.h\"\n\nnamespace native\n{\n\tnamespace ui\n\t{\n\t\tclass Win32WebViewAdapter : public WebViewAdapter, public IOleClientSite, public IOleInPlaceSite\n\t\t{\n\t\tpublic:\n\t\t\t\/\/ Constructor\n\t\t\tWin32WebViewAdapter(WebView* view, HWND hwnd);\n\t\t\t~Win32WebViewAdapter();\n\n\t\t\t\/\/ Helper Functions\n\t\t\tvoid setSize(const Size& size);\n\t\t\tvirtual void navigate(const String& url) override;\n\t\t\tvirtual void goBack() override;\n\t\t\tvirtual void goForward() override;\n\n\t\t\t\/\/ IUnknown Functions\n\t\t\tvirtual HRESULT QueryInterface(REFIID riid, void** ppvObject) override;\n\t\t\tvirtual ULONG AddRef() override { return 1; }\t\/\/ Unneeded\n\t\t\tvirtual ULONG Release() override { return 1; }\t\/\/ Unneeded\n\n\t\t\t\/\/ IOleClientSite Functions\n\t\t\tvirtual HRESULT SaveObject() override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk) override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT GetContainer(IOleContainer** ppContainer) override { return E_NOINTERFACE; }\n\t\t\tvirtual HRESULT ShowObject() override { return S_OK; }\n\t\t\tvirtual HRESULT OnShowWindow(BOOL fShow) override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT RequestNewObjectLayout() override { return E_NOTIMPL; }\n\n\t\t\t\/\/ IOleWindow Functions\n\t\t\tvirtual HRESULT GetWindow(HWND* phwnd) override;\n\t\t\tvirtual HRESULT ContextSensitiveHelp(BOOL fEnterMode) override { return E_NOTIMPL; }\n\n\t\t\t\/\/ IOleInPlaceSite Functions\n\t\t\tvirtual HRESULT CanInPlaceActivate() override { return S_OK; }\n\t\t\tvirtual HRESULT OnInPlaceActivate() override { return S_OK; }\n\t\t\tvirtual HRESULT OnUIActivate() override { return S_OK; }\n\t\t\tvirtual HRESULT GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo) override;\n\t\t\tvirtual HRESULT Scroll(SIZE scrollExtant) override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT OnUIDeactivate(BOOL fUndoable) override { return S_OK; }\n\t\t\tvirtual HRESULT OnInPlaceDeactivate() override { return S_OK; }\n\t\t\tvirtual HRESULT DiscardUndoState() override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT DeactivateAndUndo() override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT OnPosRectChange(LPCRECT lprcPosRect) override;\n\n\t\t\t\/\/ Instance Variables\n\t\t\tIStorage* storage;\n\t\t\tIOleObject* webObject;\n\t\t\tHWND hwnd;\n\t\t};\n\n\t\t\/*\n\t\t\tWebView Functions\n\t\t *\/\n\n\t\tWebView::WebView() : Component(new WebViewAdapter(this))\n\t\t{\n\t\t\tsetAlignment(Align::Fill);\n\t\t}\n\n\t\tvoid WebView::navigate(const String& url)\n\t\t{\n\t\t\t((WebViewAdapter*) getAdapter())->navigate(url);\n\t\t}\n\n\t\tvoid WebView::goBack()\n\t\t{\n\t\t\t((WebViewAdapter*) getAdapter())->goBack();\n\t\t}\n\n\t\tvoid WebView::goForward()\n\t\t{\n\t\t\t((WebViewAdapter*) getAdapter())->goForward();\n\t\t}\n\n\t\tvoid WebView::onSize(const Size& size)\n\t\t{\n\t\t\t((Win32WebViewAdapter*) getAdapter())->setSize(size);\n\t\t}\n\n\t\t\/*\n\t\t\tWebViewAdapter Functions\n\t\t*\/\n\n\t\tWebViewAdapter::WebViewAdapter(WebView* view) : ComponentAdapter({ view, nullptr, WS_CHILD | WS_VISIBLE, 0 })\n\t\t{\n\t\t}\n\n\t\tWebViewAdapter::~WebViewAdapter()\n\t\t{\n\t\t}\n\n\t\tvoid WebViewAdapter::navigate(const String& url)\n\t\t{\n\t\t\t\/\/ Always overridden.\n\t\t\tthrow NotSupportedException();\n\t\t}\n\n\t\tvoid WebViewAdapter::goBack()\n\t\t{\n\t\t\t\/\/ Always overridden.\n\t\t\tthrow NotSupportedException();\n\t\t}\n\n\t\tvoid WebViewAdapter::goForward()\n\t\t{\n\t\t\t\/\/ Always overridden.\n\t\t\tthrow NotSupportedException();\n\t\t}\n\n\t\t\/*\n\t\t\tBrowserData Functions\n\t\t*\/\n\n\t\tWin32WebViewAdapter::Win32WebViewAdapter(WebView* view, HWND hwnd) : WebViewAdapter(view), hwnd(hwnd)\n\t\t{\n\t\t\tstatic bool isOleInitialized = false;\n\t\t\tstatic SpinLock lock;\n\n\t\t\tlock.lock();\n\n\t\t\tif (!isOleInitialized)\n\t\t\t{\n\t\t\t\t\/\/ Initialise the ActiveX environment.\n\t\t\t\tisOleInitialized = true;\n\t\t\t\t::OleInitialize(NULL);\n\t\t\t\tSystem::onExit([]() { ::OleUninitialize(); });\n\t\t\t\t\n\t\t\t\t\/\/ Get the current process name.\n\t\t\t\t\/\/ TODO: Make this a function elsewhere.\n\t\t\t\tWCHAR buffer[MAX_PATH + 1];\n\t\t\t\t::GetModuleFileName(NULL, buffer, sizeof(buffer));\n\t\t\t\tString fileName = buffer;\n\t\t\t\tfileName = fileName.substring(fileName.lastIndexOf(L\"\\\\\") + 1, fileName.getLength());\n\n\t\t\t\t\/\/ Ensure we're using a decent browser version.\n\t\t\t\tHKEY browserEmulationKey;\n\t\t\t\tDWORD ieVersion = 11000;\t\/\/ IE11 pretty please.\n\t\t\t\t::RegOpenKeyEx(HKEY_CURRENT_USER, L\"SOFTWARE\\\\Microsoft\\\\Internet Explorer\\\\Main\\\\FeatureControl\\\\FEATURE_BROWSER_EMULATION\", 0, KEY_WRITE, &browserEmulationKey);\n\t\t\t\t::RegSetValueEx(browserEmulationKey, fileName.toArray(), 0, REG_DWORD, (BYTE*) &ieVersion, sizeof(ieVersion));\n\t\t\t\t::RegCloseKey(browserEmulationKey);\n\t\t\t}\n\n\t\t\tlock.release();\n\n\t\t\t\/\/ Create the ActiveX container.\n\t\t\tif (FAILED(::StgCreateStorageEx(NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_DIRECT | STGM_CREATE | STGM_DELETEONRELEASE, STGFMT_STORAGE, 0, NULL, NULL, IID_IStorage, (void**)&storage)))\n\t\t\t\tthrow UserInterfaceException(\"Failed to create ActiveX browser component.\");\n\n\t\t\tif (FAILED(::OleCreate(CLSID_WebBrowser, IID_IOleObject, OLERENDER_DRAW, NULL, this, storage, (LPVOID*) &webObject)))\n\t\t\t\tthrow UserInterfaceException(\"Failed to create ActiveX browser component.\");\n\n\t\t\t\/\/ Embed the ActiveX container in our Component.\n\t\t\tRECT rect = { 0 };\n\t\t\t::OleSetContainedObject(webObject, TRUE);\n\t\t\twebObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, -1, hwnd, &rect);\n\t\t}\n\n\t\tWin32WebViewAdapter::~Win32WebViewAdapter()\n\t\t{\n\t\t\tif (storage) storage->Release();\n\t\t\tif (webObject) webObject->Release();\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::setSize(const Size& size)\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tbrowser->put_Width(size.width);\n\t\t\tbrowser->put_Height(size.height);\n\n\t\t\tbrowser->Release();\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::navigate(const String& url)\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tVARIANT vurl, vempty;\n\n\t\t\tvempty.vt = VT_EMPTY;\n\t\t\tvurl.vt = VT_BSTR;\n\t\t\tvurl.bstrVal = ::SysAllocString(url.toArray());\n\n\t\t\tbrowser->Navigate2(&vurl, &vempty, &vempty, &vempty, &vempty);\n\t\t\t\n\t\t\tbrowser->Release();\n\t\t\t::SysFreeString(vurl.bstrVal);\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::goBack()\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tbrowser->GoBack();\n\n\t\t\tbrowser->Release();\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::goForward()\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tbrowser->GoForward();\n\n\t\t\tbrowser->Release();\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::QueryInterface(REFIID riid, void** ppvObject)\n\t\t{\n\t\t\tif (riid == IID_IUnknown || riid == IID_IOleClientSite)\n\t\t\t{\n\t\t\t\t*ppvObject = (IOleClientSite*) this;\n\t\t\t}\n\t\t\telse if (riid == IID_IOleInPlaceSite)\n\t\t\t{\n\t\t\t\t*ppvObject = (IOleInPlaceSite*) this;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*ppvObject = NULL;\n\t\t\t\treturn E_NOINTERFACE;\n\t\t\t}\n\n\t\t\tAddRef();\n\t\t\treturn S_OK;\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::GetWindow(HWND* phwnd)\n\t\t{\n\t\t\t*phwnd = hwnd; \n\t\t\treturn S_OK;\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)\n\t\t{\n\t\t\t*ppFrame = NULL;\n\t\t\t*ppDoc = NULL;\n\t\t\t*lprcPosRect = { 0 };\n\t\t\t*lprcClipRect = *lprcPosRect;\n\n\t\t\tlpFrameInfo->fMDIApp = FALSE;\n\t\t\tlpFrameInfo->hwndFrame = hwnd;\n\t\t\tlpFrameInfo->cAccelEntries = 0;\n\n\t\t\treturn S_OK;\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::OnPosRectChange(LPCRECT lprcPosRect)\n\t\t{\n\t\t\tIOleInPlaceObject* place = nullptr;\n\n\t\t\twebObject->QueryInterface(IID_IOleInPlaceObject, (void**) &place);\n\n\t\t\tplace->SetObjectRects(lprcPosRect, lprcPosRect);\n\n\t\t\tplace->Release();\n\n\t\t\treturn S_OK;\n\t\t}\n\t}\n}\n\nOops. Compile fix.\/\/ System Dependencies\n#include \n#include \n\n\/\/ External Dependencies\n#include \"..\/..\/core\/include\/spinlock.h\"\n#include \"..\/..\/core\/include\/system.h\"\n\n\/\/ Module Dependencies\n#include \"componentadapterproperties.h\"\n#include \"..\/include\/componentadapter.h\"\n#include \"..\/include\/webview.h\"\n\nnamespace native\n{\n\tnamespace ui\n\t{\n\t\tclass Win32WebViewAdapter : public WebViewAdapter, public IOleClientSite, public IOleInPlaceSite\n\t\t{\n\t\tpublic:\n\t\t\t\/\/ Constructor\n\t\t\tWin32WebViewAdapter(WebView* view);\n\t\t\t~Win32WebViewAdapter();\n\n\t\t\t\/\/ Helper Functions\n\t\t\tvoid setSize(const Size& size);\n\t\t\tvirtual void navigate(const String& url) override;\n\t\t\tvirtual void goBack() override;\n\t\t\tvirtual void goForward() override;\n\n\t\t\t\/\/ IUnknown Functions\n\t\t\tvirtual HRESULT QueryInterface(REFIID riid, void** ppvObject) override;\n\t\t\tvirtual ULONG AddRef() override { return 1; }\t\/\/ Unneeded\n\t\t\tvirtual ULONG Release() override { return 1; }\t\/\/ Unneeded\n\n\t\t\t\/\/ IOleClientSite Functions\n\t\t\tvirtual HRESULT SaveObject() override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk) override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT GetContainer(IOleContainer** ppContainer) override { return E_NOINTERFACE; }\n\t\t\tvirtual HRESULT ShowObject() override { return S_OK; }\n\t\t\tvirtual HRESULT OnShowWindow(BOOL fShow) override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT RequestNewObjectLayout() override { return E_NOTIMPL; }\n\n\t\t\t\/\/ IOleWindow Functions\n\t\t\tvirtual HRESULT GetWindow(HWND* phwnd) override;\n\t\t\tvirtual HRESULT ContextSensitiveHelp(BOOL fEnterMode) override { return E_NOTIMPL; }\n\n\t\t\t\/\/ IOleInPlaceSite Functions\n\t\t\tvirtual HRESULT CanInPlaceActivate() override { return S_OK; }\n\t\t\tvirtual HRESULT OnInPlaceActivate() override { return S_OK; }\n\t\t\tvirtual HRESULT OnUIActivate() override { return S_OK; }\n\t\t\tvirtual HRESULT GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo) override;\n\t\t\tvirtual HRESULT Scroll(SIZE scrollExtant) override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT OnUIDeactivate(BOOL fUndoable) override { return S_OK; }\n\t\t\tvirtual HRESULT OnInPlaceDeactivate() override { return S_OK; }\n\t\t\tvirtual HRESULT DiscardUndoState() override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT DeactivateAndUndo() override { return E_NOTIMPL; }\n\t\t\tvirtual HRESULT OnPosRectChange(LPCRECT lprcPosRect) override;\n\n\t\t\t\/\/ Instance Variables\n\t\t\tIStorage* storage;\n\t\t\tIOleObject* webObject;\n\t\t\tHWND hwnd;\n\t\t};\n\n\t\t\/*\n\t\t\tWebView Functions\n\t\t *\/\n\n\t\tWebView::WebView() : Component(new Win32WebViewAdapter(this))\n\t\t{\n\t\t\tsetAlignment(Align::Fill);\n\t\t}\n\n\t\tvoid WebView::navigate(const String& url)\n\t\t{\n\t\t\t((WebViewAdapter*) getAdapter())->navigate(url);\n\t\t}\n\n\t\tvoid WebView::goBack()\n\t\t{\n\t\t\t((WebViewAdapter*) getAdapter())->goBack();\n\t\t}\n\n\t\tvoid WebView::goForward()\n\t\t{\n\t\t\t((WebViewAdapter*) getAdapter())->goForward();\n\t\t}\n\n\t\tvoid WebView::onSize(const Size& size)\n\t\t{\n\t\t\t((Win32WebViewAdapter*) getAdapter())->setSize(size);\n\t\t}\n\n\t\t\/*\n\t\t\tWebViewAdapter Functions\n\t\t*\/\n\n\t\tWebViewAdapter::WebViewAdapter(WebView* view) : ComponentAdapter({ view, nullptr, WS_CHILD | WS_VISIBLE, 0 })\n\t\t{\n\t\t}\n\n\t\tWebViewAdapter::~WebViewAdapter()\n\t\t{\n\t\t}\n\n\t\tvoid WebViewAdapter::navigate(const String& url)\n\t\t{\n\t\t\t\/\/ Always overridden.\n\t\t\tthrow NotSupportedException();\n\t\t}\n\n\t\tvoid WebViewAdapter::goBack()\n\t\t{\n\t\t\t\/\/ Always overridden.\n\t\t\tthrow NotSupportedException();\n\t\t}\n\n\t\tvoid WebViewAdapter::goForward()\n\t\t{\n\t\t\t\/\/ Always overridden.\n\t\t\tthrow NotSupportedException();\n\t\t}\n\n\t\t\/*\n\t\t\tBrowserData Functions\n\t\t*\/\n\n\t\tWin32WebViewAdapter::Win32WebViewAdapter(WebView* view) : WebViewAdapter(view), hwnd(HWND(getHandle()))\n\t\t{\n\t\t\tstatic bool isOleInitialized = false;\n\t\t\tstatic SpinLock lock;\n\n\t\t\tlock.lock();\n\n\t\t\tif (!isOleInitialized)\n\t\t\t{\n\t\t\t\t\/\/ Initialise the ActiveX environment.\n\t\t\t\tisOleInitialized = true;\n\t\t\t\t::OleInitialize(NULL);\n\t\t\t\tSystem::onExit([]() { ::OleUninitialize(); });\n\t\t\t\t\n\t\t\t\t\/\/ Get the current process name.\n\t\t\t\t\/\/ TODO: Make this a function elsewhere.\n\t\t\t\tWCHAR buffer[MAX_PATH + 1];\n\t\t\t\t::GetModuleFileName(NULL, buffer, sizeof(buffer));\n\t\t\t\tString fileName = buffer;\n\t\t\t\tfileName = fileName.substring(fileName.lastIndexOf(L\"\\\\\") + 1, fileName.getLength());\n\n\t\t\t\t\/\/ Ensure we're using a decent browser version.\n\t\t\t\tHKEY browserEmulationKey;\n\t\t\t\tDWORD ieVersion = 11000;\t\/\/ IE11 pretty please.\n\t\t\t\t::RegOpenKeyEx(HKEY_CURRENT_USER, L\"SOFTWARE\\\\Microsoft\\\\Internet Explorer\\\\Main\\\\FeatureControl\\\\FEATURE_BROWSER_EMULATION\", 0, KEY_WRITE, &browserEmulationKey);\n\t\t\t\t::RegSetValueEx(browserEmulationKey, fileName.toArray(), 0, REG_DWORD, (BYTE*) &ieVersion, sizeof(ieVersion));\n\t\t\t\t::RegCloseKey(browserEmulationKey);\n\t\t\t}\n\n\t\t\tlock.release();\n\n\t\t\t\/\/ Create the ActiveX container.\n\t\t\tif (FAILED(::StgCreateStorageEx(NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_DIRECT | STGM_CREATE | STGM_DELETEONRELEASE, STGFMT_STORAGE, 0, NULL, NULL, IID_IStorage, (void**)&storage)))\n\t\t\t\tthrow UserInterfaceException(\"Failed to create ActiveX browser component.\");\n\n\t\t\tif (FAILED(::OleCreate(CLSID_WebBrowser, IID_IOleObject, OLERENDER_DRAW, NULL, this, storage, (LPVOID*) &webObject)))\n\t\t\t\tthrow UserInterfaceException(\"Failed to create ActiveX browser component.\");\n\n\t\t\t\/\/ Embed the ActiveX container in our Component.\n\t\t\tRECT rect = { 0 };\n\t\t\t::OleSetContainedObject(webObject, TRUE);\n\t\t\twebObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, -1, hwnd, &rect);\n\t\t}\n\n\t\tWin32WebViewAdapter::~Win32WebViewAdapter()\n\t\t{\n\t\t\tif (storage) storage->Release();\n\t\t\tif (webObject) webObject->Release();\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::setSize(const Size& size)\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tbrowser->put_Width(size.width);\n\t\t\tbrowser->put_Height(size.height);\n\n\t\t\tbrowser->Release();\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::navigate(const String& url)\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tVARIANT vurl, vempty;\n\n\t\t\tvempty.vt = VT_EMPTY;\n\t\t\tvurl.vt = VT_BSTR;\n\t\t\tvurl.bstrVal = ::SysAllocString(url.toArray());\n\n\t\t\tbrowser->Navigate2(&vurl, &vempty, &vempty, &vempty, &vempty);\n\t\t\t\n\t\t\tbrowser->Release();\n\t\t\t::SysFreeString(vurl.bstrVal);\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::goBack()\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tbrowser->GoBack();\n\n\t\t\tbrowser->Release();\n\t\t}\n\n\t\tvoid Win32WebViewAdapter::goForward()\n\t\t{\n\t\t\tIWebBrowser2* browser = nullptr;\n\t\t\twebObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);\n\n\t\t\tbrowser->GoForward();\n\n\t\t\tbrowser->Release();\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::QueryInterface(REFIID riid, void** ppvObject)\n\t\t{\n\t\t\tif (riid == IID_IUnknown || riid == IID_IOleClientSite)\n\t\t\t{\n\t\t\t\t*ppvObject = (IOleClientSite*) this;\n\t\t\t}\n\t\t\telse if (riid == IID_IOleInPlaceSite)\n\t\t\t{\n\t\t\t\t*ppvObject = (IOleInPlaceSite*) this;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*ppvObject = NULL;\n\t\t\t\treturn E_NOINTERFACE;\n\t\t\t}\n\n\t\t\tAddRef();\n\t\t\treturn S_OK;\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::GetWindow(HWND* phwnd)\n\t\t{\n\t\t\t*phwnd = hwnd; \n\t\t\treturn S_OK;\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)\n\t\t{\n\t\t\t*ppFrame = NULL;\n\t\t\t*ppDoc = NULL;\n\t\t\t*lprcPosRect = { 0 };\n\t\t\t*lprcClipRect = *lprcPosRect;\n\n\t\t\tlpFrameInfo->fMDIApp = FALSE;\n\t\t\tlpFrameInfo->hwndFrame = hwnd;\n\t\t\tlpFrameInfo->cAccelEntries = 0;\n\n\t\t\treturn S_OK;\n\t\t}\n\n\t\tHRESULT Win32WebViewAdapter::OnPosRectChange(LPCRECT lprcPosRect)\n\t\t{\n\t\t\tIOleInPlaceObject* place = nullptr;\n\n\t\t\twebObject->QueryInterface(IID_IOleInPlaceObject, (void**) &place);\n\n\t\t\tplace->SetObjectRects(lprcPosRect, lprcPosRect);\n\n\t\t\tplace->Release();\n\n\t\t\treturn S_OK;\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"#include \"..\/unicode\/utfconv.h\"\n\n#include \n\n#include \"cppunit-header.h\"\n\nconst char * string_utf8\n = u8\"a\\u5916\\u56FD\\u8A9E\\u306E\\u5B66\\u7FD2\\u3068\\u6559\\u6388\"\n \"\\U0010FF00 \\U00011111 \\U0010FFFF\";\n\nconst char16_t * string_utf16\n = u\"a\\u5916\\u56FD\\u8A9E\\u306E\\u5B66\\u7FD2\\u3068\\u6559\\u6388\"\n \"\\U0010FF00 \\U00011111 \\U0010FFFF\";\n\nconst char32_t * string_utf32\n = U\"a\\u5916\\u56FD\\u8A9E\\u306E\\u5B66\\u7FD2\\u3068\\u6559\\u6388\"\n \"\\U0010FF00 \\U00011111 \\U0010FFFF\";\n\nclass Test_Unicode : public CppUnit::TestFixture\n{\n\tCPPUNIT_TEST_SUITE(Test_Unicode);\n\tCPPUNIT_TEST(testStuff);\n\tCPPUNIT_TEST(testStuff);\n\tCPPUNIT_TEST(testStuff);\n\tCPPUNIT_TEST_SUITE_END();\n\n\ttypedef std::codecvt_base::result result;\n\n\ttemplate \n\tvoid testStuff()\n\t{\n#if 0\n\t\tstatic_assert(std::numeric_limits::max() >= limit,\n\t\t \"Upper limit for char values must be less \"\n\t\t \"than charater type max\");\n#endif\n\t\tCHAR_T wc[4];\n\t\tchar nc[8];\n\n\t\tconst CHAR_T * last_in = nullptr;\n\t\tchar * last_out = nullptr;\n\t\tcodecvt_utf8 cnv;\n\t\n\t\tfor (wc[0] = 0;\n\t\t static_cast(wc[0]) < (limit + 1); ++wc[0])\n\t\t{\n\t\t\tif (config::verbose && ((wc[0] & 0xFFFF) == 0))\n\t\t\t\tprintf(\"Processing plane 0x%08x\\n\", wc[0]);\n\n\t\t\tstd::mbstate_t mbs = std::mbstate_t();\n\t\t\tmemset(nc, 0, 8);\n\t\t\tresult r = cnv.out(mbs, wc, wc + 1, last_in, nc, nc + 8, last_out);\n\n\t\t\tCPPUNIT_ASSERT( r == std::codecvt_base::ok\n\t\t\t || (r == std::codecvt_base::noconv\n\t\t\t && std::is_same::value));\n\t\t\tCPPUNIT_ASSERT(mbs.__count == 0);\n\n\t\t\tconst char * last_in2 = nullptr;\n\t\t\tCHAR_T * last_out2 = nullptr;\n\t\t\tmemset(&mbs, 0, sizeof(mbs));\n\n\t\t\tr = cnv.in(mbs, nc, last_out, last_in2, wc + 1, wc + 2, last_out2);\n\n\t\t\tCPPUNIT_ASSERT( r == std::codecvt_base::ok\n\t\t\t || (r == std::codecvt_base::noconv\n\t\t\t && std::is_same::value));\n\n\t\t\tif (r != std::codecvt_base::noconv)\n\t\t\t\tCPPUNIT_ASSERT(wc[0] == wc[1]);\n\n\t\t\tCPPUNIT_ASSERT(mbs.__count == 0);\n\n\t\t\tif (wc[0] == std::numeric_limits::max())\n\t\t\t\tbreak;\n\t\t}\n\t}\n};\nCPPUNIT_TEST_SUITE_REGISTRATION(Test_Unicode);\nAdding tests for trivial functions#include \"..\/unicode\/utfconv.h\"\n\n#include \n\n#include \"cppunit-header.h\"\n\nconst char * string_utf8\n = u8\"a\\u5916\\u56FD\\u8A9E\\u306E\\u5B66\\u7FD2\\u3068\\u6559\\u6388\"\n \"\\U0010FF00 \\U00011111 \\U0010FFFF\";\n\nconst char16_t * string_utf16\n = u\"a\\u5916\\u56FD\\u8A9E\\u306E\\u5B66\\u7FD2\\u3068\\u6559\\u6388\"\n \"\\U0010FF00 \\U00011111 \\U0010FFFF\";\n\nconst char32_t * string_utf32\n = U\"a\\u5916\\u56FD\\u8A9E\\u306E\\u5B66\\u7FD2\\u3068\\u6559\\u6388\"\n \"\\U0010FF00 \\U00011111 \\U0010FFFF\";\n\nclass Test_Unicode : public CppUnit::TestFixture\n{\n\tCPPUNIT_TEST_SUITE(Test_Unicode);\n\tCPPUNIT_TEST(trivialTests);\n\tCPPUNIT_TEST(trivialTests);\n\tCPPUNIT_TEST(trivialTests);\n\n\tCPPUNIT_TEST(testStuff);\n\tCPPUNIT_TEST(testStuff);\n\tCPPUNIT_TEST(testStuff);\n\tCPPUNIT_TEST_SUITE_END();\n\n\ttypedef std::codecvt_base::result result;\n\n\ttemplate \n\tvoid trivialTests()\n\t{\n\t\tcodecvt_utf8 cnv;\n\t\tif (std::is_same::value)\n\t\t\tCPPUNIT_ASSERT(cnv.encoding() == 1);\n\t\telse\n\t\t\tCPPUNIT_ASSERT(cnv.encoding() == 0);\n\t}\n\n\ttemplate \n\tvoid testStuff()\n\t{\n\t\tCHAR_T wc[4];\n\t\tchar nc[8];\n\n\t\tconst CHAR_T * last_in = nullptr;\n\t\tchar * last_out = nullptr;\n\t\tcodecvt_utf8 cnv;\n\t\n\t\tfor (wc[0] = 0;\n\t\t static_cast(wc[0]) < (limit + 1); ++wc[0])\n\t\t{\n\t\t\tif (config::verbose && ((wc[0] & 0xFFFF) == 0))\n\t\t\t\tprintf(\"Processing plane 0x%08x\\n\", wc[0]);\n\n\t\t\tstd::mbstate_t mbs;\n\t\t\t\n\t\t\tmemset(&mbs, 0, sizeof(mbs));\n\t\t\tmemset(nc, 0, 8);\n\t\t\tresult r = cnv.out(mbs, wc, wc + 1, last_in, nc, nc + 8, last_out);\n\n\n\t\t\tCPPUNIT_ASSERT( r == std::codecvt_base::ok\n\t\t\t || (r == std::codecvt_base::noconv\n\t\t\t && std::is_same::value));\n\t\t\tCPPUNIT_ASSERT(mbs.__count == 0);\n\n\t\t\tconst char * last_in2 = nullptr;\n\t\t\tCHAR_T * last_out2 = nullptr;\n\t\t\tmemset(&mbs, 0, sizeof(mbs));\n\t\t\tint len = cnv.length(mbs, nc, last_out, 20);\n\n\t\t\tmemset(&mbs, 0, sizeof(mbs));\n\n\t\t\tr = cnv.in(mbs, nc, last_out, last_in2, wc + 1, wc + 2, last_out2);\n\n\t\t\tCPPUNIT_ASSERT(len == (last_in2 - nc));\n\n\t\t\tCPPUNIT_ASSERT( r == std::codecvt_base::ok\n\t\t\t || (r == std::codecvt_base::noconv\n\t\t\t && std::is_same::value));\n\n\t\t\tif (r != std::codecvt_base::noconv)\n\t\t\t\tCPPUNIT_ASSERT(wc[0] == wc[1]);\n\n\t\t\tCPPUNIT_ASSERT(mbs.__count == 0);\n\n\t\t\tif (wc[0] == std::numeric_limits::max())\n\t\t\t\tbreak;\n\t\t}\n\t}\n};\nCPPUNIT_TEST_SUITE_REGISTRATION(Test_Unicode);\n<|endoftext|>"} {"text":"\/*\n * Functions for working with relative URIs.\n *\n * author: Max Kellermann \n *\/\n\n#ifndef BENG_URI_RELATIVE_HXX\n#define BENG_URI_RELATIVE_HXX\n\nstruct StringView;\n\n\/**\n * Check if an (absolute) URI is relative to an a base URI (also\n * absolute), and return the relative part. Returns NULL if both URIs\n * do not match.\n *\/\nStringView\nuri_relative(StringView base, StringView uri);\n\n#endif\nuri\/relative: add \"pure\" attribute\/*\n * Functions for working with relative URIs.\n *\n * author: Max Kellermann \n *\/\n\n#ifndef BENG_URI_RELATIVE_HXX\n#define BENG_URI_RELATIVE_HXX\n\n#include \n\nstruct StringView;\n\n\/**\n * Check if an (absolute) URI is relative to an a base URI (also\n * absolute), and return the relative part. Returns NULL if both URIs\n * do not match.\n *\/\ngcc_pure\nStringView\nuri_relative(StringView base, StringView uri);\n\n#endif\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#ifdef _MSC_VER\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"otbImageIOFactory.h\"\n#include \"itkMutexLock.h\"\n#include \"itkMutexLockHolder.h\"\n\n#include \"otbONERAImageIOFactory.h\"\n#include \"otbMSTARImageIOFactory.h\"\n#include \"otbGDALImageIOFactory.h\"\n#include \"otbLUMImageIOFactory.h\"\n#include \"otbBSQImageIOFactory.h\"\n#ifndef OTB_JPEG2000_DISABLED\n#include \"otbJPEG2000ImageIOFactory.h\"\n#endif\n#ifdef OTB_USE_CURL\n#include \"otbTileMapImageIOFactory.h\"\n#endif\n\nnamespace otb\n{\n\n itk::ImageIOBase::Pointer\n ImageIOFactory::CreateImageIO(const char* path, FileModeType mode)\n {\n\n RegisterBuiltInFactories();\n return (Superclass::CreateImageIO(path,mode) );\n\n }\n \n void\n ImageIOFactory::RegisterBuiltInFactories()\n {\n static bool firstTime = true;\n\n static itk::SimpleMutexLock mutex;\n {\n \/\/ This helper class makes sure the Mutex is unlocked \n \/\/ in the event an exception is thrown.\n itk::MutexLockHolder mutexHolder( mutex );\n if( firstTime )\n {\n\t \/\/ BSQ format for OTB\n itk::ObjectFactoryBase::RegisterFactory( BSQImageIOFactory::New() );\t\t\t\n \n\t \/\/ LUM format for OTB\n itk::ObjectFactoryBase::RegisterFactory( LUMImageIOFactory::New() );\t\t\t\n \n#ifndef OTB_JPEG2000_DISABLED\n\t \/\/ JPEG2000 : New format for OTB\n itk::ObjectFactoryBase::RegisterFactory( JPEG2000ImageIOFactory::New() );\n#endif OTB_JPEG2000_DISABLED\n\t \n\t \/\/ GDAL : New format for OTB\n itk::ObjectFactoryBase::RegisterFactory( GDALImageIOFactory::New() ); \n \n\t \/\/ ONERA format for OTB\n itk::ObjectFactoryBase::RegisterFactory( ONERAImageIOFactory::New() );\t\t\t\n \n\t \/\/ MSTAR Format for OTB\n itk::ObjectFactoryBase::RegisterFactory( MSTARImageIOFactory::New() );\n \n#ifdef OTB_USE_CURL\n\t \/\/ TileMap : New format for OTB\n itk::ObjectFactoryBase::RegisterFactory( TileMapImageIOFactory::New() );\n#endif \n firstTime = false;\n }\n }\n\n }\n\n} \/\/ end namespace otb\nCorrection warning brescou\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#ifdef _MSC_VER\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"otbImageIOFactory.h\"\n#include \"itkMutexLock.h\"\n#include \"itkMutexLockHolder.h\"\n\n#include \"otbONERAImageIOFactory.h\"\n#include \"otbMSTARImageIOFactory.h\"\n#include \"otbGDALImageIOFactory.h\"\n#include \"otbLUMImageIOFactory.h\"\n#include \"otbBSQImageIOFactory.h\"\n#ifndef OTB_JPEG2000_DISABLED\n#include \"otbJPEG2000ImageIOFactory.h\"\n#endif\n#ifdef OTB_USE_CURL\n#include \"otbTileMapImageIOFactory.h\"\n#endif\n\nnamespace otb\n{\n\n itk::ImageIOBase::Pointer\n ImageIOFactory::CreateImageIO(const char* path, FileModeType mode)\n {\n\n RegisterBuiltInFactories();\n return (Superclass::CreateImageIO(path,mode) );\n\n }\n \n void\n ImageIOFactory::RegisterBuiltInFactories()\n {\n static bool firstTime = true;\n\n static itk::SimpleMutexLock mutex;\n {\n \/\/ This helper class makes sure the Mutex is unlocked \n \/\/ in the event an exception is thrown.\n itk::MutexLockHolder mutexHolder( mutex );\n if( firstTime )\n {\n\t \/\/ BSQ format for OTB\n itk::ObjectFactoryBase::RegisterFactory( BSQImageIOFactory::New() );\t\t\t\n \n\t \/\/ LUM format for OTB\n itk::ObjectFactoryBase::RegisterFactory( LUMImageIOFactory::New() );\t\t\t\n \n#ifndef OTB_JPEG2000_DISABLED\n\t \/\/ JPEG2000 : New format for OTB\n itk::ObjectFactoryBase::RegisterFactory( JPEG2000ImageIOFactory::New() );\n#endif\n\t \n\t \/\/ GDAL : New format for OTB\n itk::ObjectFactoryBase::RegisterFactory( GDALImageIOFactory::New() ); \n \n\t \/\/ ONERA format for OTB\n itk::ObjectFactoryBase::RegisterFactory( ONERAImageIOFactory::New() );\t\t\t\n \n\t \/\/ MSTAR Format for OTB\n itk::ObjectFactoryBase::RegisterFactory( MSTARImageIOFactory::New() );\n \n#ifdef OTB_USE_CURL\n\t \/\/ TileMap : New format for OTB\n itk::ObjectFactoryBase::RegisterFactory( TileMapImageIOFactory::New() );\n#endif \n firstTime = false;\n }\n }\n\n }\n\n} \/\/ end namespace otb\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ rpc_client_test.cpp\n\/\/\n\/\/ Identification: test\/networking\/rpc_client_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"common\/harness.h\"\n\n#include \"networking\/tcp_address.h\"\n#include \"networking\/rpc_type.h\"\n#include \"networking\/rpc_client.h\"\n#include \"networking\/rpc_server.h\"\n#include \"networking\/tcp_connection.h\"\n#include \"networking\/peloton_service.h\"\n#include \"networking\/abstract_service.pb.h\"\n\n#include \n\nnamespace peloton {\nnamespace test {\n\nclass RpcClientTests : public PelotonTest {};\n\n\/*\nTEST_F(RpcClientTests, BasicTest) {\n networking::RpcServer rpc_server(PELOTON_SERVER_PORT);\n networking::PelotonService service;\n rpc_server.RegisterService(&service);\n\n \/\/ Heartbeat is 13 for index\n const google::protobuf::MethodDescriptor* method_des =\n service.descriptor()->method(13);\n\n std::string methodname = std::string(method_des->full_name());\n\n \/\/\/\/\/\/\/\/\/\/\/Generate data\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n std::hash string_hash_fn;\n\n \/\/ we use unit64_t because we should specify the exact length\n uint64_t opcode = string_hash_fn(methodname);\n\n networking::HeartbeatRequest request;\n\n request.set_sender_site(12);\n request.set_last_transaction_id(34);\n\n \/\/ set the type\n uint16_t type = networking::MSG_TYPE_REQ;\n\n \/\/ prepare the sending buf\n uint32_t msg_len = request.ByteSize() + sizeof(type) + sizeof(opcode);\n\n \/\/ total length of the message: header length (4bytes) + message length\n \/\/ (8bytes + ...)\n PL_ASSERT(HEADERLEN == sizeof(msg_len));\n char buf[sizeof(msg_len) + msg_len];\n\n \/\/ copy the header into the buf\n PL_MEMCPY(buf, &msg_len, sizeof(msg_len));\n\n \/\/ copy the type into the buf\n PL_MEMCPY(buf + sizeof(msg_len), &type, sizeof(type));\n\n \/\/ copy the hashcode into the buf, following the header\n PL_ASSERT(OPCODELEN == sizeof(opcode));\n PL_MEMCPY(buf + sizeof(msg_len) + sizeof(type), &opcode, sizeof(opcode));\n\n \/\/ call protobuf to serialize the request message into sending buf\n request.SerializeToArray(\n buf + sizeof(msg_len) + sizeof(type) + sizeof(opcode),\n request.ByteSize());\n\n std::string methodname2 = rpc_server.FindMethod(opcode)->method_->full_name();\n bool comp = (methodname == methodname2);\n EXPECT_EQ(comp, true);\n}\n*\/\n}\n}\nFixed rpc client test\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ rpc_client_test.cpp\n\/\/\n\/\/ Identification: test\/networking\/rpc_client_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"common\/harness.h\"\n\n#include \"networking\/tcp_address.h\"\n#include \"networking\/rpc_type.h\"\n#include \"networking\/rpc_client.h\"\n#include \"networking\/rpc_server.h\"\n#include \"networking\/tcp_connection.h\"\n#include \"networking\/peloton_service.h\"\n#include \"peloton\/proto\/abstract_service.pb.h\"\n\n#include \n\nnamespace peloton {\nnamespace test {\n\nclass RpcClientTests : public PelotonTest {};\n\n\/*\nTEST_F(RpcClientTests, BasicTest) {\n networking::RpcServer rpc_server(PELOTON_SERVER_PORT);\n networking::PelotonService service;\n rpc_server.RegisterService(&service);\n\n \/\/ Heartbeat is 13 for index\n const google::protobuf::MethodDescriptor* method_des =\n service.descriptor()->method(13);\n\n std::string methodname = std::string(method_des->full_name());\n\n \/\/\/\/\/\/\/\/\/\/\/Generate data\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n std::hash string_hash_fn;\n\n \/\/ we use unit64_t because we should specify the exact length\n uint64_t opcode = string_hash_fn(methodname);\n\n networking::HeartbeatRequest request;\n\n request.set_sender_site(12);\n request.set_last_transaction_id(34);\n\n \/\/ set the type\n uint16_t type = networking::MSG_TYPE_REQ;\n\n \/\/ prepare the sending buf\n uint32_t msg_len = request.ByteSize() + sizeof(type) + sizeof(opcode);\n\n \/\/ total length of the message: header length (4bytes) + message length\n \/\/ (8bytes + ...)\n PL_ASSERT(HEADERLEN == sizeof(msg_len));\n char buf[sizeof(msg_len) + msg_len];\n\n \/\/ copy the header into the buf\n PL_MEMCPY(buf, &msg_len, sizeof(msg_len));\n\n \/\/ copy the type into the buf\n PL_MEMCPY(buf + sizeof(msg_len), &type, sizeof(type));\n\n \/\/ copy the hashcode into the buf, following the header\n PL_ASSERT(OPCODELEN == sizeof(opcode));\n PL_MEMCPY(buf + sizeof(msg_len) + sizeof(type), &opcode, sizeof(opcode));\n\n \/\/ call protobuf to serialize the request message into sending buf\n request.SerializeToArray(\n buf + sizeof(msg_len) + sizeof(type) + sizeof(opcode),\n request.ByteSize());\n\n std::string methodname2 = rpc_server.FindMethod(opcode)->method_->full_name();\n bool comp = (methodname == methodname2);\n EXPECT_EQ(comp, true);\n}\n*\/\n}\n}\n<|endoftext|>"} {"text":"#include \"LLVM_Headers.h\"\n#include \"LLVM_Output.h\"\n#include \"CodeGen_LLVM.h\"\n#include \"CodeGen_C.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace Halide {\n\nllvm::raw_fd_ostream *new_raw_fd_ostream(const std::string &filename) {\n std::string error_string;\n #if LLVM_VERSION < 35\n llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string);\n #elif LLVM_VERSION == 35\n llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string, llvm::sys::fs::F_None);\n #else \/\/ llvm 3.6\n std::error_code err;\n llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), err, llvm::sys::fs::F_None);\n if (err) error_string = err.message();\n #endif\n internal_assert(error_string.empty())\n << \"Error opening output \" << filename << \": \" << error_string << \"\\n\";\n\n return raw_out;\n}\n\nnamespace Internal {\n\nbool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {\n #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)\n llvm::ConstantInt *c = llvm::cast(value);\n #else\n llvm::ConstantAsMetadata *cam = llvm::cast(value);\n llvm::ConstantInt *c = llvm::cast(cam->getValue());\n #endif\n if (c) {\n result = !c->isZero();\n return true;\n }\n return false;\n}\n\nbool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {\n #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)\n if (llvm::dyn_cast(value)) {\n result = \"\";\n return true;\n }\n llvm::ConstantDataArray *c = llvm::cast(value);\n if (c) {\n result = c->getAsCString();\n return true;\n }\n #else\n llvm::MDString *c = llvm::dyn_cast(value);\n if (c) {\n result = c->getString();\n return true;\n }\n #endif\n return false;\n}\n\n}\n\nvoid get_target_options(const llvm::Module *module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {\n bool use_soft_float_abi = false;\n Internal::get_md_bool(module->getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi);\n Internal::get_md_string(module->getModuleFlag(\"halide_mcpu\"), mcpu);\n Internal::get_md_string(module->getModuleFlag(\"halide_mattrs\"), mattrs);\n\n options = llvm::TargetOptions();\n options.LessPreciseFPMADOption = true;\n options.NoFramePointerElim = false;\n options.AllowFPOpFusion = llvm::FPOpFusion::Fast;\n options.UnsafeFPMath = true;\n options.NoInfsFPMath = true;\n options.NoNaNsFPMath = true;\n options.HonorSignDependentRoundingFPMathOption = false;\n options.UseSoftFloat = false;\n options.NoZerosInBSS = false;\n options.GuaranteedTailCallOpt = false;\n options.DisableTailCalls = false;\n options.StackAlignmentOverride = 0;\n options.TrapFuncName = \"\";\n options.PositionIndependentExecutable = true;\n options.FunctionSections = true;\n #ifdef WITH_NATIVE_CLIENT\n options.UseInitArray = true;\n #else\n options.UseInitArray = false;\n #endif\n options.FloatABIType =\n use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;\n}\n\n\nvoid clone_target_options(const llvm::Module *from, llvm::Module *to) {\n to->setTargetTriple(from->getTargetTriple());\n\n llvm::LLVMContext &context = to->getContext();\n\n bool use_soft_float_abi = false;\n if (Internal::get_md_bool(from->getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi))\n to->addModuleFlag(llvm::Module::Warning, \"halide_use_soft_float_abi\", use_soft_float_abi ? 1 : 0);\n\n std::string mcpu;\n if (Internal::get_md_string(from->getModuleFlag(\"halide_mcpu\"), mcpu)) {\n #if LLVM_VERSION < 36\n to->addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::ConstantDataArray::getString(context, mcpu));\n #else\n to->addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::MDString::get(context, mcpu));\n #endif\n }\n\n std::string mattrs;\n if (Internal::get_md_string(from->getModuleFlag(\"halide_mattrs\"), mattrs)) {\n #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)\n to->addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::ConstantDataArray::getString(context, mattrs));\n #else\n to->addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::MDString::get(context, mattrs));\n #endif\n }\n}\n\n\nllvm::TargetMachine *get_target_machine(const llvm::Module *module) {\n string error_string;\n\n const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module->getTargetTriple(), error_string);\n if (!target) {\n cout << error_string << endl;\n llvm::TargetRegistry::printRegisteredTargetsForVersion();\n }\n internal_assert(target) << \"Could not create target\\n\";\n\n llvm::TargetOptions options;\n std::string mcpu = \"\";\n std::string mattrs = \"\";\n get_target_options(module, options, mcpu, mattrs);\n\n return target->createTargetMachine(module->getTargetTriple(),\n mcpu, mattrs,\n options,\n llvm::Reloc::PIC_,\n llvm::CodeModel::Default,\n llvm::CodeGenOpt::Aggressive);\n}\n\nvoid emit_file(llvm::Module *module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {\n Internal::debug(1) << \"Compiling to native code...\\n\";\n Internal::debug(2) << \"Target triple: \" << module->getTargetTriple() << \"\\n\";\n\n \/\/ Get the target specific parser.\n llvm::TargetMachine *target_machine = get_target_machine(module);\n internal_assert(target_machine) << \"Could not allocate target machine!\\n\";\n\n \/\/ Build up all of the passes that we want to do to the module.\n #if LLVM_VERSION < 37\n llvm::PassManager pass_manager;\n #else\n llvm::legacy::PassManager pass_manager;\n #endif\n\n #if LLVM_VERSION < 37\n \/\/ Add an appropriate TargetLibraryInfo pass for the module's triple.\n pass_manager.add(new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple())));\n #else\n pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module->getTargetTriple())));\n #endif\n\n #if LLVM_VERSION < 33\n pass_manager.add(new llvm::TargetTransformInfo(target_machine->getScalarTargetTransformInfo(),\n target_machine->getVectorTargetTransformInfo()));\n #elif LLVM_VERSION < 37\n target_machine->addAnalysisPasses(pass_manager);\n #endif\n\n #if LLVM_VERSION < 35\n llvm::DataLayout *layout = new llvm::DataLayout(module);\n Internal::debug(2) << \"Data layout: \" << layout->getStringRepresentation();\n pass_manager.add(layout);\n #endif\n\n \/\/ Make sure things marked as always-inline get inlined\n pass_manager.add(llvm::createAlwaysInlinerPass());\n\n \/\/ Override default to generate verbose assembly.\n #if LLVM_VERSION < 37\n target_machine->setAsmVerbosityDefault(true);\n #else\n target_machine->Options.MCOptions.AsmVerbose = true;\n #endif\n\n llvm::raw_fd_ostream *raw_out = new_raw_fd_ostream(filename);\n llvm::formatted_raw_ostream *out = new llvm::formatted_raw_ostream(*raw_out);\n\n \/\/ Ask the target to add backend passes as necessary.\n target_machine->addPassesToEmitFile(pass_manager, *out, file_type);\n\n pass_manager.run(*module);\n\n delete out;\n delete raw_out;\n\n delete target_machine;\n}\n\nllvm::Module *compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {\n return codegen_llvm(module, context);\n}\n\nvoid compile_llvm_module_to_object(llvm::Module *module, const std::string &filename) {\n emit_file(module, filename, llvm::TargetMachine::CGFT_ObjectFile);\n}\n\nvoid compile_llvm_module_to_assembly(llvm::Module *module, const std::string &filename) {\n emit_file(module, filename, llvm::TargetMachine::CGFT_AssemblyFile);\n}\n\nvoid compile_llvm_module_to_native(llvm::Module *module,\n const std::string &object_filename,\n const std::string &assembly_filename) {\n emit_file(module, object_filename, llvm::TargetMachine::CGFT_ObjectFile);\n emit_file(module, assembly_filename, llvm::TargetMachine::CGFT_AssemblyFile);\n}\n\nvoid compile_llvm_module_to_llvm_bitcode(llvm::Module *module, const std::string &filename) {\n llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);\n WriteBitcodeToFile(module, *file);\n delete file;\n}\n\nvoid compile_llvm_module_to_llvm_assembly(llvm::Module *module, const std::string &filename) {\n llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);\n module->print(*file, NULL);\n delete file;\n}\n\n} \/\/ namespace Halide\nFixes for NaCl.#include \"LLVM_Headers.h\"\n#include \"LLVM_Output.h\"\n#include \"CodeGen_LLVM.h\"\n#include \"CodeGen_C.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace Halide {\n\nllvm::raw_fd_ostream *new_raw_fd_ostream(const std::string &filename) {\n std::string error_string;\n #if LLVM_VERSION < 35\n llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string);\n #elif LLVM_VERSION == 35\n llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string, llvm::sys::fs::F_None);\n #else \/\/ llvm 3.6\n std::error_code err;\n llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), err, llvm::sys::fs::F_None);\n if (err) error_string = err.message();\n #endif\n internal_assert(error_string.empty())\n << \"Error opening output \" << filename << \": \" << error_string << \"\\n\";\n\n return raw_out;\n}\n\nnamespace Internal {\n\nbool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {\n #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)\n llvm::ConstantInt *c = llvm::cast(value);\n #else\n llvm::ConstantAsMetadata *cam = llvm::cast(value);\n llvm::ConstantInt *c = llvm::cast(cam->getValue());\n #endif\n if (c) {\n result = !c->isZero();\n return true;\n }\n return false;\n}\n\nbool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {\n #if LLVM_VERSION < 36\n if (llvm::dyn_cast(value)) {\n result = \"\";\n return true;\n }\n llvm::ConstantDataArray *c = llvm::cast(value);\n if (c) {\n result = c->getAsCString();\n return true;\n }\n #else\n llvm::MDString *c = llvm::dyn_cast(value);\n if (c) {\n result = c->getString();\n return true;\n }\n #endif\n return false;\n}\n\n}\n\nvoid get_target_options(const llvm::Module *module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {\n bool use_soft_float_abi = false;\n Internal::get_md_bool(module->getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi);\n Internal::get_md_string(module->getModuleFlag(\"halide_mcpu\"), mcpu);\n Internal::get_md_string(module->getModuleFlag(\"halide_mattrs\"), mattrs);\n\n options = llvm::TargetOptions();\n options.LessPreciseFPMADOption = true;\n options.NoFramePointerElim = false;\n options.AllowFPOpFusion = llvm::FPOpFusion::Fast;\n options.UnsafeFPMath = true;\n options.NoInfsFPMath = true;\n options.NoNaNsFPMath = true;\n options.HonorSignDependentRoundingFPMathOption = false;\n options.UseSoftFloat = false;\n options.NoZerosInBSS = false;\n options.GuaranteedTailCallOpt = false;\n options.DisableTailCalls = false;\n options.StackAlignmentOverride = 0;\n options.TrapFuncName = \"\";\n options.PositionIndependentExecutable = true;\n options.FunctionSections = true;\n #ifdef WITH_NATIVE_CLIENT\n options.UseInitArray = true;\n #else\n options.UseInitArray = false;\n #endif\n options.FloatABIType =\n use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;\n}\n\n\nvoid clone_target_options(const llvm::Module *from, llvm::Module *to) {\n to->setTargetTriple(from->getTargetTriple());\n\n llvm::LLVMContext &context = to->getContext();\n\n bool use_soft_float_abi = false;\n if (Internal::get_md_bool(from->getModuleFlag(\"halide_use_soft_float_abi\"), use_soft_float_abi))\n to->addModuleFlag(llvm::Module::Warning, \"halide_use_soft_float_abi\", use_soft_float_abi ? 1 : 0);\n\n std::string mcpu;\n if (Internal::get_md_string(from->getModuleFlag(\"halide_mcpu\"), mcpu)) {\n #if LLVM_VERSION < 36\n to->addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::ConstantDataArray::getString(context, mcpu));\n #else\n to->addModuleFlag(llvm::Module::Warning, \"halide_mcpu\", llvm::MDString::get(context, mcpu));\n #endif\n }\n\n std::string mattrs;\n if (Internal::get_md_string(from->getModuleFlag(\"halide_mattrs\"), mattrs)) {\n #if LLVM_VERSION < 36\n to->addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::ConstantDataArray::getString(context, mattrs));\n #else\n to->addModuleFlag(llvm::Module::Warning, \"halide_mattrs\", llvm::MDString::get(context, mattrs));\n #endif\n }\n}\n\n\nllvm::TargetMachine *get_target_machine(const llvm::Module *module) {\n string error_string;\n\n const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module->getTargetTriple(), error_string);\n if (!target) {\n cout << error_string << endl;\n llvm::TargetRegistry::printRegisteredTargetsForVersion();\n }\n internal_assert(target) << \"Could not create target\\n\";\n\n llvm::TargetOptions options;\n std::string mcpu = \"\";\n std::string mattrs = \"\";\n get_target_options(module, options, mcpu, mattrs);\n\n return target->createTargetMachine(module->getTargetTriple(),\n mcpu, mattrs,\n options,\n llvm::Reloc::PIC_,\n llvm::CodeModel::Default,\n llvm::CodeGenOpt::Aggressive);\n}\n\nvoid emit_file(llvm::Module *module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {\n Internal::debug(1) << \"Compiling to native code...\\n\";\n Internal::debug(2) << \"Target triple: \" << module->getTargetTriple() << \"\\n\";\n\n \/\/ Get the target specific parser.\n llvm::TargetMachine *target_machine = get_target_machine(module);\n internal_assert(target_machine) << \"Could not allocate target machine!\\n\";\n\n \/\/ Build up all of the passes that we want to do to the module.\n #if LLVM_VERSION < 37\n llvm::PassManager pass_manager;\n #else\n llvm::legacy::PassManager pass_manager;\n #endif\n\n #if LLVM_VERSION < 37\n \/\/ Add an appropriate TargetLibraryInfo pass for the module's triple.\n pass_manager.add(new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple())));\n #else\n pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module->getTargetTriple())));\n #endif\n\n #if LLVM_VERSION < 33\n pass_manager.add(new llvm::TargetTransformInfo(target_machine->getScalarTargetTransformInfo(),\n target_machine->getVectorTargetTransformInfo()));\n #elif LLVM_VERSION < 37\n target_machine->addAnalysisPasses(pass_manager);\n #endif\n\n #if LLVM_VERSION < 35\n llvm::DataLayout *layout = new llvm::DataLayout(module);\n Internal::debug(2) << \"Data layout: \" << layout->getStringRepresentation();\n pass_manager.add(layout);\n #endif\n\n \/\/ Make sure things marked as always-inline get inlined\n pass_manager.add(llvm::createAlwaysInlinerPass());\n\n \/\/ Override default to generate verbose assembly.\n #if LLVM_VERSION < 37\n target_machine->setAsmVerbosityDefault(true);\n #else\n target_machine->Options.MCOptions.AsmVerbose = true;\n #endif\n\n llvm::raw_fd_ostream *raw_out = new_raw_fd_ostream(filename);\n llvm::formatted_raw_ostream *out = new llvm::formatted_raw_ostream(*raw_out);\n\n \/\/ Ask the target to add backend passes as necessary.\n target_machine->addPassesToEmitFile(pass_manager, *out, file_type);\n\n pass_manager.run(*module);\n\n delete out;\n delete raw_out;\n\n delete target_machine;\n}\n\nllvm::Module *compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {\n return codegen_llvm(module, context);\n}\n\nvoid compile_llvm_module_to_object(llvm::Module *module, const std::string &filename) {\n emit_file(module, filename, llvm::TargetMachine::CGFT_ObjectFile);\n}\n\nvoid compile_llvm_module_to_assembly(llvm::Module *module, const std::string &filename) {\n emit_file(module, filename, llvm::TargetMachine::CGFT_AssemblyFile);\n}\n\nvoid compile_llvm_module_to_native(llvm::Module *module,\n const std::string &object_filename,\n const std::string &assembly_filename) {\n emit_file(module, object_filename, llvm::TargetMachine::CGFT_ObjectFile);\n emit_file(module, assembly_filename, llvm::TargetMachine::CGFT_AssemblyFile);\n}\n\nvoid compile_llvm_module_to_llvm_bitcode(llvm::Module *module, const std::string &filename) {\n llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);\n WriteBitcodeToFile(module, *file);\n delete file;\n}\n\nvoid compile_llvm_module_to_llvm_assembly(llvm::Module *module, const std::string &filename) {\n llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);\n module->print(*file, NULL);\n delete file;\n}\n\n} \/\/ namespace Halide\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexProgress.cxx\n ** Lexer for Progress 4GL.\n ** Based on LexCPP.cxx of Neil Hodgson \n **\/\n\/\/ Copyright 2006-2007 by Yuval Papish \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n\/** TODO:\nWebSpeed support in html lexer\nSupport \"end triggers\" expression of the triggers phrase\nchange lmPS to lmProgress\nSupport more than 6 comments levels\n**\/\n#include \n#include \n#include \n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic inline bool IsAWordChar(int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\nstatic inline bool IsAWordStart(int ch) {\n\treturn (ch < 0x80) && (isalpha(ch) || ch == '_');\n}\n\nenum SentenceStart { SetSentenceStart = 0xf, ResetSentenceStart = 0x10}; \/\/ true -> bit5 = 0\n\nstatic void Colourise4glDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],\n Accessor &styler) {\n\n WordList &keywords1 = *keywordlists[0]; \/\/ regular keywords\n WordList &keywords2 = *keywordlists[1]; \/\/ block opening keywords, only when SentenceStart\n WordList &keywords3 = *keywordlists[2]; \/\/ block opening keywords\n \/\/WordList &keywords4 = *keywordlists[3]; \/\/ preprocessor keywords. Not implemented\n \n\n\tint visibleChars = 0;\n\tint sentenceStartState; \/\/ true -> bit5 = 0\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward()) {\n\n\t\tif (sc.atLineStart) {\n\t\t\t\/\/ Reset states to begining of colourise so no surprises\n\t\t\t\/\/ if different sets of lines lexed.\n\t\t\tvisibleChars = 0;\n\t\t}\n\n\t\t\/\/ Handle line continuation generically.\n\t\tif (sc.ch == '~') {\n\t\t\tif (sc.chNext > ' ') {\n\t\t\t\t\/\/ skip special char after ~\n\t\t\t\tsc.Forward();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ Skip whitespace between ~ and EOL\n\t\t\t\twhile (sc.More() && (sc.chNext == ' ' || sc.chNext == '\\t') ) {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tif (sc.chNext == '\\n' || sc.chNext == '\\r') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t\tif (sc.ch == '\\r' && sc.chNext == '\\n') {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t}\n\t\t\t\t\tsc.Forward();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ Determine if a new state should be terminated.\n\t\tsentenceStartState = sc.state & 0x10;\n\t\tswitch (sc.state & 0xf) {\n\t\t\tcase SCE_4GL_OPERATOR:\n\t\t\t\tsc.SetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_NUMBER:\n\t\t\t\tif (!(IsADigit(sc.ch))) {\n\t\t\t\t\tsc.SetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_IDENTIFIER:\n\t\t\t\tif (!IsAWordChar(sc.ch) && sc.ch != '-') {\n\t\t\t\t\tchar s[1000];\n\t\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\t\tif ((sentenceStartState == 0) && keywords2.InList(s) || keywords3.InList(s)) { \n\t\t\t\t\t\tsc.ChangeState(SCE_4GL_BLOCK | ResetSentenceStart);\n\t\t\t\t\t}\n\t\t\t\t\telse if (keywords1.InList(s)) {\n\t\t\t\t\t\tif ((s[0] == 'e' && s[1] =='n' && s[2] == 'd' && !isalnum(s[3]) && s[3] != '-') ||\n\t\t\t\t\t\t\t(s[0] == 'f' && s[1] =='o' && s[2] == 'r' && s[3] == 'w' && s[4] =='a' && s[5] == 'r' && s[6] == 'd'&& !isalnum(s[7]))) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_4GL_END | ResetSentenceStart);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if\t((s[0] == 'e' && s[1] =='l' && s[2] == 's' && s[3] == 'e') ||\n\t\t\t\t\t\t\t\t (s[0] == 't' && s[1] =='h' && s[2] == 'e' && s[3] == 'n')) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_4GL_WORD & SetSentenceStart);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_4GL_WORD | ResetSentenceStart);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tsc.SetState(SCE_4GL_DEFAULT | (sc.state & 0x10));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_PREPROCESSOR:\n\t\t\t\tif (sc.atLineStart) {\n\t\t\t\t\tsc.SetState(SCE_4GL_DEFAULT & SetSentenceStart);\n\t\t\t\t} else if (sc.ch == '*' && sc.chNext == '\/') {\n\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_STRING:\n\t\t\t\tif (sc.ch == '\\\"') {\n\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_CHARACTER:\n\t\t\t\tif (sc.ch == '\\'') {\n\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif ((sc.state & 0xf) >= SCE_4GL_COMMENT1) {\n\t\t\t\t\tif (sc.ch == '*' && sc.chNext == '\/') {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t\tif ((sc.state & 0xf) == SCE_4GL_COMMENT1) {\n\t\t\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsc.SetState((sc.state & 0x1f) - 1);\n\t\t\t\t\t} else if (sc.ch == '\/' && sc.chNext == '*') {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t\tsc.SetState((sc.state & 0x1f) + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if a new state should be entered.\n\t\tsentenceStartState = sc.state & 0x10;\n\t\tif ((sc.state & 0xf) == SCE_4GL_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_4GL_NUMBER | ResetSentenceStart);\n\t\t\t} else if (IsAWordStart(sc.ch) || sc.ch == '@') {\n\t\t\t\tsc.SetState(SCE_4GL_IDENTIFIER | sentenceStartState);\n\t\t\t} else if (sc.ch == '\/' && sc.chNext == '*') {\n\t\t\t\tsc.SetState(SCE_4GL_COMMENT1 | sentenceStartState);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.SetState(SCE_4GL_STRING | ResetSentenceStart);\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tsc.SetState(SCE_4GL_CHARACTER | ResetSentenceStart);\n\t\t\t} else if (sc.ch == '&' && visibleChars == 0 && ((sc.state & 0x10) == 0)) {\n\t\t\t\tsc.SetState(SCE_4GL_PREPROCESSOR | ResetSentenceStart);\n\t\t\t\t\/\/ Skip whitespace between & and preprocessor word\n\t\t\t\tdo {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t} while ((sc.ch == ' ' || sc.ch == '\\t') && sc.More());\n\t\t\t\/\/ Handle syntactical line termination\n\t\t\t} else if ((sc.ch == '.' || sc.ch == ':' || sc.ch == '}') && (sc.chNext == ' ' || sc.chNext == '\\t' || sc.chNext == '\\n' || sc.chNext == '\\r')) {\n\t\t\t\tsc.SetState(sc.state & SetSentenceStart);\n\t\t\t} else if (isoperator(static_cast(sc.ch))) {\n\t\t\/* \tThis code allows highlight of handles. Alas, it would cause the frase \"last-event:function\"\n\t\t\tto be recognized as a BlockBegin\n\t\t\t\n\t\t\t\tif (sc.ch == ':')\n\t\t\t\t\tsc.SetState(SCE_4GL_OPERATOR & SetSentenceStart);\n\t\t\t\telse *\/\n\t\t\t\t\tsc.SetState(SCE_4GL_OPERATOR | ResetSentenceStart);\n\t\t\t}\n\t\t}\n\n\t\tif (!IsASpace(sc.ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic bool IsStreamCommentStyle(int style) {\n\treturn (style & 0xf) >= SCE_4GL_COMMENT1 ;\n}\n\n\/\/ Store both the current line's fold level and the next lines in the\n\/\/ level store to make it easy to pick up with each increment\n\/\/ and to make it possible to fiddle the current level for \"} else {\".\nstatic void FoldNoBox4glDoc(unsigned int startPos, int length, int initStyle,\n Accessor &styler) {\n\tbool foldComment = styler.GetPropertyInt(\"fold.comment\") != 0;\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n\tbool foldAtElse = styler.GetPropertyInt(\"fold.at.else\", 0) != 0;\n\tunsigned int endPos = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelCurrent = SC_FOLDLEVELBASE;\n\tif (lineCurrent > 0)\n\t\tlevelCurrent = styler.LevelAt(lineCurrent-1) >> 16;\n\tint levelMinCurrent = levelCurrent;\n\tint levelNext = levelCurrent;\n\tchar chNext = static_cast(tolower(styler[startPos]));\n\tint styleNext = styler.StyleAt(startPos);\n\tint style = initStyle;\n\tfor (unsigned int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = static_cast(tolower(styler.SafeGetCharAt(i + 1)));\n\t\tint stylePrev = style;\n\t\tstyle = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (foldComment && IsStreamCommentStyle(style)) {\n\t\t\tif (!IsStreamCommentStyle(stylePrev)) {\n\t\t\t\tlevelNext++;\n\t\t\t} else if (!IsStreamCommentStyle(styleNext)) { \/\/ && !atEOL) {\n\t\t\t\t\/\/ Comments don't end at end of line and the next character may be unstyled.\n\t\t\t\tlevelNext--;\n\t\t\t}\n\t\t}\n\t\telse if ((style & 0xf) == SCE_4GL_BLOCK && !isalnum(chNext)) {\n\t\t\tlevelNext++;\n\t\t}\n\t\telse if ((style & 0xf) == SCE_4GL_END && (ch == 'e' || ch == 'f')) {\n\t\t\tlevelNext--;\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint levelUse = levelCurrent;\n\t\t\tif (foldAtElse) {\n\t\t\t\tlevelUse = levelMinCurrent;\n\t\t\t}\n\t\t\tint lev = levelUse | levelNext << 16;\n\t\t\tif (visibleChars == 0 && foldCompact)\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\tif (levelUse < levelNext)\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelCurrent = levelNext;\n\t\t\tlevelMinCurrent = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch))\n\t\t\tvisibleChars++;\n\t}\n}\n\nstatic void Fold4glDoc(unsigned int startPos, int length, int initStyle, WordList *[],\n Accessor &styler) {\n\tFoldNoBox4glDoc(startPos, length, initStyle, styler);\n}\n\nstatic const char * const FglWordLists[] = {\n \"Primary keywords and identifiers\",\n \"Secondary keywords and identifiers\",\n \"Documentation comment keywords\",\n \"Unused\",\n \"Global classes and typedefs\",\n 0,\n };\n\nLexerModule lmProgress(SCLEX_PROGRESS, Colourise4glDoc, \"progress\", Fold4glDoc, FglWordLists);\nRefixed warning.\/\/ Scintilla source code edit control\n\/** @file LexProgress.cxx\n ** Lexer for Progress 4GL.\n ** Based on LexCPP.cxx of Neil Hodgson \n **\/\n\/\/ Copyright 2006-2007 by Yuval Papish \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n\/** TODO:\nWebSpeed support in html lexer\nSupport \"end triggers\" expression of the triggers phrase\nchange lmPS to lmProgress\nSupport more than 6 comments levels\n**\/\n#include \n#include \n#include \n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic inline bool IsAWordChar(int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\nstatic inline bool IsAWordStart(int ch) {\n\treturn (ch < 0x80) && (isalpha(ch) || ch == '_');\n}\n\nenum SentenceStart { SetSentenceStart = 0xf, ResetSentenceStart = 0x10}; \/\/ true -> bit5 = 0\n\nstatic void Colourise4glDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],\n Accessor &styler) {\n\n WordList &keywords1 = *keywordlists[0]; \/\/ regular keywords\n WordList &keywords2 = *keywordlists[1]; \/\/ block opening keywords, only when SentenceStart\n WordList &keywords3 = *keywordlists[2]; \/\/ block opening keywords\n \/\/WordList &keywords4 = *keywordlists[3]; \/\/ preprocessor keywords. Not implemented\n \n\n\tint visibleChars = 0;\n\tint sentenceStartState; \/\/ true -> bit5 = 0\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward()) {\n\n\t\tif (sc.atLineStart) {\n\t\t\t\/\/ Reset states to begining of colourise so no surprises\n\t\t\t\/\/ if different sets of lines lexed.\n\t\t\tvisibleChars = 0;\n\t\t}\n\n\t\t\/\/ Handle line continuation generically.\n\t\tif (sc.ch == '~') {\n\t\t\tif (sc.chNext > ' ') {\n\t\t\t\t\/\/ skip special char after ~\n\t\t\t\tsc.Forward();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ Skip whitespace between ~ and EOL\n\t\t\t\twhile (sc.More() && (sc.chNext == ' ' || sc.chNext == '\\t') ) {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tif (sc.chNext == '\\n' || sc.chNext == '\\r') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t\tif (sc.ch == '\\r' && sc.chNext == '\\n') {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t}\n\t\t\t\t\tsc.Forward();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ Determine if a new state should be terminated.\n\t\tsentenceStartState = sc.state & 0x10;\n\t\tswitch (sc.state & 0xf) {\n\t\t\tcase SCE_4GL_OPERATOR:\n\t\t\t\tsc.SetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_NUMBER:\n\t\t\t\tif (!(IsADigit(sc.ch))) {\n\t\t\t\t\tsc.SetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_IDENTIFIER:\n\t\t\t\tif (!IsAWordChar(sc.ch) && sc.ch != '-') {\n\t\t\t\t\tchar s[1000];\n\t\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\t\tif (((sentenceStartState == 0) && keywords2.InList(s)) || keywords3.InList(s)) { \n\t\t\t\t\t\tsc.ChangeState(SCE_4GL_BLOCK | ResetSentenceStart);\n\t\t\t\t\t}\n\t\t\t\t\telse if (keywords1.InList(s)) {\n\t\t\t\t\t\tif ((s[0] == 'e' && s[1] =='n' && s[2] == 'd' && !isalnum(s[3]) && s[3] != '-') ||\n\t\t\t\t\t\t\t(s[0] == 'f' && s[1] =='o' && s[2] == 'r' && s[3] == 'w' && s[4] =='a' && s[5] == 'r' && s[6] == 'd'&& !isalnum(s[7]))) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_4GL_END | ResetSentenceStart);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if\t((s[0] == 'e' && s[1] =='l' && s[2] == 's' && s[3] == 'e') ||\n\t\t\t\t\t\t\t\t (s[0] == 't' && s[1] =='h' && s[2] == 'e' && s[3] == 'n')) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_4GL_WORD & SetSentenceStart);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_4GL_WORD | ResetSentenceStart);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tsc.SetState(SCE_4GL_DEFAULT | (sc.state & 0x10));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_PREPROCESSOR:\n\t\t\t\tif (sc.atLineStart) {\n\t\t\t\t\tsc.SetState(SCE_4GL_DEFAULT & SetSentenceStart);\n\t\t\t\t} else if (sc.ch == '*' && sc.chNext == '\/') {\n\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_STRING:\n\t\t\t\tif (sc.ch == '\\\"') {\n\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SCE_4GL_CHARACTER:\n\t\t\t\tif (sc.ch == '\\'') {\n\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif ((sc.state & 0xf) >= SCE_4GL_COMMENT1) {\n\t\t\t\t\tif (sc.ch == '*' && sc.chNext == '\/') {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t\tif ((sc.state & 0xf) == SCE_4GL_COMMENT1) {\n\t\t\t\t\t\t\tsc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsc.SetState((sc.state & 0x1f) - 1);\n\t\t\t\t\t} else if (sc.ch == '\/' && sc.chNext == '*') {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t\tsc.SetState((sc.state & 0x1f) + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if a new state should be entered.\n\t\tsentenceStartState = sc.state & 0x10;\n\t\tif ((sc.state & 0xf) == SCE_4GL_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_4GL_NUMBER | ResetSentenceStart);\n\t\t\t} else if (IsAWordStart(sc.ch) || sc.ch == '@') {\n\t\t\t\tsc.SetState(SCE_4GL_IDENTIFIER | sentenceStartState);\n\t\t\t} else if (sc.ch == '\/' && sc.chNext == '*') {\n\t\t\t\tsc.SetState(SCE_4GL_COMMENT1 | sentenceStartState);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.SetState(SCE_4GL_STRING | ResetSentenceStart);\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tsc.SetState(SCE_4GL_CHARACTER | ResetSentenceStart);\n\t\t\t} else if (sc.ch == '&' && visibleChars == 0 && ((sc.state & 0x10) == 0)) {\n\t\t\t\tsc.SetState(SCE_4GL_PREPROCESSOR | ResetSentenceStart);\n\t\t\t\t\/\/ Skip whitespace between & and preprocessor word\n\t\t\t\tdo {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t} while ((sc.ch == ' ' || sc.ch == '\\t') && sc.More());\n\t\t\t\/\/ Handle syntactical line termination\n\t\t\t} else if ((sc.ch == '.' || sc.ch == ':' || sc.ch == '}') && (sc.chNext == ' ' || sc.chNext == '\\t' || sc.chNext == '\\n' || sc.chNext == '\\r')) {\n\t\t\t\tsc.SetState(sc.state & SetSentenceStart);\n\t\t\t} else if (isoperator(static_cast(sc.ch))) {\n\t\t\/* \tThis code allows highlight of handles. Alas, it would cause the frase \"last-event:function\"\n\t\t\tto be recognized as a BlockBegin\n\t\t\t\n\t\t\t\tif (sc.ch == ':')\n\t\t\t\t\tsc.SetState(SCE_4GL_OPERATOR & SetSentenceStart);\n\t\t\t\telse *\/\n\t\t\t\t\tsc.SetState(SCE_4GL_OPERATOR | ResetSentenceStart);\n\t\t\t}\n\t\t}\n\n\t\tif (!IsASpace(sc.ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic bool IsStreamCommentStyle(int style) {\n\treturn (style & 0xf) >= SCE_4GL_COMMENT1 ;\n}\n\n\/\/ Store both the current line's fold level and the next lines in the\n\/\/ level store to make it easy to pick up with each increment\n\/\/ and to make it possible to fiddle the current level for \"} else {\".\nstatic void FoldNoBox4glDoc(unsigned int startPos, int length, int initStyle,\n Accessor &styler) {\n\tbool foldComment = styler.GetPropertyInt(\"fold.comment\") != 0;\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n\tbool foldAtElse = styler.GetPropertyInt(\"fold.at.else\", 0) != 0;\n\tunsigned int endPos = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelCurrent = SC_FOLDLEVELBASE;\n\tif (lineCurrent > 0)\n\t\tlevelCurrent = styler.LevelAt(lineCurrent-1) >> 16;\n\tint levelMinCurrent = levelCurrent;\n\tint levelNext = levelCurrent;\n\tchar chNext = static_cast(tolower(styler[startPos]));\n\tint styleNext = styler.StyleAt(startPos);\n\tint style = initStyle;\n\tfor (unsigned int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = static_cast(tolower(styler.SafeGetCharAt(i + 1)));\n\t\tint stylePrev = style;\n\t\tstyle = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (foldComment && IsStreamCommentStyle(style)) {\n\t\t\tif (!IsStreamCommentStyle(stylePrev)) {\n\t\t\t\tlevelNext++;\n\t\t\t} else if (!IsStreamCommentStyle(styleNext)) { \/\/ && !atEOL) {\n\t\t\t\t\/\/ Comments don't end at end of line and the next character may be unstyled.\n\t\t\t\tlevelNext--;\n\t\t\t}\n\t\t}\n\t\telse if ((style & 0xf) == SCE_4GL_BLOCK && !isalnum(chNext)) {\n\t\t\tlevelNext++;\n\t\t}\n\t\telse if ((style & 0xf) == SCE_4GL_END && (ch == 'e' || ch == 'f')) {\n\t\t\tlevelNext--;\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint levelUse = levelCurrent;\n\t\t\tif (foldAtElse) {\n\t\t\t\tlevelUse = levelMinCurrent;\n\t\t\t}\n\t\t\tint lev = levelUse | levelNext << 16;\n\t\t\tif (visibleChars == 0 && foldCompact)\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\tif (levelUse < levelNext)\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelCurrent = levelNext;\n\t\t\tlevelMinCurrent = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch))\n\t\t\tvisibleChars++;\n\t}\n}\n\nstatic void Fold4glDoc(unsigned int startPos, int length, int initStyle, WordList *[],\n Accessor &styler) {\n\tFoldNoBox4glDoc(startPos, length, initStyle, styler);\n}\n\nstatic const char * const FglWordLists[] = {\n \"Primary keywords and identifiers\",\n \"Secondary keywords and identifiers\",\n \"Documentation comment keywords\",\n \"Unused\",\n \"Global classes and typedefs\",\n 0,\n };\n\nLexerModule lmProgress(SCLEX_PROGRESS, Colourise4glDoc, \"progress\", Fold4glDoc, FglWordLists);\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2008 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \n#include \n#include \n#include \"plugin_utils.h\"\n#include \"base64.h\"\n\n\nstd::string base64_encode(const std::string &text)\n{\n \/\/ convert to base64\n std::string dest;\n\n base64::encode(text.begin(), text.end(), std::back_inserter(dest));\n\n return dest;\n}\n\nstd::string base64_decode(const std::string &text)\n{\n \/\/ convert back to binary\n std::string dest;\n\n base64::decode(text.begin(), text.end(),std::back_inserter(dest));\n return dest;\n}\n\nconst char* bzu_GetTeamName(bz_eTeamType team)\n{\n switch (team) {\n\n case eRedTeam:\n return \"Red\";\n\n case eGreenTeam:\n return \"Green\";\n\n case eBlueTeam:\n return \"Blue\";\n\n case ePurpleTeam:\n return \"Purple\";\n\n case eRogueTeam:\n return \"Rogue\";\n\n case eObservers:\n return \"Observer\";\n\n case eRabbitTeam:\n return \"Rabbit\";\n\n case eHunterTeam:\n return \"Hunter\";\n\n default:\n break;\n }\n\n return \"Unknown\";\n}\n\nstd::string printTime(bz_Time *ts, const char* _timezone)\n{\n std::string time;\n appendTime(time,ts,_timezone);\n return time;\n}\n\n\/\/Date: Mon, 23 Jun 2008 17:50:22 GMT\n\nvoid appendTime(std::string & text, bz_Time *ts, const char* _timezone)\n{\n switch(ts->dayofweek) {\n case 1:\n text += \"Mon\";\n break;\n case 2:\n text += \"Tue\";\n break;\n case 3:\n text += \"Wed\";\n break;\n case 4:\n text += \"Thu\";\n break;\n case 5:\n text += \"Fri\";\n break;\n case 6:\n text += \"Sat\";\n break;\n case 0:\n text += \"Sun\";\n break;\n }\n\n text += format(\", %d \",ts->day);\n\n switch(ts->month) {\n case 0:\n text += \"Jan\";\n break;\n case 1:\n text += \"Feb\";\n break;\n case 2:\n text += \"Mar\";\n break;\n case 3:\n text += \"Apr\";\n break;\n case 4:\n text += \"May\";\n break;\n case 5:\n text += \"Jun\";\n break;\n case 6:\n text += \"Jul\";\n break;\n case 7:\n text += \"Aug\";\n break;\n case 8:\n text += \"Sep\";\n break;\n case 9:\n text += \"Oct\";\n break;\n case 10:\n text += \"Nov\";\n break;\n case 11:\n text += \"Dec\";\n break;\n }\n\n text += format(\" %d %d:%d:%d \",ts->year,ts->hour,ts->minute,ts->second);\n if (_timezone)\n text += _timezone;\n else\n text += \"GMT\";\n}\n\nstd::string no_whitespace(const std::string &s)\n{\n const int sourcesize = (int)s.size();\n\n int count = 0, i = 0, j = 0;\n for (i = 0; i < sourcesize; i++)\n if (!isWhitespace(s[i]))\n count++;\n\n \/\/ create result string of correct size\n std::string result(count, ' ');\n\n for (i = 0, j = 0; i < sourcesize; i++)\n if (!isWhitespace(s[i]))\n result[j++] = s[i];\n\n return result;\n}\n\nconst std::string& tolower(const std::string& s, std::string& dest)\n{\n for (std::string::const_iterator i=s.begin(), end=s.end(); i!=end; ++i)\n dest += ::tolower(*i);\n\n return dest;\n}\n\nconst std::string& toupper(const std::string& s, std::string& dest)\n{\n for (std::string::const_iterator i=s.begin(), end=s.end(); i!=end; ++i)\n dest += ::toupper(*i);\n\n return dest;\n}\n\nconst std::string& tolower(const char* s, std::string& dest)\n{\n if (!s)\n return dest;\n\n for (size_t i =0,end = strlen(s); i < end; i++)\n dest += ::tolower(s[i]);\n\n return dest;\n}\n\nconst std::string& toupper(const char* s, std::string& dest)\n{\n if (!s)\n return dest;\n\n for (size_t i =0,end = strlen(s); i < end; i++)\n dest += ::toupper(s[i]);\n\n return dest;\n}\n\nconst std::string& makelower(std::string& s)\n{\n for (std::string::iterator i=s.begin(), end=s.end(); i!=end; ++i)\n *i = ::tolower(*i);\n\n return s;\n}\n\nconst std::string& makeupper(std::string& s)\n{\n for (std::string::iterator i=s.begin(), end=s.end(); i!=end; ++i)\n *i = ::toupper(*i);\n\n return s;\n}\n\nstd::string format(const char* fmt, ...)\n{\n va_list args;\n va_start(args, fmt);\n char temp[2048];\n vsprintf(temp,fmt, args);\n std::string result = temp;\n va_end(args);\n return result;\n}\n\nstd::vector tokenize(const std::string& in, const std::string &delims,\n\t\t\t\t const int maxTokens, const bool useQuotes, size_t offset)\n{\n std::vector tokens;\n int numTokens = 0;\n bool inQuote = false;\n\n std::ostringstream currentToken;\n\n std::string::size_type pos = in.find_first_not_of(delims,offset);\n int currentChar = (pos == std::string::npos) ? -1 : in[pos];\n bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n\n while (pos != std::string::npos && !enoughTokens) {\n\n \/\/ get next token\n bool tokenDone = false;\n bool foundSlash = false;\n\n currentChar = (pos < in.size()) ? in[pos] : -1;\n while ((currentChar != -1) && !tokenDone) {\n\n tokenDone = false;\n\n if (delims.find(currentChar) != std::string::npos && !inQuote) { \/\/ currentChar is a delim\n\tpos ++;\n\tbreak; \/\/ breaks out of while loop\n }\n\n if (!useQuotes) {\n\tcurrentToken << char(currentChar);\n } else {\n\n\tswitch (currentChar) {\n\tcase '\\\\' : \/\/ found a backslash\n\t if (foundSlash) {\n\t currentToken << char(currentChar);\n\t foundSlash = false;\n\t } else {\n\t foundSlash = true;\n\t }\n\t break;\n\tcase '\\\"' : \/\/ found a quote\n\t if (foundSlash) { \/\/ found \\\"\n\t currentToken << char(currentChar);\n\t foundSlash = false;\n\t } else { \/\/ found unescaped \"\n\t if (inQuote) { \/\/ exiting a quote\n\t \/\/ finish off current token\n\t tokenDone = true;\n\t inQuote = false;\n\t \/\/slurp off one additional delimeter if possible\n\t if (pos+1 < in.size() &&\n\t\t delims.find(in[pos+1]) != std::string::npos) {\n\t\tpos++;\n\t }\n\n\t } else { \/\/ entering a quote\n\t \/\/ finish off current token\n\t tokenDone = true;\n\t inQuote = true;\n\t }\n\t }\n\t break;\n\tdefault:\n\t if (foundSlash) { \/\/ don't care about slashes except for above cases\n\t currentToken << '\\\\';\n\t foundSlash = false;\n\t }\n\t currentToken << char(currentChar);\n\t break;\n\t}\n }\n\n pos++;\n currentChar = (pos < in.size()) ? in[pos] : -1;\n } \/\/ end of getting a Token\n\n if (currentToken.str().size() > 0) { \/\/ if the token is something add to list\n tokens.push_back(currentToken.str());\n currentToken.str(\"\");\n numTokens ++;\n }\n\n enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n if (enoughTokens)\n break;\n else\n pos = in.find_first_not_of(delims,pos);\n\n } \/\/ end of getting all tokens -- either EOL or max tokens reached\n\n if (enoughTokens && pos != std::string::npos) {\n std::string lastToken = in.substr(pos);\n if (lastToken.size() > 0)\n tokens.push_back(lastToken);\n }\n\n return tokens;\n}\n\nstd::string replace_all(const std::string& in, const std::string& replaceMe, const std::string& withMe)\n{\n std::string result;\n std::string::size_type beginPos = 0;\n std::string::size_type endPos = 0;\n std::ostringstream tempStream;\n\n endPos = in.find(replaceMe);\n if (endPos == std::string::npos)\n return in; \/\/ can't find anything to replace\n if (replaceMe.empty()) return in; \/\/ can't replace nothing with something -- can do reverse\n\n while (endPos != std::string::npos) {\n \/\/ push the part up to\n tempStream << in.substr(beginPos,endPos-beginPos);\n tempStream << withMe;\n beginPos = endPos + replaceMe.size();\n endPos = in.find(replaceMe,beginPos);\n }\n tempStream << in.substr(beginPos);\n return tempStream.str();\n}\n\nstd::string url_encode(const std::string &text)\n{\n char hex[5];\n std::string destination;\n for (int i=0; i < (int) text.size(); i++) {\n char c = text[i];\n if (isAlphanumeric(c)) {\n destination+=c;\n } else if (isWhitespace(c)) {\n destination+='+';\n } else {\n destination+='%';\n sprintf(hex, \"%-2.2X\", c);\n destination.append(hex);\n }\n }\n return destination;\n}\n\nstd::string url_decode(const std::string &text)\n{\n std::string destination;\n\n std::string::const_iterator itr = text.begin();\n while (itr != text.end()) {\n if (*itr != '%' && *itr != '+')\n destination += *itr++;\n else if (*itr == '+')\n destination += \" \";\n else \n {\n char hex[5] = \"0x00\";\n\n itr++;;\n if (itr == text.end())\n\treturn destination;\n\n hex[2] = *itr;\n\n itr++;;\n if (itr == text.end())\n\treturn destination;\n\n hex[3] = *itr;\n\n unsigned int val = 0;\n sscanf(hex,\"%x\",&val);\n if (val != 0)\n\tdestination += (char)val;\n itr++;\n }\n }\n return destination;\n}\n\nsize_t find_first_substr(const std::string &findin, const std::string findwhat, size_t offset)\n{\n if (findwhat.size()) {\n for (size_t f = offset; f < findin.size(); f++) {\n if (findin[f] == findwhat[0]) {\n\tsize_t start = f;\n\tfor (size_t w = 1; w < findwhat.size(); w++) {\n\t if (f+w > findin.size())\n\t return std::string::npos;\n\t if (findin[f+w] != findwhat[w]) {\n\t f+=w;\n\t w = findwhat.size();\n\t }\n\t}\n\tif (start == f)\n\t return f;\n }\n }\n }\n return std::string::npos;\n}\n\nvoid trimLeadingWhitespace(std::string &text)\n{\n for(size_t s = 0; s < text.size(); s++) {\n if (!isWhitespace(text[s])) {\n if (s)\n\ttext.erase(text.begin()+s-1);\n return;\n }\n }\n}\n\nstd::string trimLeadingWhitespace(const std::string &text)\n{\n std::string s = text;\n trimLeadingWhitespace(s);\n return s;\n}\n\nstd::vector perms;\n\nconst std::vector bzu_standardPerms (void)\n{\n if (perms.empty()){\n perms.push_back(\"actionMessage\");\n perms.push_back(\"adminMessageReceive\");\n perms.push_back(\"adminMessageSend\");\n perms.push_back(\"antiban\");\n perms.push_back(\"antikick\");\n perms.push_back(\"antikill\");\n perms.push_back(\"antipoll\");\n perms.push_back(\"antipollban\");\n perms.push_back(\"antipollkick\");\n perms.push_back(\"antipollkill\");\n perms.push_back(\"ban\");\n perms.push_back(\"banlist\");\n perms.push_back(\"countdown\");\n perms.push_back(\"date\");\n perms.push_back(\"endGame\");\n perms.push_back(\"flagHistory\");\n perms.push_back(\"flagMaster\");\n perms.push_back(\"flagMod\");\n perms.push_back(\"hideAdmin\");\n perms.push_back(\"idleStats\");\n perms.push_back(\"info\");\n perms.push_back(\"jitter_warn\");\n perms.push_back(\"kick\");\n perms.push_back(\"kill\");\n perms.push_back(\"lagStats\");\n perms.push_back(\"lagwarn\");\n perms.push_back(\"listPlugins\");\n perms.push_back(\"listPerms\");\n perms.push_back(\"masterBan\");\n perms.push_back(\"modCount\");\n perms.push_back(\"mute\");\n perms.push_back(\"packetlosswarn\");\n perms.push_back(\"playerList\");\n perms.push_back(\"poll\");\n perms.push_back(\"pollBan\");\n perms.push_back(\"pollKick\");\n perms.push_back(\"pollKill\");\n perms.push_back(\"pollSet\");\n perms.push_back(\"pollFlagReset\");\n perms.push_back(\"privateMessage\");\n perms.push_back(\"record\");\n perms.push_back(\"rejoin\");\n perms.push_back(\"removePerms\");\n perms.push_back(\"replay\");\n perms.push_back(\"say\");\n perms.push_back(\"sendHelp\");\n perms.push_back(\"setAll\");\n perms.push_back(\"setPerms\");\n perms.push_back(\"setVar\");\n perms.push_back(\"showOthers\");\n perms.push_back(\"shortBan\");\n perms.push_back(\"shutdownServer\");\n perms.push_back(\"spawn\");\n perms.push_back(\"superKill\");\n perms.push_back(\"talk\");\n perms.push_back(\"unban\");\n perms.push_back(\"unmute\");\n perms.push_back(\"veto\");\n perms.push_back(\"viewReports\");\n perms.push_back(\"vote\");\n }\n return perms;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nIncrement the character pointer when \"+\" is seen. Fix whitespace. Remove duplicate semicolons.\/* bzflag\n * Copyright (c) 1993 - 2008 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \n#include \n#include \n#include \"plugin_utils.h\"\n#include \"base64.h\"\n\n\nstd::string base64_encode(const std::string &text)\n{\n \/\/ convert to base64\n std::string dest;\n\n base64::encode(text.begin(), text.end(), std::back_inserter(dest));\n\n return dest;\n}\n\nstd::string base64_decode(const std::string &text)\n{\n \/\/ convert back to binary\n std::string dest;\n\n base64::decode(text.begin(), text.end(),std::back_inserter(dest));\n return dest;\n}\n\nconst char* bzu_GetTeamName(bz_eTeamType team)\n{\n switch (team) {\n\n case eRedTeam:\n return \"Red\";\n\n case eGreenTeam:\n return \"Green\";\n\n case eBlueTeam:\n return \"Blue\";\n\n case ePurpleTeam:\n return \"Purple\";\n\n case eRogueTeam:\n return \"Rogue\";\n\n case eObservers:\n return \"Observer\";\n\n case eRabbitTeam:\n return \"Rabbit\";\n\n case eHunterTeam:\n return \"Hunter\";\n\n default:\n break;\n }\n\n return \"Unknown\";\n}\n\nstd::string printTime(bz_Time *ts, const char* _timezone)\n{\n std::string time;\n appendTime(time,ts,_timezone);\n return time;\n}\n\n\/\/Date: Mon, 23 Jun 2008 17:50:22 GMT\n\nvoid appendTime(std::string & text, bz_Time *ts, const char* _timezone)\n{\n switch(ts->dayofweek) {\n case 1:\n text += \"Mon\";\n break;\n case 2:\n text += \"Tue\";\n break;\n case 3:\n text += \"Wed\";\n break;\n case 4:\n text += \"Thu\";\n break;\n case 5:\n text += \"Fri\";\n break;\n case 6:\n text += \"Sat\";\n break;\n case 0:\n text += \"Sun\";\n break;\n }\n\n text += format(\", %d \",ts->day);\n\n switch(ts->month) {\n case 0:\n text += \"Jan\";\n break;\n case 1:\n text += \"Feb\";\n break;\n case 2:\n text += \"Mar\";\n break;\n case 3:\n text += \"Apr\";\n break;\n case 4:\n text += \"May\";\n break;\n case 5:\n text += \"Jun\";\n break;\n case 6:\n text += \"Jul\";\n break;\n case 7:\n text += \"Aug\";\n break;\n case 8:\n text += \"Sep\";\n break;\n case 9:\n text += \"Oct\";\n break;\n case 10:\n text += \"Nov\";\n break;\n case 11:\n text += \"Dec\";\n break;\n }\n\n text += format(\" %d %d:%d:%d \",ts->year,ts->hour,ts->minute,ts->second);\n if (_timezone)\n text += _timezone;\n else\n text += \"GMT\";\n}\n\nstd::string no_whitespace(const std::string &s)\n{\n const int sourcesize = (int)s.size();\n\n int count = 0, i = 0, j = 0;\n for (i = 0; i < sourcesize; i++)\n if (!isWhitespace(s[i]))\n count++;\n\n \/\/ create result string of correct size\n std::string result(count, ' ');\n\n for (i = 0, j = 0; i < sourcesize; i++)\n if (!isWhitespace(s[i]))\n result[j++] = s[i];\n\n return result;\n}\n\nconst std::string& tolower(const std::string& s, std::string& dest)\n{\n for (std::string::const_iterator i=s.begin(), end=s.end(); i!=end; ++i)\n dest += ::tolower(*i);\n\n return dest;\n}\n\nconst std::string& toupper(const std::string& s, std::string& dest)\n{\n for (std::string::const_iterator i=s.begin(), end=s.end(); i!=end; ++i)\n dest += ::toupper(*i);\n\n return dest;\n}\n\nconst std::string& tolower(const char* s, std::string& dest)\n{\n if (!s)\n return dest;\n\n for (size_t i =0,end = strlen(s); i < end; i++)\n dest += ::tolower(s[i]);\n\n return dest;\n}\n\nconst std::string& toupper(const char* s, std::string& dest)\n{\n if (!s)\n return dest;\n\n for (size_t i =0,end = strlen(s); i < end; i++)\n dest += ::toupper(s[i]);\n\n return dest;\n}\n\nconst std::string& makelower(std::string& s)\n{\n for (std::string::iterator i=s.begin(), end=s.end(); i!=end; ++i)\n *i = ::tolower(*i);\n\n return s;\n}\n\nconst std::string& makeupper(std::string& s)\n{\n for (std::string::iterator i=s.begin(), end=s.end(); i!=end; ++i)\n *i = ::toupper(*i);\n\n return s;\n}\n\nstd::string format(const char* fmt, ...)\n{\n va_list args;\n va_start(args, fmt);\n char temp[2048];\n vsprintf(temp,fmt, args);\n std::string result = temp;\n va_end(args);\n return result;\n}\n\nstd::vector tokenize(const std::string& in, const std::string &delims,\n\t\t\t\t const int maxTokens, const bool useQuotes, size_t offset)\n{\n std::vector tokens;\n int numTokens = 0;\n bool inQuote = false;\n\n std::ostringstream currentToken;\n\n std::string::size_type pos = in.find_first_not_of(delims,offset);\n int currentChar = (pos == std::string::npos) ? -1 : in[pos];\n bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n\n while (pos != std::string::npos && !enoughTokens) {\n\n \/\/ get next token\n bool tokenDone = false;\n bool foundSlash = false;\n\n currentChar = (pos < in.size()) ? in[pos] : -1;\n while ((currentChar != -1) && !tokenDone) {\n\n tokenDone = false;\n\n if (delims.find(currentChar) != std::string::npos && !inQuote) { \/\/ currentChar is a delim\n\tpos ++;\n\tbreak; \/\/ breaks out of while loop\n }\n\n if (!useQuotes) {\n\tcurrentToken << char(currentChar);\n } else {\n\n\tswitch (currentChar) {\n\tcase '\\\\' : \/\/ found a backslash\n\t if (foundSlash) {\n\t currentToken << char(currentChar);\n\t foundSlash = false;\n\t } else {\n\t foundSlash = true;\n\t }\n\t break;\n\tcase '\\\"' : \/\/ found a quote\n\t if (foundSlash) { \/\/ found \\\"\n\t currentToken << char(currentChar);\n\t foundSlash = false;\n\t } else { \/\/ found unescaped \"\n\t if (inQuote) { \/\/ exiting a quote\n\t \/\/ finish off current token\n\t tokenDone = true;\n\t inQuote = false;\n\t \/\/slurp off one additional delimeter if possible\n\t if (pos+1 < in.size() &&\n\t\t delims.find(in[pos+1]) != std::string::npos) {\n\t\tpos++;\n\t }\n\n\t } else { \/\/ entering a quote\n\t \/\/ finish off current token\n\t tokenDone = true;\n\t inQuote = true;\n\t }\n\t }\n\t break;\n\tdefault:\n\t if (foundSlash) { \/\/ don't care about slashes except for above cases\n\t currentToken << '\\\\';\n\t foundSlash = false;\n\t }\n\t currentToken << char(currentChar);\n\t break;\n\t}\n }\n\n pos++;\n currentChar = (pos < in.size()) ? in[pos] : -1;\n } \/\/ end of getting a Token\n\n if (currentToken.str().size() > 0) { \/\/ if the token is something add to list\n tokens.push_back(currentToken.str());\n currentToken.str(\"\");\n numTokens ++;\n }\n\n enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));\n if (enoughTokens)\n break;\n else\n pos = in.find_first_not_of(delims,pos);\n\n } \/\/ end of getting all tokens -- either EOL or max tokens reached\n\n if (enoughTokens && pos != std::string::npos) {\n std::string lastToken = in.substr(pos);\n if (lastToken.size() > 0)\n tokens.push_back(lastToken);\n }\n\n return tokens;\n}\n\nstd::string replace_all(const std::string& in, const std::string& replaceMe, const std::string& withMe)\n{\n std::string result;\n std::string::size_type beginPos = 0;\n std::string::size_type endPos = 0;\n std::ostringstream tempStream;\n\n endPos = in.find(replaceMe);\n if (endPos == std::string::npos)\n return in; \/\/ can't find anything to replace\n if (replaceMe.empty()) return in; \/\/ can't replace nothing with something -- can do reverse\n\n while (endPos != std::string::npos) {\n \/\/ push the part up to\n tempStream << in.substr(beginPos,endPos-beginPos);\n tempStream << withMe;\n beginPos = endPos + replaceMe.size();\n endPos = in.find(replaceMe,beginPos);\n }\n tempStream << in.substr(beginPos);\n return tempStream.str();\n}\n\nstd::string url_encode(const std::string &text)\n{\n char hex[5];\n std::string destination;\n for (int i=0; i < (int) text.size(); i++) {\n char c = text[i];\n if (isAlphanumeric(c)) {\n destination+=c;\n } else if (isWhitespace(c)) {\n destination+='+';\n } else {\n destination+='%';\n sprintf(hex, \"%-2.2X\", c);\n destination.append(hex);\n }\n }\n return destination;\n}\n\nstd::string url_decode(const std::string &text)\n{\n std::string destination;\n\n std::string::const_iterator itr = text.begin();\n while (itr != text.end()) {\n if (*itr != '%' && *itr != '+')\n destination += *itr++;\n else if (*itr == '+') {\n destination += \" \";\n itr++;\n }\n else {\n char hex[5] = \"0x00\";\n\n itr++;\n if (itr == text.end())\n\treturn destination;\n\n hex[2] = *itr;\n\n itr++;\n if (itr == text.end())\n\treturn destination;\n\n hex[3] = *itr;\n\n unsigned int val = 0;\n sscanf(hex,\"%x\",&val);\n if (val != 0)\n\tdestination += (char)val;\n itr++;\n }\n }\n return destination;\n}\n\nsize_t find_first_substr(const std::string &findin, const std::string findwhat, size_t offset)\n{\n if (findwhat.size()) {\n for (size_t f = offset; f < findin.size(); f++) {\n if (findin[f] == findwhat[0]) {\n\tsize_t start = f;\n\tfor (size_t w = 1; w < findwhat.size(); w++) {\n\t if (f+w > findin.size())\n\t return std::string::npos;\n\t if (findin[f+w] != findwhat[w]) {\n\t f+=w;\n\t w = findwhat.size();\n\t }\n\t}\n\tif (start == f)\n\t return f;\n }\n }\n }\n return std::string::npos;\n}\n\nvoid trimLeadingWhitespace(std::string &text)\n{\n for(size_t s = 0; s < text.size(); s++) {\n if (!isWhitespace(text[s])) {\n if (s)\n\ttext.erase(text.begin()+s-1);\n return;\n }\n }\n}\n\nstd::string trimLeadingWhitespace(const std::string &text)\n{\n std::string s = text;\n trimLeadingWhitespace(s);\n return s;\n}\n\nstd::vector perms;\n\nconst std::vector bzu_standardPerms (void)\n{\n if (perms.empty()){\n perms.push_back(\"actionMessage\");\n perms.push_back(\"adminMessageReceive\");\n perms.push_back(\"adminMessageSend\");\n perms.push_back(\"antiban\");\n perms.push_back(\"antikick\");\n perms.push_back(\"antikill\");\n perms.push_back(\"antipoll\");\n perms.push_back(\"antipollban\");\n perms.push_back(\"antipollkick\");\n perms.push_back(\"antipollkill\");\n perms.push_back(\"ban\");\n perms.push_back(\"banlist\");\n perms.push_back(\"countdown\");\n perms.push_back(\"date\");\n perms.push_back(\"endGame\");\n perms.push_back(\"flagHistory\");\n perms.push_back(\"flagMaster\");\n perms.push_back(\"flagMod\");\n perms.push_back(\"hideAdmin\");\n perms.push_back(\"idleStats\");\n perms.push_back(\"info\");\n perms.push_back(\"jitter_warn\");\n perms.push_back(\"kick\");\n perms.push_back(\"kill\");\n perms.push_back(\"lagStats\");\n perms.push_back(\"lagwarn\");\n perms.push_back(\"listPlugins\");\n perms.push_back(\"listPerms\");\n perms.push_back(\"masterBan\");\n perms.push_back(\"modCount\");\n perms.push_back(\"mute\");\n perms.push_back(\"packetlosswarn\");\n perms.push_back(\"playerList\");\n perms.push_back(\"poll\");\n perms.push_back(\"pollBan\");\n perms.push_back(\"pollKick\");\n perms.push_back(\"pollKill\");\n perms.push_back(\"pollSet\");\n perms.push_back(\"pollFlagReset\");\n perms.push_back(\"privateMessage\");\n perms.push_back(\"record\");\n perms.push_back(\"rejoin\");\n perms.push_back(\"removePerms\");\n perms.push_back(\"replay\");\n perms.push_back(\"say\");\n perms.push_back(\"sendHelp\");\n perms.push_back(\"setAll\");\n perms.push_back(\"setPerms\");\n perms.push_back(\"setVar\");\n perms.push_back(\"showOthers\");\n perms.push_back(\"shortBan\");\n perms.push_back(\"shutdownServer\");\n perms.push_back(\"spawn\");\n perms.push_back(\"superKill\");\n perms.push_back(\"talk\");\n perms.push_back(\"unban\");\n perms.push_back(\"unmute\");\n perms.push_back(\"veto\");\n perms.push_back(\"viewReports\");\n perms.push_back(\"vote\");\n }\n return perms;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n* File: vcs.cpp\n* Purpose: Implementation of wxExVCS class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nwxExVCS* wxExVCS::m_Self = NULL;\n#if wxUSE_GUI\nwxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;\n#endif\n\nwxExVCS::wxExVCS()\n : m_Command(VCS_NO_COMMAND)\n , m_FullPath(wxEmptyString)\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(int command_id, const wxString& fullpath)\n : m_Command(GetType(command_id))\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(wxExCommand type, const wxString& fullpath)\n : m_Command(type)\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\n#if wxUSE_GUI\nint wxExVCS::ConfigDialog(\n wxWindow* parent,\n const wxString& title) const\n{\n std::vector v;\n\n std::map choices;\n choices.insert(std::make_pair(VCS_NONE, _(\"None\")));\n choices.insert(std::make_pair(VCS_GIT, \"GIT\"));\n choices.insert(std::make_pair(VCS_SVN, \"SVN\"));\n v.push_back(wxExConfigItem(\"VCS\", choices));\n\n v.push_back(wxExConfigItem(\"GIT\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(\"SVN\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(_(\"Comparator\"), CONFIG_FILEPICKERCTRL));\n\n return wxExConfigDialog(parent, v, title).ShowModal();\n}\n#endif\n\nbool wxExVCS::DirExists(const wxFileName& filename) const\n{\n switch (GetVCS())\n {\n case VCS_GIT: \n {\n \/\/ The .git dir only exists in the root, so check all components.\n wxFileName root(filename.GetPath());\n\n while (root.DirExists() && root.GetDirCount() > 0)\n {\n wxFileName path(root);\n path.AppendDir(\".git\");\n\n if (path.DirExists())\n {\n return true;\n }\n\n root.RemoveLastDir();\n }\n }\n break;\n\n case VCS_NONE: break; \/\/ prevent wxFAIL\n \n case VCS_SVN: \n {\n \/\/ these cannot be combined, as AppendDir is a void (2.9.1).\n wxFileName path(filename);\n path.AppendDir(\".svn\");\n return path.DirExists();\n }\n break;\n\n default: wxFAIL;\n }\n\n return false;\n}\n\nlong wxExVCS::Execute()\n{\n wxASSERT(m_Command != VCS_NO_COMMAND);\n\n wxString cwd;\n wxString file;\n\n if (m_FullPath.empty())\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(wxExConfigFirstOf(_(\"Base folder\")));\n\n if (m_Command == VCS_ADD)\n {\n file = \" \" + wxExConfigFirstOf(_(\"Path\"));\n }\n }\n else\n {\n if (GetVCS() == VCS_GIT)\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(wxFileName(m_FullPath).GetPath());\n file = \" \\\"\" + wxFileName(m_FullPath).GetFullName() + \"\\\"\";\n }\n else\n {\n file = \" \\\"\" + m_FullPath + \"\\\"\";\n }\n }\n\n wxString comment;\n\n if (m_Command == VCS_COMMIT)\n {\n comment = \n \" -m \\\"\" + wxExConfigFirstOf(_(\"Revision comment\")) + \"\\\"\";\n }\n\n wxString subcommand;\n \n if (UseSubcommand())\n {\n subcommand = wxConfigBase::Get()->Read(_(\"Subcommand\"));\n\n if (!subcommand.empty())\n {\n subcommand = \" \" + subcommand;\n }\n }\n\n wxString flags;\n\n if (UseFlags())\n {\n flags = wxConfigBase::Get()->Read(_(\"Flags\"));\n\n if (!flags.empty())\n {\n flags = \" \" + flags;\n }\n }\n\n m_CommandWithFlags = m_CommandString + flags;\n\n wxString vcs_bin;\n\n switch (GetVCS())\n {\n case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read(\"GIT\", \"git\"); break;\n case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read(\"SVN\", \"svn\"); break;\n default: wxFAIL;\n }\n\n if (vcs_bin.empty())\n {\n wxLogError(GetVCSName() + \" \" + _(\"path is empty\"));\n return -1;\n }\n\n const wxString commandline = \n vcs_bin + \" \" + m_CommandString + subcommand + flags + comment + file;\n\n#if wxUSE_STATUSBAR\n wxExFrame::StatusText(commandline);\n#endif\n\n wxArrayString output;\n wxArrayString errors;\n long retValue;\n\n if ((retValue = wxExecute(\n commandline,\n output,\n errors)) == -1)\n {\n \/\/ See also process, same log is shown.\n wxLogError(_(\"Cannot execute\") + \": \" + commandline);\n }\n else\n {\n wxExLog::Get()->Log(commandline);\n }\n\n if (!cwd.empty())\n {\n wxSetWorkingDirectory(cwd);\n }\n\n m_Output.clear();\n\n \/\/ First output the errors.\n for (\n size_t i = 0;\n i < errors.GetCount();\n i++)\n {\n m_Output += errors[i] + \"\\n\";\n }\n\n \/\/ Then the normal output, will be empty if there are errors.\n for (\n size_t j = 0;\n j < output.GetCount();\n j++)\n {\n m_Output += output[j] + \"\\n\";\n }\n\n return retValue;\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)\n{\n if (ShowDialog(parent) == wxID_CANCEL)\n {\n return wxID_CANCEL;\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(m_FlagsKey, \n wxConfigBase::Get()->Read(_(\"Flags\")));\n }\n\n const auto retValue = Execute();\n \n return (retValue != -1 ? wxID_OK: wxID_CANCEL);\n}\n#endif\n\nwxExVCS* wxExVCS::Get(bool createOnDemand)\n{\n if (m_Self == NULL && createOnDemand)\n {\n m_Self = new wxExVCS;\n\n \/\/ Add default VCS.\n if (!wxConfigBase::Get()->Exists(\"VCS\"))\n {\n \/\/ TODO: Add SVN only if svn bin exists on linux.\n wxConfigBase::Get()->Write(\"VCS\", (long)VCS_SVN);\n }\n }\n\n return m_Self;\n}\n\nwxExVCS::wxExCommand wxExVCS::GetType(int command_id) const\n{\n if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_VCS_LOWEST);\n }\n else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST);\n }\n else\n {\n wxFAIL;\n return VCS_NO_COMMAND;\n }\n}\n\nlong wxExVCS::GetVCS() const\n{\n return wxConfigBase::Get()->ReadLong(\"VCS\", VCS_SVN);\n}\n\nconst wxString wxExVCS::GetVCSName() const\n{\n wxString text;\n\n switch (GetVCS())\n {\n case VCS_GIT: text = \"GIT\"; break;\n case VCS_SVN: text = \"SVN\"; break;\n default: wxFAIL;\n }\n\n return text;\n}\n\nvoid wxExVCS::Initialize()\n{\n if (Use() && m_Command != VCS_NO_COMMAND)\n {\n switch (GetVCS())\n {\n case VCS_GIT:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: break;\n case VCS_PROPLIST: break;\n case VCS_PROPSET: break;\n case VCS_PUSH: m_CommandString = \"push\"; break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: m_CommandString = \"show\"; break;\n case VCS_STAT: m_CommandString = \"status\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n case VCS_SVN:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: m_CommandString = \"cat\"; break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: m_CommandString = \"info\"; break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: m_CommandString = \"ls\"; break;\n case VCS_PROPLIST: m_CommandString = \"proplist\"; break;\n case VCS_PROPSET: m_CommandString = \"propset\"; break;\n case VCS_PUSH: break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: break;\n case VCS_STAT: m_CommandString = \"stat\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n default: wxFAIL;\n }\n\n m_Caption = GetVCSName() + \" \" + m_CommandString;\n\n \/\/ Currently no flags, as no command was executed.\n m_CommandWithFlags = m_CommandString;\n\n \/\/ Use general key.\n m_FlagsKey = wxString::Format(\"cvsflags\/name%d\", m_Command);\n }\n\n m_Output.clear();\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::Request(wxWindow* parent)\n{\n wxStandardID retValue;\n\n if ((retValue = ExecuteDialog(parent)) == wxID_OK)\n {\n ShowOutput(parent);\n }\n\n return retValue;\n}\n#endif\n\nwxExVCS* wxExVCS::Set(wxExVCS* vcs)\n{\n wxExVCS* old = m_Self;\n m_Self = vcs;\n return old;\n}\n\n#if wxUSE_GUI\nint wxExVCS::ShowDialog(wxWindow* parent)\n{\n std::vector v;\n\n if (m_Command == VCS_COMMIT)\n {\n v.push_back(wxExConfigItem(\n _(\"Revision comment\"), \n CONFIG_COMBOBOX,\n wxEmptyString,\n true)); \/\/ required\n }\n\n if (m_FullPath.empty() && m_Command != VCS_HELP)\n {\n v.push_back(wxExConfigItem(\n _(\"Base folder\"), \n CONFIG_COMBOBOXDIR, \n wxEmptyString, \n true,\n 1000));\n\n if (m_Command == VCS_ADD)\n {\n v.push_back(wxExConfigItem(\n _(\"Path\"), \n CONFIG_COMBOBOX,\n wxEmptyString, \n true)); \/\/ required\n }\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(\n _(\"Flags\"), \n wxConfigBase::Get()->Read(m_FlagsKey));\n\n v.push_back(wxExConfigItem(_(\"Flags\")));\n }\n\n if (UseSubcommand())\n {\n v.push_back(wxExConfigItem(_(\"Subcommand\")));\n }\n\n return wxExConfigDialog(parent,\n v,\n m_Caption).ShowModal();\n}\n#endif\n\n#if wxUSE_GUI\nvoid wxExVCS::ShowOutput(wxWindow* parent) const\n{\n wxString caption = m_Caption;\n \n if (m_Command != VCS_HELP)\n {\n caption += \" \" + (!m_FullPath.empty() ? \n wxFileName(m_FullPath).GetFullName(): \n wxExConfigFirstOf(_(\"Base folder\")));\n }\n\n \/\/ Create a dialog for contents.\n if (m_STCEntryDialog == NULL)\n {\n m_STCEntryDialog = new wxExSTCEntryDialog(\n parent,\n caption,\n m_Output,\n wxEmptyString,\n wxOK,\n wxID_ANY,\n wxDefaultPosition,\n wxSize(350, 50));\n }\n else\n {\n m_STCEntryDialog->SetText(m_Output);\n m_STCEntryDialog->SetTitle(caption);\n }\n\n \/\/ Add a lexer if we specified a path, asked for cat or blame \n \/\/ and there is a lexer.\n if (\n !m_FullPath.empty() &&\n (m_Command == VCS_CAT || m_Command == VCS_BLAME))\n {\n const wxExFileName fn(m_FullPath);\n \n if (fn.GetLexer().IsOk())\n {\n m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());\n }\n }\n else\n {\n m_STCEntryDialog->SetLexer(wxEmptyString);\n }\n\n m_STCEntryDialog->Show();\n}\n#endif\n\nbool wxExVCS::Use() const\n{\n return GetVCS() != VCS_NONE;\n}\n\nbool wxExVCS::UseFlags() const\n{\n return m_Command != VCS_UPDATE && m_Command != VCS_HELP;\n}\n\nbool wxExVCS::UseSubcommand() const\n{\n return m_Command == VCS_HELP;\n}\nadded diff lexer for VCS_DIFF\/******************************************************************************\\\n* File: vcs.cpp\n* Purpose: Implementation of wxExVCS class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nwxExVCS* wxExVCS::m_Self = NULL;\n#if wxUSE_GUI\nwxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;\n#endif\n\nwxExVCS::wxExVCS()\n : m_Command(VCS_NO_COMMAND)\n , m_FullPath(wxEmptyString)\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(int command_id, const wxString& fullpath)\n : m_Command(GetType(command_id))\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\nwxExVCS::wxExVCS(wxExCommand type, const wxString& fullpath)\n : m_Command(type)\n , m_FullPath(fullpath)\n{\n Initialize();\n}\n\n#if wxUSE_GUI\nint wxExVCS::ConfigDialog(\n wxWindow* parent,\n const wxString& title) const\n{\n std::vector v;\n\n std::map choices;\n choices.insert(std::make_pair(VCS_NONE, _(\"None\")));\n choices.insert(std::make_pair(VCS_GIT, \"GIT\"));\n choices.insert(std::make_pair(VCS_SVN, \"SVN\"));\n v.push_back(wxExConfigItem(\"VCS\", choices));\n\n v.push_back(wxExConfigItem(\"GIT\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(\"SVN\", CONFIG_FILEPICKERCTRL));\n v.push_back(wxExConfigItem(_(\"Comparator\"), CONFIG_FILEPICKERCTRL));\n\n return wxExConfigDialog(parent, v, title).ShowModal();\n}\n#endif\n\nbool wxExVCS::DirExists(const wxFileName& filename) const\n{\n switch (GetVCS())\n {\n case VCS_GIT: \n {\n \/\/ The .git dir only exists in the root, so check all components.\n wxFileName root(filename.GetPath());\n\n while (root.DirExists() && root.GetDirCount() > 0)\n {\n wxFileName path(root);\n path.AppendDir(\".git\");\n\n if (path.DirExists())\n {\n return true;\n }\n\n root.RemoveLastDir();\n }\n }\n break;\n\n case VCS_NONE: break; \/\/ prevent wxFAIL\n \n case VCS_SVN: \n {\n \/\/ these cannot be combined, as AppendDir is a void (2.9.1).\n wxFileName path(filename);\n path.AppendDir(\".svn\");\n return path.DirExists();\n }\n break;\n\n default: wxFAIL;\n }\n\n return false;\n}\n\nlong wxExVCS::Execute()\n{\n wxASSERT(m_Command != VCS_NO_COMMAND);\n\n wxString cwd;\n wxString file;\n\n if (m_FullPath.empty())\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(wxExConfigFirstOf(_(\"Base folder\")));\n\n if (m_Command == VCS_ADD)\n {\n file = \" \" + wxExConfigFirstOf(_(\"Path\"));\n }\n }\n else\n {\n if (GetVCS() == VCS_GIT)\n {\n cwd = wxGetCwd();\n wxSetWorkingDirectory(wxFileName(m_FullPath).GetPath());\n file = \" \\\"\" + wxFileName(m_FullPath).GetFullName() + \"\\\"\";\n }\n else\n {\n file = \" \\\"\" + m_FullPath + \"\\\"\";\n }\n }\n\n wxString comment;\n\n if (m_Command == VCS_COMMIT)\n {\n comment = \n \" -m \\\"\" + wxExConfigFirstOf(_(\"Revision comment\")) + \"\\\"\";\n }\n\n wxString subcommand;\n \n if (UseSubcommand())\n {\n subcommand = wxConfigBase::Get()->Read(_(\"Subcommand\"));\n\n if (!subcommand.empty())\n {\n subcommand = \" \" + subcommand;\n }\n }\n\n wxString flags;\n\n if (UseFlags())\n {\n flags = wxConfigBase::Get()->Read(_(\"Flags\"));\n\n if (!flags.empty())\n {\n flags = \" \" + flags;\n }\n }\n\n m_CommandWithFlags = m_CommandString + flags;\n\n wxString vcs_bin;\n\n switch (GetVCS())\n {\n case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read(\"GIT\", \"git\"); break;\n case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read(\"SVN\", \"svn\"); break;\n default: wxFAIL;\n }\n\n if (vcs_bin.empty())\n {\n wxLogError(GetVCSName() + \" \" + _(\"path is empty\"));\n return -1;\n }\n\n const wxString commandline = \n vcs_bin + \" \" + m_CommandString + subcommand + flags + comment + file;\n\n#if wxUSE_STATUSBAR\n wxExFrame::StatusText(commandline);\n#endif\n\n wxArrayString output;\n wxArrayString errors;\n long retValue;\n\n if ((retValue = wxExecute(\n commandline,\n output,\n errors)) == -1)\n {\n \/\/ See also process, same log is shown.\n wxLogError(_(\"Cannot execute\") + \": \" + commandline);\n }\n else\n {\n wxExLog::Get()->Log(commandline);\n }\n\n if (!cwd.empty())\n {\n wxSetWorkingDirectory(cwd);\n }\n\n m_Output.clear();\n\n \/\/ First output the errors.\n for (\n size_t i = 0;\n i < errors.GetCount();\n i++)\n {\n m_Output += errors[i] + \"\\n\";\n }\n\n \/\/ Then the normal output, will be empty if there are errors.\n for (\n size_t j = 0;\n j < output.GetCount();\n j++)\n {\n m_Output += output[j] + \"\\n\";\n }\n\n return retValue;\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)\n{\n if (ShowDialog(parent) == wxID_CANCEL)\n {\n return wxID_CANCEL;\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(m_FlagsKey, \n wxConfigBase::Get()->Read(_(\"Flags\")));\n }\n\n const auto retValue = Execute();\n \n return (retValue != -1 ? wxID_OK: wxID_CANCEL);\n}\n#endif\n\nwxExVCS* wxExVCS::Get(bool createOnDemand)\n{\n if (m_Self == NULL && createOnDemand)\n {\n m_Self = new wxExVCS;\n\n \/\/ Add default VCS.\n if (!wxConfigBase::Get()->Exists(\"VCS\"))\n {\n \/\/ TODO: Add SVN only if svn bin exists on linux.\n wxConfigBase::Get()->Write(\"VCS\", (long)VCS_SVN);\n }\n }\n\n return m_Self;\n}\n\nwxExVCS::wxExCommand wxExVCS::GetType(int command_id) const\n{\n if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_VCS_LOWEST);\n }\n else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST)\n {\n return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST);\n }\n else\n {\n wxFAIL;\n return VCS_NO_COMMAND;\n }\n}\n\nlong wxExVCS::GetVCS() const\n{\n return wxConfigBase::Get()->ReadLong(\"VCS\", VCS_SVN);\n}\n\nconst wxString wxExVCS::GetVCSName() const\n{\n wxString text;\n\n switch (GetVCS())\n {\n case VCS_GIT: text = \"GIT\"; break;\n case VCS_SVN: text = \"SVN\"; break;\n default: wxFAIL;\n }\n\n return text;\n}\n\nvoid wxExVCS::Initialize()\n{\n if (Use() && m_Command != VCS_NO_COMMAND)\n {\n switch (GetVCS())\n {\n case VCS_GIT:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: break;\n case VCS_PROPLIST: break;\n case VCS_PROPSET: break;\n case VCS_PUSH: m_CommandString = \"push\"; break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: m_CommandString = \"show\"; break;\n case VCS_STAT: m_CommandString = \"status\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n case VCS_SVN:\n switch (m_Command)\n {\n case VCS_ADD: m_CommandString = \"add\"; break;\n case VCS_BLAME: m_CommandString = \"blame\"; break;\n case VCS_CAT: m_CommandString = \"cat\"; break;\n case VCS_COMMIT: m_CommandString = \"commit\"; break;\n case VCS_DIFF: m_CommandString = \"diff\"; break;\n case VCS_HELP: m_CommandString = \"help\"; break;\n case VCS_INFO: m_CommandString = \"info\"; break;\n case VCS_LOG: m_CommandString = \"log\"; break;\n case VCS_LS: m_CommandString = \"ls\"; break;\n case VCS_PROPLIST: m_CommandString = \"proplist\"; break;\n case VCS_PROPSET: m_CommandString = \"propset\"; break;\n case VCS_PUSH: break;\n case VCS_REVERT: m_CommandString = \"revert\"; break;\n case VCS_SHOW: break;\n case VCS_STAT: m_CommandString = \"stat\"; break;\n case VCS_UPDATE: m_CommandString = \"update\"; break;\n default:\n wxFAIL;\n break;\n }\n break;\n\n default: wxFAIL;\n }\n\n m_Caption = GetVCSName() + \" \" + m_CommandString;\n\n \/\/ Currently no flags, as no command was executed.\n m_CommandWithFlags = m_CommandString;\n\n \/\/ Use general key.\n m_FlagsKey = wxString::Format(\"cvsflags\/name%d\", m_Command);\n }\n\n m_Output.clear();\n}\n\n#if wxUSE_GUI\nwxStandardID wxExVCS::Request(wxWindow* parent)\n{\n wxStandardID retValue;\n\n if ((retValue = ExecuteDialog(parent)) == wxID_OK)\n {\n ShowOutput(parent);\n }\n\n return retValue;\n}\n#endif\n\nwxExVCS* wxExVCS::Set(wxExVCS* vcs)\n{\n wxExVCS* old = m_Self;\n m_Self = vcs;\n return old;\n}\n\n#if wxUSE_GUI\nint wxExVCS::ShowDialog(wxWindow* parent)\n{\n std::vector v;\n\n if (m_Command == VCS_COMMIT)\n {\n v.push_back(wxExConfigItem(\n _(\"Revision comment\"), \n CONFIG_COMBOBOX,\n wxEmptyString,\n true)); \/\/ required\n }\n\n if (m_FullPath.empty() && m_Command != VCS_HELP)\n {\n v.push_back(wxExConfigItem(\n _(\"Base folder\"), \n CONFIG_COMBOBOXDIR, \n wxEmptyString, \n true,\n 1000));\n\n if (m_Command == VCS_ADD)\n {\n v.push_back(wxExConfigItem(\n _(\"Path\"), \n CONFIG_COMBOBOX,\n wxEmptyString, \n true)); \/\/ required\n }\n }\n\n if (UseFlags())\n {\n wxConfigBase::Get()->Write(\n _(\"Flags\"), \n wxConfigBase::Get()->Read(m_FlagsKey));\n\n v.push_back(wxExConfigItem(_(\"Flags\")));\n }\n\n if (UseSubcommand())\n {\n v.push_back(wxExConfigItem(_(\"Subcommand\")));\n }\n\n return wxExConfigDialog(parent,\n v,\n m_Caption).ShowModal();\n}\n#endif\n\n#if wxUSE_GUI\nvoid wxExVCS::ShowOutput(wxWindow* parent) const\n{\n wxString caption = m_Caption;\n \n if (m_Command != VCS_HELP)\n {\n caption += \" \" + (!m_FullPath.empty() ? \n wxFileName(m_FullPath).GetFullName(): \n wxExConfigFirstOf(_(\"Base folder\")));\n }\n\n \/\/ Create a dialog for contents.\n if (m_STCEntryDialog == NULL)\n {\n m_STCEntryDialog = new wxExSTCEntryDialog(\n parent,\n caption,\n m_Output,\n wxEmptyString,\n wxOK,\n wxID_ANY,\n wxDefaultPosition,\n wxSize(350, 50));\n }\n else\n {\n m_STCEntryDialog->SetText(m_Output);\n m_STCEntryDialog->SetTitle(caption);\n }\n\n \/\/ Add a lexer when appropriate.\n if (\n !m_FullPath.empty() &&\n (m_Command == VCS_CAT || m_Command == VCS_BLAME))\n {\n const wxExFileName fn(m_FullPath);\n \n if (fn.GetLexer().IsOk())\n {\n m_STCEntryDialog->SetLexer(fn.GetLexer().GetScintillaLexer());\n }\n }\n else if (m_Command == VCS_DIFF)\n {\n m_STCEntryDialog->SetLexer(\"diff\");\n }\n else\n {\n m_STCEntryDialog->SetLexer(wxEmptyString);\n }\n\n m_STCEntryDialog->Show();\n}\n#endif\n\nbool wxExVCS::Use() const\n{\n return GetVCS() != VCS_NONE;\n}\n\nbool wxExVCS::UseFlags() const\n{\n return m_Command != VCS_UPDATE && m_Command != VCS_HELP;\n}\n\nbool wxExVCS::UseSubcommand() const\n{\n return m_Command == VCS_HELP;\n}\n<|endoftext|>"} {"text":"It executes right but it doesnt make sens, need to investigate<|endoftext|>"} {"text":"\n\/**\n Copyright(c) 2015 - 2017 Denis Blank \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files(the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions :\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n**\/\n\n#ifndef TEST_CONTINUABLE_HPP__\n#define TEST_CONTINUABLE_HPP__\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\nusing cti::detail::traits::identity;\n\ninline auto to_hint(identity<> \/*hint*\/) {\n return identity{};\n}\ntemplate \nauto to_hint(identity hint) {\n return hint;\n}\n\ntemplate \nauto supplier_of(Args&&... args) {\n return [values = std::make_tuple(std::forward(args)...)](\n auto&& promise) mutable {\n cti::detail::traits::unpack(std::move(values), [&](auto&&... passed) {\n promise.set_value(std::forward(passed)...);\n });\n };\n}\n\ntemplate \nauto exception_supplier_of(Arg&& arg) {\n return [arg = std::forward(arg)](auto&& promise) mutable {\n promise.set_exception(std::move(arg));\n };\n}\n\ntemplate \nclass continuation_provider : public ::testing::Test, public Provider {\npublic:\n template \n auto invoke(T&& type) {\n return this->make(identity<>{}, identity{},\n [type = std::forward(type)](auto&& promise) mutable {\n promise.set_value();\n });\n }\n\n template \n auto supply(Args&&... args) {\n identity...> arg_types;\n auto hint_types = to_hint(arg_types);\n\n return this->make(arg_types, hint_types,\n supplier_of(std::forward(args)...));\n }\n\n template \n auto supply_exception(Arg&& arg) {\n identity<> arg_types;\n auto hint_types = to_hint(arg_types);\n\n return this->make(arg_types, hint_types,\n exception_supplier_of(std::forward(arg)));\n }\n};\n\ninline auto empty_caller() {\n return [](auto&& promise) { promise.set_value(); };\n}\n\ninline auto empty_continuable() {\n return cti::make_continuable(empty_caller());\n}\n\nstruct provide_copyable {\n template \n auto make(identity, identity, T&& callback) {\n return cti::make_continuable(std::forward(callback));\n }\n};\n\nstruct provide_unique {\n template \n auto make(identity, identity, T&& callback) {\n return cti::make_continuable([\n callback = std::forward(callback), guard = std::make_unique(0)\n ](auto&&... args) mutable {\n (void)(*guard);\n return std::move(callback)(std::forward(args)...);\n });\n }\n};\n\ntemplate