text
stringlengths
54
60.6k
<commit_before>#include "FAST/Tests/catch.hpp" #include "TubeSegmentationAndCenterlineExtraction.hpp" #include "FAST/Importers/ImageFileImporter.hpp" #include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp" #include "FAST/Visualization/LineRenderer/LineRenderer.hpp" #include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp" #include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp" #include "FAST/Visualization/SimpleWindow.hpp" namespace fast { TEST_CASE("TSF", "[tsf]") { ImageFileImporter::pointer importer = ImageFileImporter::New(); importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd"); TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New(); tubeExtraction->setInputConnection(importer->getOutputPort()); tubeExtraction->extractBrightTubes(); tubeExtraction->setMinimumRadius(0.5); tubeExtraction->setMaximumRadius(8); tubeExtraction->setSensitivity(0.99); SliceRenderer::pointer renderer = SliceRenderer::New(); renderer->setInputConnection(tubeExtraction->getTDFOutputPort()); LineRenderer::pointer lineRenderer = LineRenderer::New(); lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort()); lineRenderer->setDefaultDrawOnTop(true); SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New(); surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort()); MeshRenderer::pointer meshRenderer = MeshRenderer::New(); meshRenderer->addInputConnection(surfaceExtraction->getOutputPort()); SimpleWindow::pointer window = SimpleWindow::New(); window->addRenderer(renderer); window->addRenderer(meshRenderer); window->addRenderer(lineRenderer); window->start(); } /* TEST_CASE("TSF Airway", "[tsf][airway]") { Report::setReportMethod(Report::COUT); ImageFileImporter::pointer importer = ImageFileImporter::New(); //importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd"); importer->setFilename("/home/smistad/Dropbox/CT-Thorax-cropped.mhd"); TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New(); tubeExtraction->setInputConnection(importer->getOutputPort()); tubeExtraction->extractDarkTubes(); tubeExtraction->setMinimumIntensity(-1024); tubeExtraction->setMaximumIntensity(100); tubeExtraction->setMinimumRadius(3); tubeExtraction->setMaximumRadius(30); tubeExtraction->setSensitivity(0.85); SliceRenderer::pointer renderer = SliceRenderer::New(); renderer->setInputConnection(tubeExtraction->getTDFOutputPort()); LineRenderer::pointer lineRenderer = LineRenderer::New(); lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort()); lineRenderer->setDefaultDrawOnTop(true); SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New(); surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort()); MeshRenderer::pointer meshRenderer = MeshRenderer::New(); meshRenderer->addInputConnection(surfaceExtraction->getOutputPort()); SimpleWindow::pointer window = SimpleWindow::New(); window->addRenderer(renderer); window->addRenderer(meshRenderer); window->addRenderer(lineRenderer); window->start(); } */ } <commit_msg>comment out tsf tests for now<commit_after>#include "FAST/Tests/catch.hpp" #include "TubeSegmentationAndCenterlineExtraction.hpp" #include "FAST/Importers/ImageFileImporter.hpp" #include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp" #include "FAST/Visualization/LineRenderer/LineRenderer.hpp" #include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp" #include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp" #include "FAST/Visualization/SimpleWindow.hpp" namespace fast { /* TEST_CASE("TSF", "[tsf]") { ImageFileImporter::pointer importer = ImageFileImporter::New(); importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd"); TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New(); tubeExtraction->setInputConnection(importer->getOutputPort()); tubeExtraction->extractBrightTubes(); tubeExtraction->setMinimumRadius(0.5); tubeExtraction->setMaximumRadius(8); tubeExtraction->setSensitivity(0.99); SliceRenderer::pointer renderer = SliceRenderer::New(); renderer->setInputConnection(tubeExtraction->getTDFOutputPort()); LineRenderer::pointer lineRenderer = LineRenderer::New(); lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort()); lineRenderer->setDefaultDrawOnTop(true); SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New(); surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort()); MeshRenderer::pointer meshRenderer = MeshRenderer::New(); meshRenderer->addInputConnection(surfaceExtraction->getOutputPort()); SimpleWindow::pointer window = SimpleWindow::New(); window->addRenderer(renderer); window->addRenderer(meshRenderer); window->addRenderer(lineRenderer); window->start(); } TEST_CASE("TSF Airway", "[tsf][airway]") { Report::setReportMethod(Report::COUT); ImageFileImporter::pointer importer = ImageFileImporter::New(); //importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd"); importer->setFilename("/home/smistad/Dropbox/CT-Thorax-cropped.mhd"); TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New(); tubeExtraction->setInputConnection(importer->getOutputPort()); tubeExtraction->extractDarkTubes(); tubeExtraction->setMinimumIntensity(-1024); tubeExtraction->setMaximumIntensity(100); tubeExtraction->setMinimumRadius(3); tubeExtraction->setMaximumRadius(30); tubeExtraction->setSensitivity(0.85); SliceRenderer::pointer renderer = SliceRenderer::New(); renderer->setInputConnection(tubeExtraction->getTDFOutputPort()); LineRenderer::pointer lineRenderer = LineRenderer::New(); lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort()); lineRenderer->setDefaultDrawOnTop(true); SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New(); surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort()); MeshRenderer::pointer meshRenderer = MeshRenderer::New(); meshRenderer->addInputConnection(surfaceExtraction->getOutputPort()); SimpleWindow::pointer window = SimpleWindow::New(); window->addRenderer(renderer); window->addRenderer(meshRenderer); window->addRenderer(lineRenderer); window->start(); } */ } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/plugin_updater.h" #include <string> #include <vector> #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/plugin_group.h" #include "chrome/common/pref_names.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/webplugininfo.h" namespace plugin_updater { // Convert to a List of Groups static void GetPluginGroups( std::vector<linked_ptr<PluginGroup> >* plugin_groups) { // Read all plugins and convert them to plugin groups std::vector<WebPluginInfo> web_plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &web_plugins); // We first search for an existing group that matches our name, // and only create a new group if we can't find any. for (size_t i = 0; i < web_plugins.size(); ++i) { const WebPluginInfo& web_plugin = web_plugins[i]; PluginGroup* group = PluginGroup::FindGroupMatchingPlugin( *plugin_groups, web_plugin); if (!group) { group = PluginGroup::FindHardcodedPluginGroup(web_plugin); plugin_groups->push_back(linked_ptr<PluginGroup>(group)); } group->AddPlugin(web_plugin, i); } } static DictionaryValue* CreatePluginFileSummary( const WebPluginInfo& plugin) { DictionaryValue* data = new DictionaryValue(); data->SetString(L"path", plugin.path.value()); data->SetStringFromUTF16(L"name", plugin.name); data->SetStringFromUTF16(L"version", plugin.version); data->SetBoolean(L"enabled", plugin.enabled); return data; } ListValue* GetPluginGroupsData() { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); // Construct DictionaryValues to return to the UI ListValue* plugin_groups_data = new ListValue(); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { plugin_groups_data->Append((*it)->GetDataForUI()); } return plugin_groups_data; } void EnablePluginGroup(bool enable, const string16& group_name) { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->GetGroupName() == group_name) { (*it)->Enable(enable); } } } void EnablePluginFile(bool enable, const FilePath::StringType& path) { FilePath file_path(path); if (enable && !PluginGroup::IsPluginPathDisabledByPolicy(file_path)) NPAPI::PluginList::Singleton()->EnablePlugin(file_path); else NPAPI::PluginList::Singleton()->DisablePlugin(file_path); } #if defined(OS_CHROMEOS) static bool enable_internal_pdf_ = true; #else static bool enable_internal_pdf_ = false; #endif void DisablePluginGroupsFromPrefs(Profile* profile) { bool update_internal_dir = false; FilePath last_internal_dir = profile->GetPrefs()->GetFilePath(prefs::kPluginsLastInternalDirectory); FilePath cur_internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &cur_internal_dir) && cur_internal_dir != last_internal_dir) { update_internal_dir = true; profile->GetPrefs()->SetFilePath( prefs::kPluginsLastInternalDirectory, cur_internal_dir); } bool found_internal_pdf = false; bool force_enable_internal_pdf = false; FilePath pdf_path; PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path); FilePath::StringType pdf_path_str = pdf_path.value(); if (enable_internal_pdf_ && !profile->GetPrefs()->GetBoolean(prefs::kPluginsEnabledInternalPDF)) { // We switched to the internal pdf plugin being on by default, and so we // need to force it to be enabled. We only want to do it this once though, // i.e. we don't want to enable it again if the user disables it afterwards. profile->GetPrefs()->SetBoolean(prefs::kPluginsEnabledInternalPDF, true); force_enable_internal_pdf = true; } if (ListValue* saved_plugins_list = profile->GetPrefs()->GetMutableList(prefs::kPluginsPluginsList)) { for (ListValue::const_iterator it = saved_plugins_list->begin(); it != saved_plugins_list->end(); ++it) { if (!(*it)->IsType(Value::TYPE_DICTIONARY)) { LOG(WARNING) << "Invalid entry in " << prefs::kPluginsPluginsList; continue; // Oops, don't know what to do with this item. } DictionaryValue* plugin = static_cast<DictionaryValue*>(*it); string16 group_name; bool enabled = true; plugin->GetBoolean(L"enabled", &enabled); FilePath::StringType path; // The plugin list constains all the plugin files in addition to the // plugin groups. if (plugin->GetString(L"path", &path)) { // Files have a path attribute, groups don't. FilePath plugin_path(path); if (update_internal_dir && FilePath::CompareIgnoreCase(plugin_path.DirName().value(), last_internal_dir.value()) == 0) { // If the internal plugin directory has changed and if the plugin // looks internal, update its path in the prefs. plugin_path = cur_internal_dir.Append(plugin_path.BaseName()); path = plugin_path.value(); plugin->SetString(L"path", path); } if (FilePath::CompareIgnoreCase(path, pdf_path_str) == 0) { found_internal_pdf = true; if (!enabled && force_enable_internal_pdf) { enabled = true; plugin->SetBoolean(L"enabled", true); } } if (!enabled) NPAPI::PluginList::Singleton()->DisablePlugin(plugin_path); } else if (!enabled && plugin->GetStringAsUTF16(L"name", &group_name)) { // Otherwise this is a list of groups. EnablePluginGroup(false, group_name); } } } // Build the set of policy-disabled plugins once and cache it. // Don't do this in the constructor, there's no profile available there. std::set<string16> policy_disabled_plugins; const ListValue* plugin_blacklist = profile->GetPrefs()->GetList(prefs::kPluginsPluginsBlacklist); if (plugin_blacklist) { ListValue::const_iterator end(plugin_blacklist->end()); for (ListValue::const_iterator current(plugin_blacklist->begin()); current != end; ++current) { string16 plugin_name; if ((*current)->GetAsUTF16(&plugin_name)) { policy_disabled_plugins.insert(plugin_name); } } } PluginGroup::SetPolicyDisabledPluginSet(policy_disabled_plugins); // Disable all of the plugins and plugin groups that are disabled by policy. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (PluginGroup::IsPluginNameDisabledByPolicy(it->name)) NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); std::vector<linked_ptr<PluginGroup> >::const_iterator it; for (it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { string16 current_group_name = (*it)->GetGroupName(); if (PluginGroup::IsPluginNameDisabledByPolicy(current_group_name)) EnablePluginGroup(false, current_group_name); } if (!enable_internal_pdf_ && !found_internal_pdf) { // The internal PDF plugin is disabled by default, and the user hasn't // overridden the default. NPAPI::PluginList::Singleton()->DisablePlugin(pdf_path); } } void UpdatePreferences(Profile* profile) { ListValue* plugins_list = profile->GetPrefs()->GetMutableList( prefs::kPluginsPluginsList); plugins_list->Clear(); FilePath internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir)) profile->GetPrefs()->SetFilePath(prefs::kPluginsLastInternalDirectory, internal_dir); // Add the plugin files. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { plugins_list->Append(CreatePluginFileSummary(*it)); } // Add the groups as well. std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { // Don't save preferences for vulnerable pugins. if (!(*it)->IsVulnerable()) { plugins_list->Append((*it)->GetSummary()); } } } } // namespace plugin_updater <commit_msg>Enable the pdf plugin by default. Review URL: http://codereview.chromium.org/3028009<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/plugin_updater.h" #include <string> #include <vector> #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/plugin_group.h" #include "chrome/common/pref_names.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/webplugininfo.h" namespace plugin_updater { // Convert to a List of Groups static void GetPluginGroups( std::vector<linked_ptr<PluginGroup> >* plugin_groups) { // Read all plugins and convert them to plugin groups std::vector<WebPluginInfo> web_plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &web_plugins); // We first search for an existing group that matches our name, // and only create a new group if we can't find any. for (size_t i = 0; i < web_plugins.size(); ++i) { const WebPluginInfo& web_plugin = web_plugins[i]; PluginGroup* group = PluginGroup::FindGroupMatchingPlugin( *plugin_groups, web_plugin); if (!group) { group = PluginGroup::FindHardcodedPluginGroup(web_plugin); plugin_groups->push_back(linked_ptr<PluginGroup>(group)); } group->AddPlugin(web_plugin, i); } } static DictionaryValue* CreatePluginFileSummary( const WebPluginInfo& plugin) { DictionaryValue* data = new DictionaryValue(); data->SetString(L"path", plugin.path.value()); data->SetStringFromUTF16(L"name", plugin.name); data->SetStringFromUTF16(L"version", plugin.version); data->SetBoolean(L"enabled", plugin.enabled); return data; } ListValue* GetPluginGroupsData() { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); // Construct DictionaryValues to return to the UI ListValue* plugin_groups_data = new ListValue(); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { plugin_groups_data->Append((*it)->GetDataForUI()); } return plugin_groups_data; } void EnablePluginGroup(bool enable, const string16& group_name) { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->GetGroupName() == group_name) { (*it)->Enable(enable); } } } void EnablePluginFile(bool enable, const FilePath::StringType& path) { FilePath file_path(path); if (enable && !PluginGroup::IsPluginPathDisabledByPolicy(file_path)) NPAPI::PluginList::Singleton()->EnablePlugin(file_path); else NPAPI::PluginList::Singleton()->DisablePlugin(file_path); } static bool enable_internal_pdf_ = true; void DisablePluginGroupsFromPrefs(Profile* profile) { bool update_internal_dir = false; FilePath last_internal_dir = profile->GetPrefs()->GetFilePath(prefs::kPluginsLastInternalDirectory); FilePath cur_internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &cur_internal_dir) && cur_internal_dir != last_internal_dir) { update_internal_dir = true; profile->GetPrefs()->SetFilePath( prefs::kPluginsLastInternalDirectory, cur_internal_dir); } bool found_internal_pdf = false; bool force_enable_internal_pdf = false; FilePath pdf_path; PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path); FilePath::StringType pdf_path_str = pdf_path.value(); if (enable_internal_pdf_ && !profile->GetPrefs()->GetBoolean(prefs::kPluginsEnabledInternalPDF)) { // We switched to the internal pdf plugin being on by default, and so we // need to force it to be enabled. We only want to do it this once though, // i.e. we don't want to enable it again if the user disables it afterwards. profile->GetPrefs()->SetBoolean(prefs::kPluginsEnabledInternalPDF, true); force_enable_internal_pdf = true; } if (ListValue* saved_plugins_list = profile->GetPrefs()->GetMutableList(prefs::kPluginsPluginsList)) { for (ListValue::const_iterator it = saved_plugins_list->begin(); it != saved_plugins_list->end(); ++it) { if (!(*it)->IsType(Value::TYPE_DICTIONARY)) { LOG(WARNING) << "Invalid entry in " << prefs::kPluginsPluginsList; continue; // Oops, don't know what to do with this item. } DictionaryValue* plugin = static_cast<DictionaryValue*>(*it); string16 group_name; bool enabled = true; plugin->GetBoolean(L"enabled", &enabled); FilePath::StringType path; // The plugin list constains all the plugin files in addition to the // plugin groups. if (plugin->GetString(L"path", &path)) { // Files have a path attribute, groups don't. FilePath plugin_path(path); if (update_internal_dir && FilePath::CompareIgnoreCase(plugin_path.DirName().value(), last_internal_dir.value()) == 0) { // If the internal plugin directory has changed and if the plugin // looks internal, update its path in the prefs. plugin_path = cur_internal_dir.Append(plugin_path.BaseName()); path = plugin_path.value(); plugin->SetString(L"path", path); } if (FilePath::CompareIgnoreCase(path, pdf_path_str) == 0) { found_internal_pdf = true; if (!enabled && force_enable_internal_pdf) { enabled = true; plugin->SetBoolean(L"enabled", true); } } if (!enabled) NPAPI::PluginList::Singleton()->DisablePlugin(plugin_path); } else if (!enabled && plugin->GetStringAsUTF16(L"name", &group_name)) { // Otherwise this is a list of groups. EnablePluginGroup(false, group_name); } } } // Build the set of policy-disabled plugins once and cache it. // Don't do this in the constructor, there's no profile available there. std::set<string16> policy_disabled_plugins; const ListValue* plugin_blacklist = profile->GetPrefs()->GetList(prefs::kPluginsPluginsBlacklist); if (plugin_blacklist) { ListValue::const_iterator end(plugin_blacklist->end()); for (ListValue::const_iterator current(plugin_blacklist->begin()); current != end; ++current) { string16 plugin_name; if ((*current)->GetAsUTF16(&plugin_name)) { policy_disabled_plugins.insert(plugin_name); } } } PluginGroup::SetPolicyDisabledPluginSet(policy_disabled_plugins); // Disable all of the plugins and plugin groups that are disabled by policy. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (PluginGroup::IsPluginNameDisabledByPolicy(it->name)) NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); std::vector<linked_ptr<PluginGroup> >::const_iterator it; for (it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { string16 current_group_name = (*it)->GetGroupName(); if (PluginGroup::IsPluginNameDisabledByPolicy(current_group_name)) EnablePluginGroup(false, current_group_name); } if (!enable_internal_pdf_ && !found_internal_pdf) { // The internal PDF plugin is disabled by default, and the user hasn't // overridden the default. NPAPI::PluginList::Singleton()->DisablePlugin(pdf_path); } } void UpdatePreferences(Profile* profile) { ListValue* plugins_list = profile->GetPrefs()->GetMutableList( prefs::kPluginsPluginsList); plugins_list->Clear(); FilePath internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir)) profile->GetPrefs()->SetFilePath(prefs::kPluginsLastInternalDirectory, internal_dir); // Add the plugin files. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { plugins_list->Append(CreatePluginFileSummary(*it)); } // Add the groups as well. std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { // Don't save preferences for vulnerable pugins. if (!(*it)->IsVulnerable()) { plugins_list->Append((*it)->GetSummary()); } } } } // namespace plugin_updater <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/usb/usb_device.h" #include "base/stl_util.h" #include "base/synchronization/lock.h" #include "chrome/browser/usb/usb_service.h" #include "third_party/libusb/libusb.h" namespace { static uint8 ConvertTransferDirection( const UsbDevice::TransferDirection direction) { switch (direction) { case UsbDevice::INBOUND: return LIBUSB_ENDPOINT_IN; case UsbDevice::OUTBOUND: return LIBUSB_ENDPOINT_OUT; } NOTREACHED(); return LIBUSB_ENDPOINT_OUT; } static uint8 CreateRequestType(const UsbDevice::TransferDirection direction, const UsbDevice::TransferRequestType request_type, const UsbDevice::TransferRecipient recipient) { uint8 result = ConvertTransferDirection(direction); switch (request_type) { case UsbDevice::STANDARD: result |= LIBUSB_REQUEST_TYPE_STANDARD; break; case UsbDevice::CLASS: result |= LIBUSB_REQUEST_TYPE_CLASS; break; case UsbDevice::VENDOR: result |= LIBUSB_REQUEST_TYPE_VENDOR; break; case UsbDevice::RESERVED: result |= LIBUSB_REQUEST_TYPE_RESERVED; break; } switch (recipient) { case UsbDevice::DEVICE: result |= LIBUSB_RECIPIENT_DEVICE; break; case UsbDevice::INTERFACE: result |= LIBUSB_RECIPIENT_INTERFACE; break; case UsbDevice::ENDPOINT: result |= LIBUSB_RECIPIENT_ENDPOINT; break; case UsbDevice::OTHER: result |= LIBUSB_RECIPIENT_OTHER; break; } return result; } static UsbTransferStatus ConvertTransferStatus( const libusb_transfer_status status) { switch (status) { case LIBUSB_TRANSFER_COMPLETED: return USB_TRANSFER_COMPLETED; case LIBUSB_TRANSFER_ERROR: return USB_TRANSFER_ERROR; case LIBUSB_TRANSFER_TIMED_OUT: return USB_TRANSFER_TIMEOUT; case LIBUSB_TRANSFER_STALL: return USB_TRANSFER_STALLED; case LIBUSB_TRANSFER_NO_DEVICE: return USB_TRANSFER_DISCONNECT; case LIBUSB_TRANSFER_OVERFLOW: return USB_TRANSFER_OVERFLOW; case LIBUSB_TRANSFER_CANCELLED: return USB_TRANSFER_CANCELLED; } NOTREACHED(); return USB_TRANSFER_ERROR; } static void HandleTransferCompletion(struct libusb_transfer* transfer) { UsbDevice* const device = reinterpret_cast<UsbDevice*>(transfer->user_data); device->TransferComplete(transfer); } } // namespace UsbDevice::Transfer::Transfer() {} UsbDevice::Transfer::~Transfer() {} UsbDevice::UsbDevice(UsbService* service, PlatformUsbDeviceHandle handle) : service_(service), handle_(handle) { DCHECK(handle) << "Cannot create device with NULL handle."; } UsbDevice::UsbDevice() : service_(NULL), handle_(NULL) {} UsbDevice::~UsbDevice() {} void UsbDevice::Close(const base::Callback<void()>& callback) { CheckDevice(); service_->CloseDevice(this); handle_ = NULL; callback.Run(); } void UsbDevice::TransferComplete(PlatformUsbTransferHandle handle) { base::AutoLock lock(lock_); // TODO(gdk): Handle device disconnect. DCHECK(ContainsKey(transfers_, handle)) << "Missing transfer completed"; Transfer* const transfer = &transfers_[handle]; DCHECK(handle->actual_length >= 0) << "Negative actual length received"; size_t actual_length = static_cast<size_t>(std::max(handle->actual_length, 0)); DCHECK(transfer->length >= actual_length) << "data too big for our buffer (libusb failure?)"; scoped_refptr<net::IOBuffer> buffer = transfer->buffer; switch (transfer->transfer_type) { case USB_TRANSFER_CONTROL: // If the transfer is a control transfer we do not expose the control // setup header to the caller. This logic strips off the header if // present before invoking the callback provided with the transfer. if (actual_length > 0) { CHECK(transfer->length >= LIBUSB_CONTROL_SETUP_SIZE) << "buffer was not correctly set: too small for the control header"; if (transfer->length >= actual_length && actual_length >= LIBUSB_CONTROL_SETUP_SIZE) { // If the payload is zero bytes long, pad out the allocated buffer // size to one byte so that an IOBuffer of that size can be allocated. scoped_refptr<net::IOBuffer> resized_buffer = new net::IOBuffer( std::max(actual_length, static_cast<size_t>(1))); memcpy(resized_buffer->data(), buffer->data() + LIBUSB_CONTROL_SETUP_SIZE, actual_length); buffer = resized_buffer; } } break; case USB_TRANSFER_ISOCHRONOUS: // Isochronous replies might carry data in the different isoc packets even // if the transfer actual_data value is zero. Furthermore, not all of the // received packets might contain data, so we need to calculate how many // data bytes we are effectively providing and pack the results. if (actual_length == 0) { size_t packet_buffer_start = 0; for (int i = 0; i < handle->num_iso_packets; ++i) { PlatformUsbIsoPacketDescriptor packet = &handle->iso_packet_desc[i]; if (packet->actual_length > 0) { // We don't need to copy as long as all packets until now provide // all the data the packet can hold. if (actual_length < packet_buffer_start) { CHECK(packet_buffer_start + packet->actual_length <= transfer->length); memmove(buffer->data() + actual_length, buffer->data() + packet_buffer_start, packet->actual_length); } actual_length += packet->actual_length; } packet_buffer_start += packet->length; } } break; case USB_TRANSFER_BULK: case USB_TRANSFER_INTERRUPT: break; default: NOTREACHED() << "Invalid usb transfer type"; } transfer->callback.Run(ConvertTransferStatus(handle->status), buffer, actual_length); transfers_.erase(handle); libusb_free_transfer(handle); } void UsbDevice::ClaimInterface(const int interface_number, const UsbInterfaceCallback& callback) { CheckDevice(); const int claim_result = libusb_claim_interface(handle_, interface_number); callback.Run(claim_result == 0); } void UsbDevice::ReleaseInterface(const int interface_number, const UsbInterfaceCallback& callback) { CheckDevice(); const int release_result = libusb_release_interface(handle_, interface_number); callback.Run(release_result == 0); } void UsbDevice::SetInterfaceAlternateSetting( const int interface_number, const int alternate_setting, const UsbInterfaceCallback& callback) { CheckDevice(); const int setting_result = libusb_set_interface_alt_setting(handle_, interface_number, alternate_setting); callback.Run(setting_result == 0); } void UsbDevice::ControlTransfer(const TransferDirection direction, const TransferRequestType request_type, const TransferRecipient recipient, const uint8 request, const uint16 value, const uint16 index, net::IOBuffer* buffer, const size_t length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); const size_t resized_length = LIBUSB_CONTROL_SETUP_SIZE + length; scoped_refptr<net::IOBuffer> resized_buffer(new net::IOBufferWithSize( resized_length)); memcpy(resized_buffer->data() + LIBUSB_CONTROL_SETUP_SIZE, buffer->data(), length); struct libusb_transfer* const transfer = libusb_alloc_transfer(0); const uint8 converted_type = CreateRequestType(direction, request_type, recipient); libusb_fill_control_setup(reinterpret_cast<uint8*>(resized_buffer->data()), converted_type, request, value, index, length); libusb_fill_control_transfer(transfer, handle_, reinterpret_cast<uint8*>( resized_buffer->data()), reinterpret_cast<libusb_transfer_cb_fn>( &HandleTransferCompletion), this, timeout); SubmitTransfer(transfer, USB_TRANSFER_CONTROL, resized_buffer, resized_length, callback); } void UsbDevice::BulkTransfer(const TransferDirection direction, const uint8 endpoint, net::IOBuffer* buffer, const size_t length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); struct libusb_transfer* const transfer = libusb_alloc_transfer(0); const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint; libusb_fill_bulk_transfer(transfer, handle_, new_endpoint, reinterpret_cast<uint8*>(buffer->data()), length, reinterpret_cast<libusb_transfer_cb_fn>(&HandleTransferCompletion), this, timeout); SubmitTransfer(transfer, USB_TRANSFER_BULK, buffer, length, callback); } void UsbDevice::InterruptTransfer(const TransferDirection direction, const uint8 endpoint, net::IOBuffer* buffer, const size_t length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); struct libusb_transfer* const transfer = libusb_alloc_transfer(0); const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint; libusb_fill_interrupt_transfer(transfer, handle_, new_endpoint, reinterpret_cast<uint8*>(buffer->data()), length, reinterpret_cast<libusb_transfer_cb_fn>(&HandleTransferCompletion), this, timeout); SubmitTransfer(transfer, USB_TRANSFER_INTERRUPT, buffer, length, callback); } void UsbDevice::IsochronousTransfer(const TransferDirection direction, const uint8 endpoint, net::IOBuffer* buffer, const size_t length, const unsigned int packets, const unsigned int packet_length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); const uint64 total_length = packets * packet_length; if (total_length > length) { callback.Run(USB_TRANSFER_LENGTH_SHORT, NULL, 0); return; } struct libusb_transfer* const transfer = libusb_alloc_transfer(packets); const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint; libusb_fill_iso_transfer(transfer, handle_, new_endpoint, reinterpret_cast<uint8*>(buffer->data()), length, packets, reinterpret_cast<libusb_transfer_cb_fn>(&HandleTransferCompletion), this, timeout); libusb_set_iso_packet_lengths(transfer, packet_length); SubmitTransfer(transfer, USB_TRANSFER_ISOCHRONOUS, buffer, length, callback); } void UsbDevice::CheckDevice() { DCHECK(handle_) << "Device is already closed."; } void UsbDevice::SubmitTransfer(PlatformUsbTransferHandle handle, UsbTransferType transfer_type, net::IOBuffer* buffer, const size_t length, const UsbTransferCallback& callback) { Transfer transfer; transfer.transfer_type = transfer_type; transfer.buffer = buffer; transfer.length = length; transfer.callback = callback; { base::AutoLock lock(lock_); transfers_[handle] = transfer; libusb_submit_transfer(handle); } } <commit_msg>[Coverity] Fix uninitialized scalar field.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/usb/usb_device.h" #include "base/stl_util.h" #include "base/synchronization/lock.h" #include "chrome/browser/usb/usb_service.h" #include "third_party/libusb/libusb.h" namespace { static uint8 ConvertTransferDirection( const UsbDevice::TransferDirection direction) { switch (direction) { case UsbDevice::INBOUND: return LIBUSB_ENDPOINT_IN; case UsbDevice::OUTBOUND: return LIBUSB_ENDPOINT_OUT; } NOTREACHED(); return LIBUSB_ENDPOINT_OUT; } static uint8 CreateRequestType(const UsbDevice::TransferDirection direction, const UsbDevice::TransferRequestType request_type, const UsbDevice::TransferRecipient recipient) { uint8 result = ConvertTransferDirection(direction); switch (request_type) { case UsbDevice::STANDARD: result |= LIBUSB_REQUEST_TYPE_STANDARD; break; case UsbDevice::CLASS: result |= LIBUSB_REQUEST_TYPE_CLASS; break; case UsbDevice::VENDOR: result |= LIBUSB_REQUEST_TYPE_VENDOR; break; case UsbDevice::RESERVED: result |= LIBUSB_REQUEST_TYPE_RESERVED; break; } switch (recipient) { case UsbDevice::DEVICE: result |= LIBUSB_RECIPIENT_DEVICE; break; case UsbDevice::INTERFACE: result |= LIBUSB_RECIPIENT_INTERFACE; break; case UsbDevice::ENDPOINT: result |= LIBUSB_RECIPIENT_ENDPOINT; break; case UsbDevice::OTHER: result |= LIBUSB_RECIPIENT_OTHER; break; } return result; } static UsbTransferStatus ConvertTransferStatus( const libusb_transfer_status status) { switch (status) { case LIBUSB_TRANSFER_COMPLETED: return USB_TRANSFER_COMPLETED; case LIBUSB_TRANSFER_ERROR: return USB_TRANSFER_ERROR; case LIBUSB_TRANSFER_TIMED_OUT: return USB_TRANSFER_TIMEOUT; case LIBUSB_TRANSFER_STALL: return USB_TRANSFER_STALLED; case LIBUSB_TRANSFER_NO_DEVICE: return USB_TRANSFER_DISCONNECT; case LIBUSB_TRANSFER_OVERFLOW: return USB_TRANSFER_OVERFLOW; case LIBUSB_TRANSFER_CANCELLED: return USB_TRANSFER_CANCELLED; } NOTREACHED(); return USB_TRANSFER_ERROR; } static void HandleTransferCompletion(struct libusb_transfer* transfer) { UsbDevice* const device = reinterpret_cast<UsbDevice*>(transfer->user_data); device->TransferComplete(transfer); } } // namespace UsbDevice::Transfer::Transfer() : length(0) {} UsbDevice::Transfer::~Transfer() {} UsbDevice::UsbDevice(UsbService* service, PlatformUsbDeviceHandle handle) : service_(service), handle_(handle) { DCHECK(handle) << "Cannot create device with NULL handle."; } UsbDevice::UsbDevice() : service_(NULL), handle_(NULL) {} UsbDevice::~UsbDevice() {} void UsbDevice::Close(const base::Callback<void()>& callback) { CheckDevice(); service_->CloseDevice(this); handle_ = NULL; callback.Run(); } void UsbDevice::TransferComplete(PlatformUsbTransferHandle handle) { base::AutoLock lock(lock_); // TODO(gdk): Handle device disconnect. DCHECK(ContainsKey(transfers_, handle)) << "Missing transfer completed"; Transfer* const transfer = &transfers_[handle]; DCHECK(handle->actual_length >= 0) << "Negative actual length received"; size_t actual_length = static_cast<size_t>(std::max(handle->actual_length, 0)); DCHECK(transfer->length >= actual_length) << "data too big for our buffer (libusb failure?)"; scoped_refptr<net::IOBuffer> buffer = transfer->buffer; switch (transfer->transfer_type) { case USB_TRANSFER_CONTROL: // If the transfer is a control transfer we do not expose the control // setup header to the caller. This logic strips off the header if // present before invoking the callback provided with the transfer. if (actual_length > 0) { CHECK(transfer->length >= LIBUSB_CONTROL_SETUP_SIZE) << "buffer was not correctly set: too small for the control header"; if (transfer->length >= actual_length && actual_length >= LIBUSB_CONTROL_SETUP_SIZE) { // If the payload is zero bytes long, pad out the allocated buffer // size to one byte so that an IOBuffer of that size can be allocated. scoped_refptr<net::IOBuffer> resized_buffer = new net::IOBuffer( std::max(actual_length, static_cast<size_t>(1))); memcpy(resized_buffer->data(), buffer->data() + LIBUSB_CONTROL_SETUP_SIZE, actual_length); buffer = resized_buffer; } } break; case USB_TRANSFER_ISOCHRONOUS: // Isochronous replies might carry data in the different isoc packets even // if the transfer actual_data value is zero. Furthermore, not all of the // received packets might contain data, so we need to calculate how many // data bytes we are effectively providing and pack the results. if (actual_length == 0) { size_t packet_buffer_start = 0; for (int i = 0; i < handle->num_iso_packets; ++i) { PlatformUsbIsoPacketDescriptor packet = &handle->iso_packet_desc[i]; if (packet->actual_length > 0) { // We don't need to copy as long as all packets until now provide // all the data the packet can hold. if (actual_length < packet_buffer_start) { CHECK(packet_buffer_start + packet->actual_length <= transfer->length); memmove(buffer->data() + actual_length, buffer->data() + packet_buffer_start, packet->actual_length); } actual_length += packet->actual_length; } packet_buffer_start += packet->length; } } break; case USB_TRANSFER_BULK: case USB_TRANSFER_INTERRUPT: break; default: NOTREACHED() << "Invalid usb transfer type"; } transfer->callback.Run(ConvertTransferStatus(handle->status), buffer, actual_length); transfers_.erase(handle); libusb_free_transfer(handle); } void UsbDevice::ClaimInterface(const int interface_number, const UsbInterfaceCallback& callback) { CheckDevice(); const int claim_result = libusb_claim_interface(handle_, interface_number); callback.Run(claim_result == 0); } void UsbDevice::ReleaseInterface(const int interface_number, const UsbInterfaceCallback& callback) { CheckDevice(); const int release_result = libusb_release_interface(handle_, interface_number); callback.Run(release_result == 0); } void UsbDevice::SetInterfaceAlternateSetting( const int interface_number, const int alternate_setting, const UsbInterfaceCallback& callback) { CheckDevice(); const int setting_result = libusb_set_interface_alt_setting(handle_, interface_number, alternate_setting); callback.Run(setting_result == 0); } void UsbDevice::ControlTransfer(const TransferDirection direction, const TransferRequestType request_type, const TransferRecipient recipient, const uint8 request, const uint16 value, const uint16 index, net::IOBuffer* buffer, const size_t length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); const size_t resized_length = LIBUSB_CONTROL_SETUP_SIZE + length; scoped_refptr<net::IOBuffer> resized_buffer(new net::IOBufferWithSize( resized_length)); memcpy(resized_buffer->data() + LIBUSB_CONTROL_SETUP_SIZE, buffer->data(), length); struct libusb_transfer* const transfer = libusb_alloc_transfer(0); const uint8 converted_type = CreateRequestType(direction, request_type, recipient); libusb_fill_control_setup(reinterpret_cast<uint8*>(resized_buffer->data()), converted_type, request, value, index, length); libusb_fill_control_transfer(transfer, handle_, reinterpret_cast<uint8*>( resized_buffer->data()), reinterpret_cast<libusb_transfer_cb_fn>( &HandleTransferCompletion), this, timeout); SubmitTransfer(transfer, USB_TRANSFER_CONTROL, resized_buffer, resized_length, callback); } void UsbDevice::BulkTransfer(const TransferDirection direction, const uint8 endpoint, net::IOBuffer* buffer, const size_t length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); struct libusb_transfer* const transfer = libusb_alloc_transfer(0); const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint; libusb_fill_bulk_transfer(transfer, handle_, new_endpoint, reinterpret_cast<uint8*>(buffer->data()), length, reinterpret_cast<libusb_transfer_cb_fn>(&HandleTransferCompletion), this, timeout); SubmitTransfer(transfer, USB_TRANSFER_BULK, buffer, length, callback); } void UsbDevice::InterruptTransfer(const TransferDirection direction, const uint8 endpoint, net::IOBuffer* buffer, const size_t length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); struct libusb_transfer* const transfer = libusb_alloc_transfer(0); const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint; libusb_fill_interrupt_transfer(transfer, handle_, new_endpoint, reinterpret_cast<uint8*>(buffer->data()), length, reinterpret_cast<libusb_transfer_cb_fn>(&HandleTransferCompletion), this, timeout); SubmitTransfer(transfer, USB_TRANSFER_INTERRUPT, buffer, length, callback); } void UsbDevice::IsochronousTransfer(const TransferDirection direction, const uint8 endpoint, net::IOBuffer* buffer, const size_t length, const unsigned int packets, const unsigned int packet_length, const unsigned int timeout, const UsbTransferCallback& callback) { CheckDevice(); const uint64 total_length = packets * packet_length; if (total_length > length) { callback.Run(USB_TRANSFER_LENGTH_SHORT, NULL, 0); return; } struct libusb_transfer* const transfer = libusb_alloc_transfer(packets); const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint; libusb_fill_iso_transfer(transfer, handle_, new_endpoint, reinterpret_cast<uint8*>(buffer->data()), length, packets, reinterpret_cast<libusb_transfer_cb_fn>(&HandleTransferCompletion), this, timeout); libusb_set_iso_packet_lengths(transfer, packet_length); SubmitTransfer(transfer, USB_TRANSFER_ISOCHRONOUS, buffer, length, callback); } void UsbDevice::CheckDevice() { DCHECK(handle_) << "Device is already closed."; } void UsbDevice::SubmitTransfer(PlatformUsbTransferHandle handle, UsbTransferType transfer_type, net::IOBuffer* buffer, const size_t length, const UsbTransferCallback& callback) { Transfer transfer; transfer.transfer_type = transfer_type; transfer.buffer = buffer; transfer.length = length; transfer.callback = callback; { base::AutoLock lock(lock_); transfers_[handle] = transfer; libusb_submit_transfer(handle); } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/resource_bundle.h" #include <atlbase.h> #include "base/file_util.h" #include "base/gfx/png_decoder.h" #include "base/logging.h" #include "base/path_service.h" #include "base/resource_util.h" #include "base/scoped_ptr.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/win_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/gfx/chrome_font.h" #include "chrome/common/l10n_util.h" #include "chrome/common/win_util.h" #include "SkBitmap.h" using namespace std; ResourceBundle *ResourceBundle::g_shared_instance_ = NULL; // Returns the flags that should be passed to LoadLibraryEx. DWORD GetDataDllLoadFlags() { if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; return 0; } /* static */ void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) { DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice"; g_shared_instance_ = new ResourceBundle(); g_shared_instance_->LoadLocaleResources(pref_locale); } /* static */ void ResourceBundle::CleanupSharedInstance() { if (g_shared_instance_) { delete g_shared_instance_; g_shared_instance_ = NULL; } } /* static */ ResourceBundle& ResourceBundle::GetSharedInstance() { // Must call InitSharedInstance before this function. CHECK(g_shared_instance_ != NULL); return *g_shared_instance_; } ResourceBundle::ResourceBundle() : locale_resources_dll_(NULL), theme_dll_(NULL) { } ResourceBundle::~ResourceBundle() { for (SkImageMap::iterator i = skia_images_.begin(); i != skia_images_.end(); i++) { delete i->second; } skia_images_.clear(); if (locale_resources_dll_) { BOOL rv = FreeLibrary(locale_resources_dll_); DCHECK(rv); } if (theme_dll_) { BOOL rv = FreeLibrary(theme_dll_); DCHECK(rv); } } void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) { DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded"; const std::wstring& locale_path = GetLocaleDllPath(pref_locale); if (locale_path.empty()) { // It's possible that there are no locale dlls found, in which case we just // return. NOTREACHED(); return; } // The dll should only have resources, not executable code. locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL, GetDataDllLoadFlags()); DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources"; } std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) { std::wstring locale_path; PathService::Get(chrome::DIR_LOCALES, &locale_path); const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale); if (app_locale.empty()) return app_locale; file_util::AppendToPath(&locale_path, app_locale + L".dll"); return locale_path; } void ResourceBundle::LoadThemeResources() { DCHECK(NULL == theme_dll_) << "theme dll already loaded"; std::wstring theme_dll_path; PathService::Get(chrome::DIR_THEMES, &theme_dll_path); file_util::AppendToPath(&theme_dll_path, L"default.dll"); // The dll should only have resources, not executable code. theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL, GetDataDllLoadFlags()); DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path; } /* static */ SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) { void* data_ptr = NULL; size_t data_size; bool success = base::GetDataResourceFromModule(dll_inst, resource_id, &data_ptr, &data_size); if (!success) return NULL; unsigned char* data = static_cast<unsigned char*>(data_ptr); // Decode the PNG. vector<unsigned char> png_data; int image_width; int image_height; if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA, &png_data, &image_width, &image_height)) { NOTREACHED() << "Unable to decode theme resource " << resource_id; return NULL; } return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data, image_width, image_height); } SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) { AutoLock lock_scope(lock_); SkImageMap::const_iterator found = skia_images_.find(resource_id); SkBitmap* bitmap = NULL; // If not found load and store the image if (found == skia_images_.end()) { // Load the image bitmap = LoadBitmap(theme_dll_, resource_id); // We did not find the bitmap in the theme DLL, try the current one. if (!bitmap) bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id); skia_images_[resource_id] = bitmap; } else { bitmap = found->second; } // This bitmap will be returned when a bitmap is requested that can not be // found. The data inside is lazily initialized, so users must lock and static SkBitmap* empty_bitmap = NULL; // Handle the case where loading the bitmap failed. if (!bitmap) { LOG(WARNING) << "Unable to load bitmap with id " << resource_id; if (!empty_bitmap) { empty_bitmap = new SkBitmap(); } return empty_bitmap; } return bitmap; } bool ResourceBundle::LoadImageResourceBytes(int resource_id, vector<unsigned char>* bytes) { return LoadModuleResourceBytes(theme_dll_, resource_id, bytes); } bool ResourceBundle::LoadDataResourceBytes(int resource_id, vector<unsigned char>* bytes) { return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(), resource_id, bytes); } bool ResourceBundle::LoadModuleResourceBytes( HINSTANCE module, int resource_id, std::vector<unsigned char>* bytes) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(module, resource_id, &data_ptr, &data_size)) { bytes->resize(data_size); memcpy(&(bytes->front()), data_ptr, data_size); return true; } else { return false; } } HICON ResourceBundle::LoadThemeIcon(int icon_id) { return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id)); } std::string ResourceBundle::GetDataResource(int resource_id) { return GetRawDataResource(resource_id).as_string(); } StringPiece ResourceBundle::GetRawDataResource(int resource_id) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule( _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size)) return StringPiece(static_cast<const char*>(data_ptr), data_size); return StringPiece(); } // Loads and returns the global accelerators from the current module. HACCEL ResourceBundle::GetGlobalAccelerators() { return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(IDR_MAINFRAME)); } // Loads and returns a cursor from the current module. HCURSOR ResourceBundle::LoadCursor(int cursor_id) { return ::LoadCursor(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(cursor_id)); } std::wstring ResourceBundle::GetLocalizedString(int message_id) { // If for some reason we were unable to load a resource dll, return an empty // string (better than crashing). if (!locale_resources_dll_) return std::wstring(); DCHECK(IS_INTRESOURCE(message_id)); // Get a reference directly to the string resource. HINSTANCE hinstance = locale_resources_dll_; const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance, message_id); if (!image) { // Fall back on the current module (shouldn't be any strings here except // in unittests). image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(), message_id); if (!image) { NOTREACHED() << "unable to find resource: " << message_id; return std::wstring(); } } // Copy into a wstring and return. return std::wstring(image->achString, image->nLength); } void ResourceBundle::LoadFontsIfNecessary() { AutoLock lock_scope(lock_); if (!base_font_.get()) { base_font_.reset(new ChromeFont()); small_font_.reset(new ChromeFont()); *small_font_ = base_font_->DeriveFont(-2); medium_font_.reset(new ChromeFont()); *medium_font_ = base_font_->DeriveFont(3); medium_bold_font_.reset(new ChromeFont()); *medium_bold_font_ = base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD); large_font_.reset(new ChromeFont()); *large_font_ = base_font_->DeriveFont(8); web_font_.reset(new ChromeFont()); *web_font_ = base_font_->DeriveFont(1, base_font_->style() | ChromeFont::WEB); } } ChromeFont ResourceBundle::GetFont(FontStyle style) { LoadFontsIfNecessary(); switch(style) { case SmallFont: return *small_font_; case MediumFont: return *medium_font_; case MediumBoldFont: return *medium_bold_font_; case LargeFont: return *large_font_; case WebFont: return *web_font_; default: return *base_font_; } } <commit_msg>Make sure we don't execute code from the theme dll.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/resource_bundle.h" #include <atlbase.h> #include "base/file_util.h" #include "base/gfx/png_decoder.h" #include "base/logging.h" #include "base/path_service.h" #include "base/resource_util.h" #include "base/scoped_ptr.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/win_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/gfx/chrome_font.h" #include "chrome/common/l10n_util.h" #include "chrome/common/win_util.h" #include "SkBitmap.h" using namespace std; ResourceBundle *ResourceBundle::g_shared_instance_ = NULL; // Returns the flags that should be passed to LoadLibraryEx. DWORD GetDataDllLoadFlags() { if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; return LOAD_LIBRARY_AS_DATAFILE; } /* static */ void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) { DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice"; g_shared_instance_ = new ResourceBundle(); g_shared_instance_->LoadLocaleResources(pref_locale); } /* static */ void ResourceBundle::CleanupSharedInstance() { if (g_shared_instance_) { delete g_shared_instance_; g_shared_instance_ = NULL; } } /* static */ ResourceBundle& ResourceBundle::GetSharedInstance() { // Must call InitSharedInstance before this function. CHECK(g_shared_instance_ != NULL); return *g_shared_instance_; } ResourceBundle::ResourceBundle() : locale_resources_dll_(NULL), theme_dll_(NULL) { } ResourceBundle::~ResourceBundle() { for (SkImageMap::iterator i = skia_images_.begin(); i != skia_images_.end(); i++) { delete i->second; } skia_images_.clear(); if (locale_resources_dll_) { BOOL rv = FreeLibrary(locale_resources_dll_); DCHECK(rv); } if (theme_dll_) { BOOL rv = FreeLibrary(theme_dll_); DCHECK(rv); } } void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) { DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded"; const std::wstring& locale_path = GetLocaleDllPath(pref_locale); if (locale_path.empty()) { // It's possible that there are no locale dlls found, in which case we just // return. NOTREACHED(); return; } // The dll should only have resources, not executable code. locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL, GetDataDllLoadFlags()); DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources"; } std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) { std::wstring locale_path; PathService::Get(chrome::DIR_LOCALES, &locale_path); const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale); if (app_locale.empty()) return app_locale; file_util::AppendToPath(&locale_path, app_locale + L".dll"); return locale_path; } void ResourceBundle::LoadThemeResources() { DCHECK(NULL == theme_dll_) << "theme dll already loaded"; std::wstring theme_dll_path; PathService::Get(chrome::DIR_THEMES, &theme_dll_path); file_util::AppendToPath(&theme_dll_path, L"default.dll"); // The dll should only have resources, not executable code. theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL, GetDataDllLoadFlags()); DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path; } /* static */ SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) { void* data_ptr = NULL; size_t data_size; bool success = base::GetDataResourceFromModule(dll_inst, resource_id, &data_ptr, &data_size); if (!success) return NULL; unsigned char* data = static_cast<unsigned char*>(data_ptr); // Decode the PNG. vector<unsigned char> png_data; int image_width; int image_height; if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA, &png_data, &image_width, &image_height)) { NOTREACHED() << "Unable to decode theme resource " << resource_id; return NULL; } return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data, image_width, image_height); } SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) { AutoLock lock_scope(lock_); SkImageMap::const_iterator found = skia_images_.find(resource_id); SkBitmap* bitmap = NULL; // If not found load and store the image if (found == skia_images_.end()) { // Load the image bitmap = LoadBitmap(theme_dll_, resource_id); // We did not find the bitmap in the theme DLL, try the current one. if (!bitmap) bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id); skia_images_[resource_id] = bitmap; } else { bitmap = found->second; } // This bitmap will be returned when a bitmap is requested that can not be // found. The data inside is lazily initialized, so users must lock and static SkBitmap* empty_bitmap = NULL; // Handle the case where loading the bitmap failed. if (!bitmap) { LOG(WARNING) << "Unable to load bitmap with id " << resource_id; if (!empty_bitmap) { empty_bitmap = new SkBitmap(); } return empty_bitmap; } return bitmap; } bool ResourceBundle::LoadImageResourceBytes(int resource_id, vector<unsigned char>* bytes) { return LoadModuleResourceBytes(theme_dll_, resource_id, bytes); } bool ResourceBundle::LoadDataResourceBytes(int resource_id, vector<unsigned char>* bytes) { return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(), resource_id, bytes); } bool ResourceBundle::LoadModuleResourceBytes( HINSTANCE module, int resource_id, std::vector<unsigned char>* bytes) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(module, resource_id, &data_ptr, &data_size)) { bytes->resize(data_size); memcpy(&(bytes->front()), data_ptr, data_size); return true; } else { return false; } } HICON ResourceBundle::LoadThemeIcon(int icon_id) { return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id)); } std::string ResourceBundle::GetDataResource(int resource_id) { return GetRawDataResource(resource_id).as_string(); } StringPiece ResourceBundle::GetRawDataResource(int resource_id) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule( _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size)) return StringPiece(static_cast<const char*>(data_ptr), data_size); return StringPiece(); } // Loads and returns the global accelerators from the current module. HACCEL ResourceBundle::GetGlobalAccelerators() { return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(IDR_MAINFRAME)); } // Loads and returns a cursor from the current module. HCURSOR ResourceBundle::LoadCursor(int cursor_id) { return ::LoadCursor(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(cursor_id)); } std::wstring ResourceBundle::GetLocalizedString(int message_id) { // If for some reason we were unable to load a resource dll, return an empty // string (better than crashing). if (!locale_resources_dll_) return std::wstring(); DCHECK(IS_INTRESOURCE(message_id)); // Get a reference directly to the string resource. HINSTANCE hinstance = locale_resources_dll_; const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance, message_id); if (!image) { // Fall back on the current module (shouldn't be any strings here except // in unittests). image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(), message_id); if (!image) { NOTREACHED() << "unable to find resource: " << message_id; return std::wstring(); } } // Copy into a wstring and return. return std::wstring(image->achString, image->nLength); } void ResourceBundle::LoadFontsIfNecessary() { AutoLock lock_scope(lock_); if (!base_font_.get()) { base_font_.reset(new ChromeFont()); small_font_.reset(new ChromeFont()); *small_font_ = base_font_->DeriveFont(-2); medium_font_.reset(new ChromeFont()); *medium_font_ = base_font_->DeriveFont(3); medium_bold_font_.reset(new ChromeFont()); *medium_bold_font_ = base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD); large_font_.reset(new ChromeFont()); *large_font_ = base_font_->DeriveFont(8); web_font_.reset(new ChromeFont()); *web_font_ = base_font_->DeriveFont(1, base_font_->style() | ChromeFont::WEB); } } ChromeFont ResourceBundle::GetFont(FontStyle style) { LoadFontsIfNecessary(); switch(style) { case SmallFont: return *small_font_; case MediumFont: return *medium_font_; case MediumBoldFont: return *medium_bold_font_; case LargeFont: return *large_font_; case WebFont: return *web_font_; default: return *base_font_; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "update_engine/chrome_browser_proxy_resolver.h" #include <map> #include <string> #include <base/string_util.h> #include <base/strings/string_tokenizer.h> #include <dbus/dbus-glib.h> #include <dbus/dbus-glib-lowlevel.h> #include <google/protobuf/stubs/common.h> #include "update_engine/dbus_constants.h" #include "update_engine/utils.h" namespace chromeos_update_engine { using base::StringTokenizer; using google::protobuf::Closure; using google::protobuf::NewCallback; using std::deque; using std::make_pair; using std::multimap; using std::pair; using std::string; #define LIB_CROS_PROXY_RESOLVE_NAME "ProxyResolved" #define LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE \ "org.chromium.UpdateEngineLibcrosProxyResolvedInterface" const char kLibCrosServiceName[] = "org.chromium.LibCrosService"; const char kLibCrosServicePath[] = "/org/chromium/LibCrosService"; const char kLibCrosServiceInterface[] = "org.chromium.LibCrosServiceInterface"; const char kLibCrosServiceResolveNetworkProxyMethodName[] = "ResolveNetworkProxy"; const char kLibCrosProxyResolveName[] = LIB_CROS_PROXY_RESOLVE_NAME; const char kLibCrosProxyResolveSignalInterface[] = LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE; const char kLibCrosProxyResolveSignalFilter[] = "type='signal', " "interface='" LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE "', " "member='" LIB_CROS_PROXY_RESOLVE_NAME "'"; #undef LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE #undef LIB_CROS_PROXY_RESOLVE_NAME namespace { const int kTimeout = 5; // seconds DBusGProxy* GetProxy(DbusGlibInterface* dbus) { GError* error = NULL; DBusGConnection* bus = dbus->BusGet(DBUS_BUS_SYSTEM, &error); if (!bus) { LOG(ERROR) << "Failed to get bus"; return NULL; } DBusGProxy* proxy = dbus->ProxyNewForNameOwner(bus, kLibCrosServiceName, kLibCrosServicePath, kLibCrosServiceInterface, &error); if (!proxy) { LOG(ERROR) << "Error getting dbus proxy for " << kLibCrosServiceName << ": " << utils::GetAndFreeGError(&error); return NULL; } return proxy; } } // namespace {} ChromeBrowserProxyResolver::ChromeBrowserProxyResolver(DbusGlibInterface* dbus) : dbus_(dbus), proxy_(NULL), timeout_(kTimeout) {} bool ChromeBrowserProxyResolver::Init() { // Set up signal handler. Code lifted from libcros if (proxy_) { // Already initialized return true; } GError* gerror = NULL; DBusGConnection* gbus = dbus_->BusGet(DBUS_BUS_SYSTEM, &gerror); TEST_AND_RETURN_FALSE(gbus); DBusConnection* connection = dbus_->ConnectionGetConnection(gbus); TEST_AND_RETURN_FALSE(connection); DBusError error; dbus_error_init(&error); dbus_->DbusBusAddMatch(connection, kLibCrosProxyResolveSignalFilter, &error); TEST_AND_RETURN_FALSE(!dbus_error_is_set(&error)); TEST_AND_RETURN_FALSE(dbus_->DbusConnectionAddFilter( connection, &ChromeBrowserProxyResolver::StaticFilterMessage, this, NULL)); proxy_ = GetProxy(dbus_); if (!proxy_) { dbus_->DbusConnectionRemoveFilter( connection, &ChromeBrowserProxyResolver::StaticFilterMessage, this); } TEST_AND_RETURN_FALSE(proxy_); // For the error log return true; } void ChromeBrowserProxyResolver::Shutdown() { if (!proxy_) return; GError* gerror = NULL; DBusGConnection* gbus = dbus_->BusGet(DBUS_BUS_SYSTEM, &gerror); TEST_AND_RETURN(gbus); DBusConnection* connection = dbus_->ConnectionGetConnection(gbus); dbus_->DbusConnectionRemoveFilter( connection, &ChromeBrowserProxyResolver::StaticFilterMessage, this); proxy_ = NULL; } ChromeBrowserProxyResolver::~ChromeBrowserProxyResolver() { // Kill proxy object. Shutdown(); // Kill outstanding timers for (TimeoutsMap::iterator it = timers_.begin(), e = timers_.end(); it != e; ++it) { g_source_destroy(it->second); it->second = NULL; } } bool ChromeBrowserProxyResolver::GetProxiesForUrl(const string& url, ProxiesResolvedFn callback, void* data) { GError* error = NULL; guint timeout = timeout_; if (proxy_) { bool dbus_success = true; bool dbus_reinit = false; bool dbus_got_error; do { if (!dbus_success) { // We failed with a null error, time to re-init the dbus proxy. LOG(WARNING) << "attempting to reinitialize dbus proxy and retrying"; Shutdown(); if (!Init()) { LOG(WARNING) << "failed to reinitialize the dbus proxy"; break; } dbus_reinit = true; } dbus_success = dbus_->ProxyCall( proxy_, kLibCrosServiceResolveNetworkProxyMethodName, &error, G_TYPE_STRING, url.c_str(), G_TYPE_STRING, kLibCrosProxyResolveSignalInterface, G_TYPE_STRING, kLibCrosProxyResolveName, G_TYPE_INVALID, G_TYPE_INVALID); dbus_got_error = false; if (dbus_success) { LOG(INFO) << "dbug_g_proxy_call succeeded!"; } else { if (error) { // Register the fact that we did receive an error, as it is nullified // on the next line. dbus_got_error = true; LOG(WARNING) << "dbus_g_proxy_call failed: " << utils::GetAndFreeGError(&error) << " Continuing with no proxy."; } else { LOG(WARNING) << "dbug_g_proxy_call failed with no error string, " "continuing with no proxy."; } timeout = 0; } } while (!(dbus_success || dbus_got_error || dbus_reinit)); } else { LOG(WARNING) << "dbug proxy object missing, continuing with no proxy."; timeout = 0; } callbacks_.insert(make_pair(url, make_pair(callback, data))); Closure* closure = NewCallback(this, &ChromeBrowserProxyResolver::HandleTimeout, url); GSource* timer = g_timeout_source_new_seconds(timeout); g_source_set_callback(timer, &utils::GlibRunClosure, closure, NULL); g_source_attach(timer, NULL); timers_.insert(make_pair(url, timer)); return true; } DBusHandlerResult ChromeBrowserProxyResolver::FilterMessage( DBusConnection* connection, DBusMessage* message) { // Code lifted from libcros. if (!dbus_->DbusMessageIsSignal(message, kLibCrosProxyResolveSignalInterface, kLibCrosProxyResolveName)) { return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } // Get args char* source_url = NULL; char* proxy_list = NULL; char* error = NULL; DBusError arg_error; dbus_error_init(&arg_error); if (!dbus_->DbusMessageGetArgs(message, &arg_error, DBUS_TYPE_STRING, &source_url, DBUS_TYPE_STRING, &proxy_list, DBUS_TYPE_STRING, &error, DBUS_TYPE_INVALID)) { LOG(ERROR) << "Error reading dbus signal."; return DBUS_HANDLER_RESULT_HANDLED; } if (!source_url || !proxy_list) { LOG(ERROR) << "Error getting url, proxy list from dbus signal."; return DBUS_HANDLER_RESULT_HANDLED; } HandleReply(source_url, proxy_list); return DBUS_HANDLER_RESULT_HANDLED; } bool ChromeBrowserProxyResolver::DeleteUrlState( const string& source_url, bool delete_timer, pair<ProxiesResolvedFn, void*>* callback) { { CallbacksMap::iterator it = callbacks_.lower_bound(source_url); TEST_AND_RETURN_FALSE(it != callbacks_.end()); TEST_AND_RETURN_FALSE(it->first == source_url); if (callback) *callback = it->second; callbacks_.erase(it); } { TimeoutsMap::iterator it = timers_.lower_bound(source_url); TEST_AND_RETURN_FALSE(it != timers_.end()); TEST_AND_RETURN_FALSE(it->first == source_url); if (delete_timer) g_source_destroy(it->second); timers_.erase(it); } return true; } void ChromeBrowserProxyResolver::HandleReply(const string& source_url, const string& proxy_list) { pair<ProxiesResolvedFn, void*> callback; TEST_AND_RETURN(DeleteUrlState(source_url, true, &callback)); (*callback.first)(ParseProxyString(proxy_list), callback.second); } void ChromeBrowserProxyResolver::HandleTimeout(string source_url) { LOG(INFO) << "Timeout handler called. Seems Chrome isn't responding."; pair<ProxiesResolvedFn, void*> callback; TEST_AND_RETURN(DeleteUrlState(source_url, false, &callback)); deque<string> proxies; proxies.push_back(kNoProxy); (*callback.first)(proxies, callback.second); } deque<string> ChromeBrowserProxyResolver::ParseProxyString( const string& input) { deque<string> ret; // Some of this code taken from // http://src.chromium.org/svn/trunk/src/net/proxy/proxy_server.cc and // http://src.chromium.org/svn/trunk/src/net/proxy/proxy_list.cc StringTokenizer entry_tok(input, ";"); while (entry_tok.GetNext()) { string token = entry_tok.token(); TrimWhitespaceASCII(token, TRIM_ALL, &token); // Start by finding the first space (if any). std::string::iterator space; for (space = token.begin(); space != token.end(); ++space) { if (IsAsciiWhitespace(*space)) { break; } } string scheme = string(token.begin(), space); StringToLowerASCII(&scheme); // Chrome uses "socks" to mean socks4 and "proxy" to mean http. if (scheme == "socks") scheme += "4"; else if (scheme == "proxy") scheme = "http"; else if (scheme != "https" && scheme != "socks4" && scheme != "socks5" && scheme != "direct") continue; // Invalid proxy scheme string host_and_port = string(space, token.end()); TrimWhitespaceASCII(host_and_port, TRIM_ALL, &host_and_port); if (scheme != "direct" && host_and_port.empty()) continue; // Must supply host/port when non-direct proxy used. ret.push_back(scheme + "://" + host_and_port); } if (ret.empty() || *ret.rbegin() != kNoProxy) ret.push_back(kNoProxy); return ret; } } // namespace chromeos_update_engine <commit_msg>fix(chrome_browser_proxy_resolver): fix spelling errors<commit_after>// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "update_engine/chrome_browser_proxy_resolver.h" #include <map> #include <string> #include <base/string_util.h> #include <base/strings/string_tokenizer.h> #include <dbus/dbus-glib.h> #include <dbus/dbus-glib-lowlevel.h> #include <google/protobuf/stubs/common.h> #include "update_engine/dbus_constants.h" #include "update_engine/utils.h" namespace chromeos_update_engine { using base::StringTokenizer; using google::protobuf::Closure; using google::protobuf::NewCallback; using std::deque; using std::make_pair; using std::multimap; using std::pair; using std::string; #define LIB_CROS_PROXY_RESOLVE_NAME "ProxyResolved" #define LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE \ "org.chromium.UpdateEngineLibcrosProxyResolvedInterface" const char kLibCrosServiceName[] = "org.chromium.LibCrosService"; const char kLibCrosServicePath[] = "/org/chromium/LibCrosService"; const char kLibCrosServiceInterface[] = "org.chromium.LibCrosServiceInterface"; const char kLibCrosServiceResolveNetworkProxyMethodName[] = "ResolveNetworkProxy"; const char kLibCrosProxyResolveName[] = LIB_CROS_PROXY_RESOLVE_NAME; const char kLibCrosProxyResolveSignalInterface[] = LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE; const char kLibCrosProxyResolveSignalFilter[] = "type='signal', " "interface='" LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE "', " "member='" LIB_CROS_PROXY_RESOLVE_NAME "'"; #undef LIB_CROS_PROXY_RESOLVE_SIGNAL_INTERFACE #undef LIB_CROS_PROXY_RESOLVE_NAME namespace { const int kTimeout = 5; // seconds DBusGProxy* GetProxy(DbusGlibInterface* dbus) { GError* error = NULL; DBusGConnection* bus = dbus->BusGet(DBUS_BUS_SYSTEM, &error); if (!bus) { LOG(ERROR) << "Failed to get bus"; return NULL; } DBusGProxy* proxy = dbus->ProxyNewForNameOwner(bus, kLibCrosServiceName, kLibCrosServicePath, kLibCrosServiceInterface, &error); if (!proxy) { LOG(ERROR) << "Error getting dbus proxy for " << kLibCrosServiceName << ": " << utils::GetAndFreeGError(&error); return NULL; } return proxy; } } // namespace {} ChromeBrowserProxyResolver::ChromeBrowserProxyResolver(DbusGlibInterface* dbus) : dbus_(dbus), proxy_(NULL), timeout_(kTimeout) {} bool ChromeBrowserProxyResolver::Init() { // Set up signal handler. Code lifted from libcros if (proxy_) { // Already initialized return true; } GError* gerror = NULL; DBusGConnection* gbus = dbus_->BusGet(DBUS_BUS_SYSTEM, &gerror); TEST_AND_RETURN_FALSE(gbus); DBusConnection* connection = dbus_->ConnectionGetConnection(gbus); TEST_AND_RETURN_FALSE(connection); DBusError error; dbus_error_init(&error); dbus_->DbusBusAddMatch(connection, kLibCrosProxyResolveSignalFilter, &error); TEST_AND_RETURN_FALSE(!dbus_error_is_set(&error)); TEST_AND_RETURN_FALSE(dbus_->DbusConnectionAddFilter( connection, &ChromeBrowserProxyResolver::StaticFilterMessage, this, NULL)); proxy_ = GetProxy(dbus_); if (!proxy_) { dbus_->DbusConnectionRemoveFilter( connection, &ChromeBrowserProxyResolver::StaticFilterMessage, this); } TEST_AND_RETURN_FALSE(proxy_); // For the error log return true; } void ChromeBrowserProxyResolver::Shutdown() { if (!proxy_) return; GError* gerror = NULL; DBusGConnection* gbus = dbus_->BusGet(DBUS_BUS_SYSTEM, &gerror); TEST_AND_RETURN(gbus); DBusConnection* connection = dbus_->ConnectionGetConnection(gbus); dbus_->DbusConnectionRemoveFilter( connection, &ChromeBrowserProxyResolver::StaticFilterMessage, this); proxy_ = NULL; } ChromeBrowserProxyResolver::~ChromeBrowserProxyResolver() { // Kill proxy object. Shutdown(); // Kill outstanding timers for (TimeoutsMap::iterator it = timers_.begin(), e = timers_.end(); it != e; ++it) { g_source_destroy(it->second); it->second = NULL; } } bool ChromeBrowserProxyResolver::GetProxiesForUrl(const string& url, ProxiesResolvedFn callback, void* data) { GError* error = NULL; guint timeout = timeout_; if (proxy_) { bool dbus_success = true; bool dbus_reinit = false; bool dbus_got_error; do { if (!dbus_success) { // We failed with a null error, time to re-init the dbus proxy. LOG(WARNING) << "attempting to reinitialize dbus proxy and retrying"; Shutdown(); if (!Init()) { LOG(WARNING) << "failed to reinitialize the dbus proxy"; break; } dbus_reinit = true; } dbus_success = dbus_->ProxyCall( proxy_, kLibCrosServiceResolveNetworkProxyMethodName, &error, G_TYPE_STRING, url.c_str(), G_TYPE_STRING, kLibCrosProxyResolveSignalInterface, G_TYPE_STRING, kLibCrosProxyResolveName, G_TYPE_INVALID, G_TYPE_INVALID); dbus_got_error = false; if (dbus_success) { LOG(INFO) << "dbus_g_proxy_call succeeded!"; } else { if (error) { // Register the fact that we did receive an error, as it is nullified // on the next line. dbus_got_error = true; LOG(WARNING) << "dbus_g_proxy_call failed: " << utils::GetAndFreeGError(&error) << " Continuing with no proxy."; } else { LOG(WARNING) << "dbus_g_proxy_call failed with no error string, " "continuing with no proxy."; } timeout = 0; } } while (!(dbus_success || dbus_got_error || dbus_reinit)); } else { LOG(WARNING) << "dbus proxy object missing, continuing with no proxy."; timeout = 0; } callbacks_.insert(make_pair(url, make_pair(callback, data))); Closure* closure = NewCallback(this, &ChromeBrowserProxyResolver::HandleTimeout, url); GSource* timer = g_timeout_source_new_seconds(timeout); g_source_set_callback(timer, &utils::GlibRunClosure, closure, NULL); g_source_attach(timer, NULL); timers_.insert(make_pair(url, timer)); return true; } DBusHandlerResult ChromeBrowserProxyResolver::FilterMessage( DBusConnection* connection, DBusMessage* message) { // Code lifted from libcros. if (!dbus_->DbusMessageIsSignal(message, kLibCrosProxyResolveSignalInterface, kLibCrosProxyResolveName)) { return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } // Get args char* source_url = NULL; char* proxy_list = NULL; char* error = NULL; DBusError arg_error; dbus_error_init(&arg_error); if (!dbus_->DbusMessageGetArgs(message, &arg_error, DBUS_TYPE_STRING, &source_url, DBUS_TYPE_STRING, &proxy_list, DBUS_TYPE_STRING, &error, DBUS_TYPE_INVALID)) { LOG(ERROR) << "Error reading dbus signal."; return DBUS_HANDLER_RESULT_HANDLED; } if (!source_url || !proxy_list) { LOG(ERROR) << "Error getting url, proxy list from dbus signal."; return DBUS_HANDLER_RESULT_HANDLED; } HandleReply(source_url, proxy_list); return DBUS_HANDLER_RESULT_HANDLED; } bool ChromeBrowserProxyResolver::DeleteUrlState( const string& source_url, bool delete_timer, pair<ProxiesResolvedFn, void*>* callback) { { CallbacksMap::iterator it = callbacks_.lower_bound(source_url); TEST_AND_RETURN_FALSE(it != callbacks_.end()); TEST_AND_RETURN_FALSE(it->first == source_url); if (callback) *callback = it->second; callbacks_.erase(it); } { TimeoutsMap::iterator it = timers_.lower_bound(source_url); TEST_AND_RETURN_FALSE(it != timers_.end()); TEST_AND_RETURN_FALSE(it->first == source_url); if (delete_timer) g_source_destroy(it->second); timers_.erase(it); } return true; } void ChromeBrowserProxyResolver::HandleReply(const string& source_url, const string& proxy_list) { pair<ProxiesResolvedFn, void*> callback; TEST_AND_RETURN(DeleteUrlState(source_url, true, &callback)); (*callback.first)(ParseProxyString(proxy_list), callback.second); } void ChromeBrowserProxyResolver::HandleTimeout(string source_url) { LOG(INFO) << "Timeout handler called. Seems Chrome isn't responding."; pair<ProxiesResolvedFn, void*> callback; TEST_AND_RETURN(DeleteUrlState(source_url, false, &callback)); deque<string> proxies; proxies.push_back(kNoProxy); (*callback.first)(proxies, callback.second); } deque<string> ChromeBrowserProxyResolver::ParseProxyString( const string& input) { deque<string> ret; // Some of this code taken from // http://src.chromium.org/svn/trunk/src/net/proxy/proxy_server.cc and // http://src.chromium.org/svn/trunk/src/net/proxy/proxy_list.cc StringTokenizer entry_tok(input, ";"); while (entry_tok.GetNext()) { string token = entry_tok.token(); TrimWhitespaceASCII(token, TRIM_ALL, &token); // Start by finding the first space (if any). std::string::iterator space; for (space = token.begin(); space != token.end(); ++space) { if (IsAsciiWhitespace(*space)) { break; } } string scheme = string(token.begin(), space); StringToLowerASCII(&scheme); // Chrome uses "socks" to mean socks4 and "proxy" to mean http. if (scheme == "socks") scheme += "4"; else if (scheme == "proxy") scheme = "http"; else if (scheme != "https" && scheme != "socks4" && scheme != "socks5" && scheme != "direct") continue; // Invalid proxy scheme string host_and_port = string(space, token.end()); TrimWhitespaceASCII(host_and_port, TRIM_ALL, &host_and_port); if (scheme != "direct" && host_and_port.empty()) continue; // Must supply host/port when non-direct proxy used. ret.push_back(scheme + "://" + host_and_port); } if (ret.empty() || *ret.rbegin() != kNoProxy) ret.push_back(kNoProxy); return ret; } } // namespace chromeos_update_engine <|endoftext|>
<commit_before>#include "Halide.h" #include <stdio.h> #include <math.h> using std::vector; using namespace Halide; using namespace Halide::Internal; class CountInterleaves : public IRVisitor { public: int result; CountInterleaves() : result(0) {} using IRVisitor::visit; void visit(const Call *op) { if (op->name == Call::interleave_vectors && op->call_type == Call::Intrinsic) { result++; } IRVisitor::visit(op); } }; int count_interleaves(Func f) { Target t = get_jit_target_from_environment(); t.set_feature(Target::NoBoundsQuery); t.set_feature(Target::NoAsserts); f.compute_root(); Stmt s = Internal::lower({f.function()}, t); CountInterleaves i; s.accept(&i); return i.result; } void check_interleave_count(Func f, int correct) { int c = count_interleaves(f); if (c < correct) { printf("Func %s should have interleaved >= %d times but interleaved %d times instead.\n", f.name().c_str(), correct, c); exit(-1); } } // Make sure the interleave pattern generates good vector code int main(int argc, char **argv) { Var x, y, c; { Func f, g, h; f(x) = sin(x); g(x) = cos(x); h(x) = select(x % 2 == 0, 1.0f/f(x/2), g(x/2)*17.0f); f.compute_root(); g.compute_root(); h.vectorize(x, 8); check_interleave_count(h, 1); Image<float> result = h.realize(16); for (int x = 0; x < 16; x++) { float correct = ((x % 2) == 0) ? (1.0f/(sinf(x/2))) : (cosf(x/2)*17.0f); float delta = result(x) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result(x), correct); return -1; } } } { // Test interleave 3 vectors: Func planar, interleaved; planar(x, y) = Halide::cast<float>( 3 * x + y ); interleaved(x, y) = planar(x, y); Var xy("xy"); planar .compute_at(interleaved, xy) .vectorize(x, 4); interleaved .reorder(y, x) .bound(y, 0, 3) .bound(x, 0, 16) .fuse(y, x, xy) .vectorize(xy, 12); interleaved .output_buffer() .set_min(1, 0) .set_stride(0, 3) .set_stride(1, 1) .set_extent(1, 3); Buffer buff3; buff3 = Buffer(Float(32), 16, 3, 0, 0, (uint8_t *)0); buff3.raw_buffer()->stride[0] = 3; buff3.raw_buffer()->stride[1] = 1; Realization r3({buff3}); interleaved.realize(r3); check_interleave_count(interleaved, 2); Image<float> result3 = r3[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 3; y++) { float correct = 3*x + y; float delta = result3(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result3(x,y), correct); return -1; } } } } { // Test interleave 4 vectors: Func f1, f2, f3, f4, f5; f1(x) = sin(x); f2(x) = sin(2*x); f3(x) = sin(3*x); f4(x) = sin(4*x); f5(x) = sin(5*x); Func output4; output4(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), f4(x)); output4 .reorder(y, x) .bound(y, 0, 4) .unroll(y) .vectorize(x, 4); output4.output_buffer() .set_min(1, 0) .set_stride(0, 4) .set_stride(1, 1) .set_extent(1, 4); check_interleave_count(output4, 1); Buffer buff4; buff4 = Buffer(Float(32), 16, 4, 0, 0, (uint8_t *)0); buff4.raw_buffer()->stride[0] = 4; buff4.raw_buffer()->stride[1] = 1; Realization r4({buff4}); output4.realize(r4); Image<float> result4 = r4[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 4; y++) { float correct = sin((y+1)*x); float delta = result4(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result4(x,y), correct); return -1; } } } // Test interleave 5 vectors: Func output5; output5(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), y == 3, f4(x), f5(x)); output5 .reorder(y, x) .bound(y, 0, 5) .unroll(y) .vectorize(x, 4); output5.output_buffer() .set_min(1, 0) .set_stride(0, 5) .set_stride(1, 1) .set_extent(1, 5); check_interleave_count(output5, 1); Buffer buff5; buff5 = Buffer(Float(32), 16, 5, 0, 0, (uint8_t *)0); buff5.raw_buffer()->stride[0] = 5; buff5.raw_buffer()->stride[1] = 1; Realization r5({buff5}); output5.realize(r5); Image<float> result5 = r5[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 5; y++) { float correct = sin((y+1)*x); float delta = result5(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result5(x,y), correct); return -1; } } } } { // Test interleaving inside of nested blocks Func f1, f2, f3, f4, f5; f1(x) = sin(x); f1.compute_root(); f2(x) = sin(2*x); f2.compute_root(); Func unrolled; unrolled(x, y) = select(x % 2 == 0, f1(x), f2(x)) + y; Var xi, yi; unrolled.tile(x, y, xi, yi, 2, 2).vectorize(x, 4).unroll(xi).unroll(yi).unroll(x, 2); check_interleave_count(unrolled, 4); } { // Make sure we don't interleave when the reordering would change the meaning. Image<uint8_t> ref; for (int i = 0; i < 2; i++) { Func output6; output6(x, y) = cast<uint8_t>(x); RDom r(0, 16); // A not-safe-to-merge pair of updates output6(2*r, 0) = cast<uint8_t>(3); output6(2*r+1, 0) = output6(2*r, 0)+2; // A safe-to-merge pair of updates output6(2*r, 1) = cast<uint8_t>(3); output6(2*r+1, 1) = cast<uint8_t>(4); // A safe-to-merge-but-not-complete triple of updates: output6(3*r, 3) = cast<uint8_t>(3); output6(3*r+1, 3) = cast<uint8_t>(4); // A safe-to-merge-but-we-don't pair of updates, because they // load recursively, so we conservatively bail out. output6(2*r, 2) += 1; output6(2*r+1, 2) += 2; // A safe-to-merge triple of updates: output6(3*r, 3) = cast<uint8_t>(7); output6(3*r+2, 3) = cast<uint8_t>(9); output6(3*r+1, 3) = cast<uint8_t>(8); if (i == 0) { // Making the reference output. ref = output6.realize(50, 4); } else { // Vectorize and compare to the reference. for (int j = 0; j < 11; j++) { output6.update(j).vectorize(r); } check_interleave_count(output6, 2); Image<uint8_t> out = output6.realize(50, 4); for (int y = 0; y < ref.height(); y++) { for (int x = 0; x < ref.width(); x++) { if (out(x, y) != ref(x, y)) { printf("result(%d, %d) = %d instead of %d\n", x, y, out(x, y), ref(x, y)); return -1; } } } } } } { // Test that transposition works when vectorizing either dimension: Func square("square"); square(x, y) = cast(UInt(16), 5*x + y); Func trans1("trans1"); trans1(x, y) = square(y, x); Func trans2("trans2"); trans2(x, y) = square(y, x); square.compute_root() .bound(x, 0, 8) .bound(y, 0, 8); trans1.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .vectorize(x) .unroll(y); trans2.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .unroll(x) .vectorize(y); trans1.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); trans2.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); Image<uint16_t> result6(8,8); Image<uint16_t> result7(8,8); trans1.realize(result6); trans2.realize(result7); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { int correct = 5*y + x; if (result6(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result6(x,y), correct); return -1; } if (result7(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result7(x,y), correct); return -1; } } } check_interleave_count(trans1, 1); check_interleave_count(trans2, 1); } printf("Success!\n"); return 0; } <commit_msg>Added tests of multiple output interleaving.<commit_after>#include "Halide.h" #include <stdio.h> #include <math.h> using std::vector; using namespace Halide; using namespace Halide::Internal; class CountInterleaves : public IRVisitor { public: int result; CountInterleaves() : result(0) {} using IRVisitor::visit; void visit(const Call *op) { if (op->name == Call::interleave_vectors && op->call_type == Call::Intrinsic) { result++; } IRVisitor::visit(op); } }; int count_interleaves(Func f) { Target t = get_jit_target_from_environment(); t.set_feature(Target::NoBoundsQuery); t.set_feature(Target::NoAsserts); f.compute_root(); Stmt s = Internal::lower({f.function()}, t); CountInterleaves i; s.accept(&i); return i.result; } void check_interleave_count(Func f, int correct) { int c = count_interleaves(f); if (c < correct) { printf("Func %s should have interleaved >= %d times but interleaved %d times instead.\n", f.name().c_str(), correct, c); exit(-1); } } template <typename FuncRefVarOrExpr> void define(FuncRefVarOrExpr f, std::vector<Expr> values) { if (values.size() == 1) { f = values[0]; } else { f = Tuple(values); } } template <typename FuncRefVarOrExpr> void define(FuncRefVarOrExpr f, Expr value, int count) { std::vector<Expr> values; for (int i = 0; i < count; i++) { values.push_back(value); } define(f, values); } template <typename FuncRefVarOrExpr> Expr element(FuncRefVarOrExpr f, int i) { if (f.size() == 1) { assert(i == 0); return f; } else { return f[i]; } } // Make sure the interleave pattern generates good vector code int main(int argc, char **argv) { Var x, y, c; for (int elements = 1; elements <= 5; elements++) { Func f, g, h; std::vector<Expr> f_def, g_def; for (int i = 0; i < elements; i++) { f_def.push_back(sin(x + i)); g_def.push_back(cos(x + i)); } define(f(x), f_def); define(g(x), g_def); std::vector<Expr> h_def; for (int i = 0; i < elements; i++) { h_def.push_back(select(x % 2 == 0, 1.0f/element(f(x/2), i), element(g(x/2), i)*17.0f)); g_def.push_back(cos(x + i)); } define(h(x), h_def); f.compute_root(); g.compute_root(); h.vectorize(x, 8); check_interleave_count(h, 1); Realization results = h.realize(16); for (int i = 0; i < elements; i++) { Image<float> result = results[i]; for (int x = 0; x < 16; x++) { float correct = ((x % 2) == 0) ? (1.0f/(sinf(x/2 + i))) : (cosf(x/2 + i)*17.0f); float delta = result(x) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result(x), correct); return -1; } } } } { // Test interleave 3 vectors: Func planar, interleaved; planar(x, y) = Halide::cast<float>( 3 * x + y ); interleaved(x, y) = planar(x, y); Var xy("xy"); planar .compute_at(interleaved, xy) .vectorize(x, 4); interleaved .reorder(y, x) .bound(y, 0, 3) .bound(x, 0, 16) .fuse(y, x, xy) .vectorize(xy, 12); interleaved .output_buffer() .set_min(1, 0) .set_stride(0, 3) .set_stride(1, 1) .set_extent(1, 3); Buffer buff3; buff3 = Buffer(Float(32), 16, 3, 0, 0, (uint8_t *)0); buff3.raw_buffer()->stride[0] = 3; buff3.raw_buffer()->stride[1] = 1; Realization r3({buff3}); interleaved.realize(r3); check_interleave_count(interleaved, 2); Image<float> result3 = r3[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 3; y++) { float correct = 3*x + y; float delta = result3(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result3(x,y), correct); return -1; } } } } { // Test interleave 4 vectors: Func f1, f2, f3, f4, f5; f1(x) = sin(x); f2(x) = sin(2*x); f3(x) = sin(3*x); f4(x) = sin(4*x); f5(x) = sin(5*x); Func output4; output4(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), f4(x)); output4 .reorder(y, x) .bound(y, 0, 4) .unroll(y) .vectorize(x, 4); output4.output_buffer() .set_min(1, 0) .set_stride(0, 4) .set_stride(1, 1) .set_extent(1, 4); check_interleave_count(output4, 1); Buffer buff4; buff4 = Buffer(Float(32), 16, 4, 0, 0, (uint8_t *)0); buff4.raw_buffer()->stride[0] = 4; buff4.raw_buffer()->stride[1] = 1; Realization r4({buff4}); output4.realize(r4); Image<float> result4 = r4[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 4; y++) { float correct = sin((y+1)*x); float delta = result4(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result4(x,y), correct); return -1; } } } // Test interleave 5 vectors: Func output5; output5(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), y == 3, f4(x), f5(x)); output5 .reorder(y, x) .bound(y, 0, 5) .unroll(y) .vectorize(x, 4); output5.output_buffer() .set_min(1, 0) .set_stride(0, 5) .set_stride(1, 1) .set_extent(1, 5); check_interleave_count(output5, 1); Buffer buff5; buff5 = Buffer(Float(32), 16, 5, 0, 0, (uint8_t *)0); buff5.raw_buffer()->stride[0] = 5; buff5.raw_buffer()->stride[1] = 1; Realization r5({buff5}); output5.realize(r5); Image<float> result5 = r5[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 5; y++) { float correct = sin((y+1)*x); float delta = result5(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result5(x,y), correct); return -1; } } } } { // Test interleaving inside of nested blocks Func f1, f2, f3, f4, f5; f1(x) = sin(x); f1.compute_root(); f2(x) = sin(2*x); f2.compute_root(); Func unrolled; unrolled(x, y) = select(x % 2 == 0, f1(x), f2(x)) + y; Var xi, yi; unrolled.tile(x, y, xi, yi, 2, 2).vectorize(x, 4).unroll(xi).unroll(yi).unroll(x, 2); check_interleave_count(unrolled, 4); } for (int elements = 1; elements <= 5; elements++) { // Make sure we don't interleave when the reordering would change the meaning. Realization* refs; for (int i = 0; i < 2; i++) { Func output6; define(output6(x, y), cast<uint8_t>(x), elements); RDom r(0, 16); // A not-safe-to-merge pair of updates define(output6(2*r, 0), cast<uint8_t>(3), elements); define(output6(2*r+1, 0), cast<uint8_t>(4), elements); // A safe-to-merge pair of updates define(output6(2*r, 1), cast<uint8_t>(3), elements); define(output6(2*r+1, 1), cast<uint8_t>(4), elements); // A safe-to-merge-but-not-complete triple of updates: define(output6(3*r, 3), cast<uint8_t>(3), elements); define(output6(3*r+1, 3), cast<uint8_t>(4), elements); // A safe-to-merge-but-we-don't pair of updates, because they // load recursively, so we conservatively bail out. std::vector<Expr> rdef0, rdef1; for (int i = 0; i < elements; i++) { rdef0.push_back(element(output6(2*r, 2), i) + 1); rdef1.push_back(element(output6(2*r+1, 2), i) + 1); } define(output6(2*r, 2), rdef0); define(output6(2*r+1, 2), rdef1); // A safe-to-merge triple of updates: define(output6(3*r, 3), cast<uint8_t>(7), elements); define(output6(3*r+2, 3), cast<uint8_t>(9), elements); define(output6(3*r+1, 3), cast<uint8_t>(8), elements); if (i == 0) { // Making the reference output. refs = new Realization(output6.realize(50, 4)); } else { // Vectorize and compare to the reference. for (int j = 0; j < 11; j++) { output6.update(j).vectorize(r); } check_interleave_count(output6, 2*elements); Realization outs = output6.realize(50, 4); for (int e = 0; e < elements; e++) { Image<uint8_t> ref = (*refs)[e]; Image<uint8_t> out = outs[e]; for (int y = 0; y < ref.height(); y++) { for (int x = 0; x < ref.width(); x++) { if (out(x, y) != ref(x, y)) { printf("result(%d, %d) = %d instead of %d\n", x, y, out(x, y), ref(x, y)); return -1; } } } } } } delete refs; } { // Test that transposition works when vectorizing either dimension: Func square("square"); square(x, y) = cast(UInt(16), 5*x + y); Func trans1("trans1"); trans1(x, y) = square(y, x); Func trans2("trans2"); trans2(x, y) = square(y, x); square.compute_root() .bound(x, 0, 8) .bound(y, 0, 8); trans1.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .vectorize(x) .unroll(y); trans2.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .unroll(x) .vectorize(y); trans1.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); trans2.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); Image<uint16_t> result6(8,8); Image<uint16_t> result7(8,8); trans1.realize(result6); trans2.realize(result7); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { int correct = 5*y + x; if (result6(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result6(x,y), correct); return -1; } if (result7(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result7(x,y), correct); return -1; } } } check_interleave_count(trans1, 1); check_interleave_count(trans2, 1); } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>/*************************************************** This is a library for the MCP23008 i2c port expander These displays use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. Adapted for Particle IDE by Evan Simkowitz. BSD license, all text above must be included in any redistribution ****************************************************/ #if defined (SPARK) #include "Adafruit_MCP23008.h" #else #include <Wire.h> #ifdef __AVR__ #include <avr/pgmspace.h> #endif #include "Adafruit_MCP23008.h" #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #endif //Spark //////////////////////////////////////////////////////////////////////////////// // RTC_DS1307 implementation void Adafruit_MCP23008::begin(uint8_t addr) { if (addr > 7) { addr = 7; } i2caddr = addr; Wire.begin(); // set defaults! Wire.beginTransmission(MCP23008_ADDRESS | i2caddr); #if ARDUINO >= 100 Wire.write((byte)MCP23008_IODIR); Wire.write((byte)0xFF); // all inputs Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); #else Wire.send(MCP23008_IODIR); Wire.send(0xFF); // all inputs Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); #endif Wire.endTransmission(); } void Adafruit_MCP23008::begin(void) { begin(0); } void Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) { uint8_t iodir; // only 8 bits! if (p > 7) return; iodir = read8(MCP23008_IODIR); // set the pin and direction if (d == INPUT) { iodir |= 1 << p; } else { iodir &= ~(1 << p); } // write the new IODIR write8(MCP23008_IODIR, iodir); } uint8_t Adafruit_MCP23008::readGPIO(void) { // read the current GPIO input return read8(MCP23008_GPIO); } void Adafruit_MCP23008::writeGPIO(uint8_t gpio) { write8(MCP23008_GPIO, gpio); } void Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) { uint8_t gpio; // only 8 bits! if (p > 7) return; // read the current GPIO output latches gpio = readGPIO(); // set the pin and direction if (d == HIGH) { gpio |= 1 << p; } else { gpio &= ~(1 << p); } // write the new GPIO writeGPIO(gpio); } void Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) { uint8_t gppu; // only 8 bits! if (p > 7) return; gppu = read8(MCP23008_GPPU); // set the pin and direction if (d == HIGH) { gppu |= 1 << p; } else { gppu &= ~(1 << p); } // write the new GPIO write8(MCP23008_GPPU, gppu); } uint8_t Adafruit_MCP23008::digitalRead(uint8_t p) { // only 8 bits! if (p > 7) return 0; // read the current GPIO return (readGPIO() >> p) & 0x1; } uint8_t Adafruit_MCP23008::read8(uint8_t addr) { Wire.beginTransmission(MCP23008_ADDRESS | i2caddr); #if ARDUINO >= 100 Wire.write((byte)addr); #else Wire.send(addr); #endif Wire.endTransmission(); Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1); #if ARDUINO >= 100 return Wire.read(); #else return Wire.receive(); #endif } void Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) { Wire.beginTransmission(MCP23008_ADDRESS | i2caddr); #if ARDUINO >= 100 Wire.write((byte)addr); Wire.write((byte)data); #else Wire.send(addr); Wire.send(data); #endif Wire.endTransmission(); } <commit_msg>trying to get it working<commit_after>/*************************************************** This is a library for the MCP23008 i2c port expander These displays use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. Adapted for Particle IDE by Evan Simkowitz. BSD license, all text above must be included in any redistribution ****************************************************/ #if defined (SPARK) #include "Adafruit_MCP23008.h" #else #include <Wire.h> #ifdef __AVR__ #include <avr/pgmspace.h> #endif #include "Adafruit_MCP23008.h" #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #endif //Spark //////////////////////////////////////////////////////////////////////////////// // RTC_DS1307 implementation void Adafruit_MCP23008::begin(uint8_t addr) { if (addr > 7) { addr = 7; } i2caddr = addr; Wire.begin(); // set defaults! Wire.beginTransmission(MCP23008_ADDRESS | i2caddr); #if ARDUINO >= 100 || defined (SPARK) Wire.write((byte)MCP23008_IODIR); Wire.write((byte)0xFF); // all inputs Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); Wire.write((byte)0x00); #else Wire.send(MCP23008_IODIR); Wire.send(0xFF); // all inputs Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); Wire.send(0x00); #endif Wire.endTransmission(); } void Adafruit_MCP23008::begin(void) { begin(0); } void Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) { uint8_t iodir; // only 8 bits! if (p > 7) return; iodir = read8(MCP23008_IODIR); // set the pin and direction if (d == INPUT) { iodir |= 1 << p; } else { iodir &= ~(1 << p); } // write the new IODIR write8(MCP23008_IODIR, iodir); } uint8_t Adafruit_MCP23008::readGPIO(void) { // read the current GPIO input return read8(MCP23008_GPIO); } void Adafruit_MCP23008::writeGPIO(uint8_t gpio) { write8(MCP23008_GPIO, gpio); } void Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) { uint8_t gpio; // only 8 bits! if (p > 7) return; // read the current GPIO output latches gpio = readGPIO(); // set the pin and direction if (d == HIGH) { gpio |= 1 << p; } else { gpio &= ~(1 << p); } // write the new GPIO writeGPIO(gpio); } void Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) { uint8_t gppu; // only 8 bits! if (p > 7) return; gppu = read8(MCP23008_GPPU); // set the pin and direction if (d == HIGH) { gppu |= 1 << p; } else { gppu &= ~(1 << p); } // write the new GPIO write8(MCP23008_GPPU, gppu); } uint8_t Adafruit_MCP23008::digitalRead(uint8_t p) { // only 8 bits! if (p > 7) return 0; // read the current GPIO return (readGPIO() >> p) & 0x1; } uint8_t Adafruit_MCP23008::read8(uint8_t addr) { Wire.beginTransmission(MCP23008_ADDRESS | i2caddr); #if ARDUINO >= 100 || defined (SPARK) Wire.write((byte)addr); #else Wire.send(addr); #endif Wire.endTransmission(); Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1); #if ARDUINO >= 100 || defined (SPARK) return Wire.read(); #else return Wire.receive(); #endif } void Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) { Wire.beginTransmission(MCP23008_ADDRESS | i2caddr); #if ARDUINO >= 100 || defined (SPARK) Wire.write((byte)addr); Wire.write((byte)data); #else Wire.send(addr); Wire.send(data); #endif Wire.endTransmission(); } <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <malloc.h> #include <boost/format.hpp> #include "log.h" #include "safs_file.h" #include "cache.h" #include "slab_allocator.h" #include "native_file.h" #include "in_mem_storage.h" #include "graph_file_header.h" class in_mem_byte_array: public page_byte_array { off_t off; size_t size; const char *pages; void assign(in_mem_byte_array &arr) { this->off = arr.off; this->size = arr.size; this->pages = arr.pages; } in_mem_byte_array(in_mem_byte_array &arr) { assign(arr); } in_mem_byte_array &operator=(in_mem_byte_array &arr) { assign(arr); return *this; } public: in_mem_byte_array(byte_array_allocator &alloc): page_byte_array(alloc) { off = 0; size = 0; pages = NULL; } in_mem_byte_array(const io_request &req, char *pages, byte_array_allocator &alloc): page_byte_array(alloc) { this->off = req.get_offset(); this->size = req.get_size(); this->pages = pages; } virtual off_t get_offset() const { return off; } virtual off_t get_offset_in_first_page() const { return off % PAGE_SIZE; } virtual const char *get_page(int pg_idx) const { return pages + pg_idx * PAGE_SIZE; } virtual size_t get_size() const { return size; } void lock() { ABORT_MSG("lock isn't implemented"); } void unlock() { ABORT_MSG("unlock isn't implemented"); } page_byte_array *clone() { in_mem_byte_array *arr = (in_mem_byte_array *) get_allocator().alloc(); *arr = *this; return arr; } }; class in_mem_byte_array_allocator: public byte_array_allocator { class array_initiator: public obj_initiator<in_mem_byte_array> { in_mem_byte_array_allocator *alloc; public: array_initiator(in_mem_byte_array_allocator *alloc) { this->alloc = alloc; } virtual void init(in_mem_byte_array *obj) { new (obj) in_mem_byte_array(*alloc); } }; class array_destructor: public obj_destructor<in_mem_byte_array> { public: void destroy(in_mem_byte_array *obj) { obj->~in_mem_byte_array(); } }; obj_allocator<in_mem_byte_array> allocator; public: in_mem_byte_array_allocator(thread *t): allocator( "byte-array-allocator", t->get_node_id(), false, 1024 * 1024, params.get_max_obj_alloc_size(), obj_initiator<in_mem_byte_array>::ptr(new array_initiator(this)), obj_destructor<in_mem_byte_array>::ptr(new array_destructor())) { } virtual page_byte_array *alloc() { return allocator.alloc_obj(); } virtual void free(page_byte_array *arr) { allocator.free((in_mem_byte_array *) arr); } }; class in_mem_io: public io_interface { const in_mem_graph &graph; int file_id; fifo_queue<io_request> req_buf; fifo_queue<user_compute *> compute_buf; fifo_queue<user_compute *> incomp_computes; std::unique_ptr<byte_array_allocator> array_allocator; void process_req(const io_request &req); void process_computes(); public: in_mem_io(const in_mem_graph &_graph, int file_id, thread *t): io_interface(t), graph(_graph), req_buf( get_node_id(), 1024), compute_buf(get_node_id(), 1024, true), incomp_computes(get_node_id(), 1024, true) { this->file_id = file_id; array_allocator = std::unique_ptr<byte_array_allocator>( new in_mem_byte_array_allocator(t)); } virtual int get_file_id() const { return file_id; } virtual bool support_aio() { return true; } virtual void flush_requests() { } virtual int num_pending_ios() const { return 0; } virtual io_status access(char *buf, off_t off, ssize_t size, int access_method) { assert(access_method == READ); memcpy(buf, graph.graph_data + off, size); return IO_OK; } virtual void access(io_request *requests, int num, io_status *status); virtual int wait4complete(int) { assert(compute_buf.is_empty()); if (!incomp_computes.is_empty()) { compute_buf.add(&incomp_computes); assert(incomp_computes.is_empty()); process_computes(); } return 0; } }; enum { IN_QUEUE, }; void in_mem_io::process_req(const io_request &req) { assert(req.get_req_type() == io_request::USER_COMPUTE); in_mem_byte_array byte_arr(req, graph.graph_data + ROUND_PAGE(req.get_offset()), *array_allocator); user_compute *compute = req.get_compute(); compute->run(byte_arr); // If the user compute hasn't completed and it's not in the queue, // add it to the queue. if (!compute->has_completed() && !compute->test_flag(IN_QUEUE)) { compute->set_flag(IN_QUEUE, true); if (compute_buf.is_full()) compute_buf.expand_queue(compute_buf.get_size() * 2); compute_buf.push_back(compute); } else compute->dec_ref(); if (compute->has_completed() && !compute->test_flag(IN_QUEUE)) { assert(compute->get_ref() == 0); // It might still be referenced by the graph engine. if (compute->get_ref() == 0) { compute_allocator *alloc = compute->get_allocator(); alloc->free(compute); } } } void in_mem_io::process_computes() { while (!compute_buf.is_empty()) { user_compute *compute = compute_buf.pop_front(); assert(compute->get_ref() > 0); while (compute->has_requests()) { compute->fetch_requests(this, req_buf, req_buf.get_size()); while (!req_buf.is_empty()) { io_request new_req = req_buf.pop_front(); process_req(new_req); } } if (compute->has_completed()) { compute->dec_ref(); compute->set_flag(IN_QUEUE, false); assert(compute->get_ref() == 0); if (compute->get_ref() == 0) { compute_allocator *alloc = compute->get_allocator(); alloc->free(compute); } } else incomp_computes.push_back(compute); } } void in_mem_io::access(io_request *requests, int num, io_status *) { for (int i = 0; i < num; i++) { io_request &req = requests[i]; assert(req.get_req_type() == io_request::USER_COMPUTE); // Let's possess a reference to the user compute first. process_req() // will release the reference when the user compute is completed. req.get_compute()->inc_ref(); process_req(req); } process_computes(); } class in_mem_io_factory: public file_io_factory { const in_mem_graph &graph; int file_id; public: in_mem_io_factory(const in_mem_graph &_graph, int file_id, const std::string file_name): file_io_factory(file_name), graph(_graph) { this->file_id = file_id; } virtual int get_file_id() const { return file_id; } virtual io_interface::ptr create_io(thread *t) { return io_interface::ptr(new in_mem_io(graph, file_id, t)); } virtual void destroy_io(io_interface *) { } }; in_mem_graph::ptr in_mem_graph::load_graph(const std::string &file_name) { native_file local_f(file_name); ssize_t size = local_f.get_size(); assert(size > 0); in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph()); graph->graph_size = size; graph->graph_data = (char *) malloc(size); assert(graph->graph_data); graph->graph_file_name = file_name; BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes") % graph->graph_size; FILE *fd = fopen(file_name.c_str(), "r"); if (fd == NULL) throw io_exception(std::string("can't open ") + file_name); if (fread(graph->graph_data, size, 1, fd) != 1) throw io_exception(std::string("can't read from ") + file_name); fclose(fd); graph_header *header = (graph_header *) graph->graph_data; header->verify(); return graph; } in_mem_graph::ptr in_mem_graph::load_safs_graph(const std::string &file_name) { file_io_factory::shared_ptr io_factory = ::create_io_factory(file_name, REMOTE_ACCESS); in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph()); graph->graph_size = io_factory->get_file_size(); size_t num_pages = ROUNDUP_PAGE(graph->graph_size) / PAGE_SIZE; graph->graph_data = (char *) memalign(PAGE_SIZE, num_pages * PAGE_SIZE); assert(graph->graph_data); graph->graph_file_name = file_name; BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes") % graph->graph_size; #if 0 graph->graph_file_id = io_factory->get_file_id(); #endif io_interface::ptr io = io_factory->create_io(thread::get_curr_thread()); const size_t MAX_IO_SIZE = 256 * 1024 * 1024; for (off_t off = 0; (size_t) off < graph->graph_size; off += MAX_IO_SIZE) { data_loc_t loc(io_factory->get_file_id(), off); size_t req_size = min(MAX_IO_SIZE, graph->graph_size - off); io_request req(graph->graph_data + off, loc, req_size, READ); io->access(&req, 1); io->wait4complete(1); } graph_header *header = (graph_header *) graph->graph_data; header->verify(); return graph; } file_io_factory::shared_ptr in_mem_graph::create_io_factory() const { return file_io_factory::shared_ptr(new in_mem_io_factory(*this, graph_file_id, graph_file_name)); } <commit_msg>[Graph]: in-mem graph support async I/O with callback.<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <malloc.h> #include <boost/format.hpp> #include "log.h" #include "safs_file.h" #include "cache.h" #include "slab_allocator.h" #include "native_file.h" #include "in_mem_storage.h" #include "graph_file_header.h" class in_mem_byte_array: public page_byte_array { off_t off; size_t size; const char *pages; void assign(in_mem_byte_array &arr) { this->off = arr.off; this->size = arr.size; this->pages = arr.pages; } in_mem_byte_array(in_mem_byte_array &arr) { assign(arr); } in_mem_byte_array &operator=(in_mem_byte_array &arr) { assign(arr); return *this; } public: in_mem_byte_array(byte_array_allocator &alloc): page_byte_array(alloc) { off = 0; size = 0; pages = NULL; } in_mem_byte_array(const io_request &req, char *pages, byte_array_allocator &alloc): page_byte_array(alloc) { this->off = req.get_offset(); this->size = req.get_size(); this->pages = pages; } virtual off_t get_offset() const { return off; } virtual off_t get_offset_in_first_page() const { return off % PAGE_SIZE; } virtual const char *get_page(int pg_idx) const { return pages + pg_idx * PAGE_SIZE; } virtual size_t get_size() const { return size; } void lock() { ABORT_MSG("lock isn't implemented"); } void unlock() { ABORT_MSG("unlock isn't implemented"); } page_byte_array *clone() { in_mem_byte_array *arr = (in_mem_byte_array *) get_allocator().alloc(); *arr = *this; return arr; } }; class in_mem_byte_array_allocator: public byte_array_allocator { class array_initiator: public obj_initiator<in_mem_byte_array> { in_mem_byte_array_allocator *alloc; public: array_initiator(in_mem_byte_array_allocator *alloc) { this->alloc = alloc; } virtual void init(in_mem_byte_array *obj) { new (obj) in_mem_byte_array(*alloc); } }; class array_destructor: public obj_destructor<in_mem_byte_array> { public: void destroy(in_mem_byte_array *obj) { obj->~in_mem_byte_array(); } }; obj_allocator<in_mem_byte_array> allocator; public: in_mem_byte_array_allocator(thread *t): allocator( "byte-array-allocator", t->get_node_id(), false, 1024 * 1024, params.get_max_obj_alloc_size(), obj_initiator<in_mem_byte_array>::ptr(new array_initiator(this)), obj_destructor<in_mem_byte_array>::ptr(new array_destructor())) { } virtual page_byte_array *alloc() { return allocator.alloc_obj(); } virtual void free(page_byte_array *arr) { allocator.free((in_mem_byte_array *) arr); } }; class in_mem_io: public io_interface { const in_mem_graph &graph; int file_id; fifo_queue<io_request> req_buf; fifo_queue<user_compute *> compute_buf; fifo_queue<user_compute *> incomp_computes; std::unique_ptr<byte_array_allocator> array_allocator; callback *cb; void process_req(const io_request &req); void process_computes(); public: in_mem_io(const in_mem_graph &_graph, int file_id, thread *t): io_interface(t), graph(_graph), req_buf( get_node_id(), 1024), compute_buf(get_node_id(), 1024, true), incomp_computes(get_node_id(), 1024, true) { this->file_id = file_id; array_allocator = std::unique_ptr<byte_array_allocator>( new in_mem_byte_array_allocator(t)); cb = NULL; } virtual int get_file_id() const { return file_id; } virtual bool support_aio() { return true; } virtual bool set_callback(callback *cb) { this->cb = cb; } virtual callback *get_callback() { return cb; } virtual void flush_requests() { } virtual int num_pending_ios() const { return 0; } virtual io_status access(char *buf, off_t off, ssize_t size, int access_method) { assert(access_method == READ); memcpy(buf, graph.graph_data + off, size); return IO_OK; } virtual void access(io_request *requests, int num, io_status *status); virtual int wait4complete(int) { assert(compute_buf.is_empty()); if (!incomp_computes.is_empty()) { compute_buf.add(&incomp_computes); assert(incomp_computes.is_empty()); process_computes(); } return 0; } }; enum { IN_QUEUE, }; void in_mem_io::process_req(const io_request &req) { assert(req.get_req_type() == io_request::USER_COMPUTE); in_mem_byte_array byte_arr(req, graph.graph_data + ROUND_PAGE(req.get_offset()), *array_allocator); user_compute *compute = req.get_compute(); compute->run(byte_arr); // If the user compute hasn't completed and it's not in the queue, // add it to the queue. if (!compute->has_completed() && !compute->test_flag(IN_QUEUE)) { compute->set_flag(IN_QUEUE, true); if (compute_buf.is_full()) compute_buf.expand_queue(compute_buf.get_size() * 2); compute_buf.push_back(compute); } else compute->dec_ref(); if (compute->has_completed() && !compute->test_flag(IN_QUEUE)) { assert(compute->get_ref() == 0); // It might still be referenced by the graph engine. if (compute->get_ref() == 0) { compute_allocator *alloc = compute->get_allocator(); alloc->free(compute); } } } void in_mem_io::process_computes() { while (!compute_buf.is_empty()) { user_compute *compute = compute_buf.pop_front(); assert(compute->get_ref() > 0); while (compute->has_requests()) { compute->fetch_requests(this, req_buf, req_buf.get_size()); while (!req_buf.is_empty()) { io_request new_req = req_buf.pop_front(); process_req(new_req); } } if (compute->has_completed()) { compute->dec_ref(); compute->set_flag(IN_QUEUE, false); assert(compute->get_ref() == 0); if (compute->get_ref() == 0) { compute_allocator *alloc = compute->get_allocator(); alloc->free(compute); } } else incomp_computes.push_back(compute); } } void in_mem_io::access(io_request *requests, int num, io_status *) { for (int i = 0; i < num; i++) { io_request &req = requests[i]; if (req.get_req_type() == io_request::USER_COMPUTE) { // Let's possess a reference to the user compute first. process_req() // will release the reference when the user compute is completed. req.get_compute()->inc_ref(); process_req(req); } else { assert(req.get_req_type() == io_request::BASIC_REQ); memcpy(req.get_buf(), graph.graph_data + req.get_offset(), req.get_size()); io_request *reqs[1]; reqs[0] = &req; this->get_callback()->invoke(reqs, 1); } } process_computes(); } class in_mem_io_factory: public file_io_factory { const in_mem_graph &graph; int file_id; public: in_mem_io_factory(const in_mem_graph &_graph, int file_id, const std::string file_name): file_io_factory(file_name), graph(_graph) { this->file_id = file_id; } virtual int get_file_id() const { return file_id; } virtual io_interface::ptr create_io(thread *t) { return io_interface::ptr(new in_mem_io(graph, file_id, t)); } virtual void destroy_io(io_interface *) { } }; in_mem_graph::ptr in_mem_graph::load_graph(const std::string &file_name) { native_file local_f(file_name); ssize_t size = local_f.get_size(); assert(size > 0); in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph()); graph->graph_size = size; graph->graph_data = (char *) malloc(size); assert(graph->graph_data); graph->graph_file_name = file_name; BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes") % graph->graph_size; FILE *fd = fopen(file_name.c_str(), "r"); if (fd == NULL) throw io_exception(std::string("can't open ") + file_name); if (fread(graph->graph_data, size, 1, fd) != 1) throw io_exception(std::string("can't read from ") + file_name); fclose(fd); graph_header *header = (graph_header *) graph->graph_data; header->verify(); return graph; } in_mem_graph::ptr in_mem_graph::load_safs_graph(const std::string &file_name) { file_io_factory::shared_ptr io_factory = ::create_io_factory(file_name, REMOTE_ACCESS); in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph()); graph->graph_size = io_factory->get_file_size(); size_t num_pages = ROUNDUP_PAGE(graph->graph_size) / PAGE_SIZE; graph->graph_data = (char *) memalign(PAGE_SIZE, num_pages * PAGE_SIZE); assert(graph->graph_data); graph->graph_file_name = file_name; BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes") % graph->graph_size; #if 0 graph->graph_file_id = io_factory->get_file_id(); #endif io_interface::ptr io = io_factory->create_io(thread::get_curr_thread()); const size_t MAX_IO_SIZE = 256 * 1024 * 1024; for (off_t off = 0; (size_t) off < graph->graph_size; off += MAX_IO_SIZE) { data_loc_t loc(io_factory->get_file_id(), off); size_t req_size = min(MAX_IO_SIZE, graph->graph_size - off); io_request req(graph->graph_data + off, loc, req_size, READ); io->access(&req, 1); io->wait4complete(1); } graph_header *header = (graph_header *) graph->graph_data; header->verify(); return graph; } file_io_factory::shared_ptr in_mem_graph::create_io_factory() const { return file_io_factory::shared_ptr(new in_mem_io_factory(*this, graph_file_id, graph_file_name)); } <|endoftext|>
<commit_before>// bitmessage cracker, build with g++ or MSVS to a shared library, use included python code for usage under bitmessage #ifdef _WIN32 #include "Winsock.h" #include "Windows.h" #define uint64_t unsigned __int64 #else #include <arpa/inet.h> #include <pthread.h> #include <stdint.h> #endif #include <string.h> #include <stdio.h> #include <stdlib.h> #include "openssl/sha.h" #define HASH_SIZE 64 #define BUFLEN 16384 #if defined(__GNUC__) #define EXPORT __attribute__ ((__visibility__("default"))) #elif defined(_WIN32) #define EXPORT __declspec(dllexport) #endif #define ntohll(x) ( ( (uint64_t)(ntohl( (unsigned int)((x << 32) >> 32) )) << 32) | ntohl( ((unsigned int)(x >> 32)) ) ) unsigned long long max_val; unsigned char *initialHash; unsigned long long successval = 0; unsigned int numthreads = 0; #ifdef _WIN32 DWORD WINAPI threadfunc(LPVOID lpParameter) { #else void * threadfunc(void* param) { #endif unsigned int incamt = *((unsigned int*)lpParameter); SHA512_CTX sha; unsigned char buf[HASH_SIZE + sizeof(uint64_t)] = { 0 }; unsigned char output[HASH_SIZE] = { 0 }; memcpy(buf + sizeof(uint64_t), initialHash, HASH_SIZE); unsigned long long tmpnonce = incamt; unsigned long long * nonce = (unsigned long long *)buf; unsigned long long * hash = (unsigned long long *)output; while (successval == 0) { tmpnonce += numthreads; (*nonce) = ntohll(tmpnonce); /* increment nonce */ SHA512_Init(&sha); SHA512_Update(&sha, buf, HASH_SIZE + sizeof(uint64_t)); SHA512_Final(output, &sha); SHA512_Init(&sha); SHA512_Update(&sha, output, HASH_SIZE); SHA512_Final(output, &sha); if (ntohll(*hash) < max_val) { successval = tmpnonce; } } return NULL; } void getnumthreads() { #ifdef _WIN32 DWORD_PTR dwProcessAffinity, dwSystemAffinity; #elif __linux__ cpu_set_t dwProcessAffinity; #else int dwProcessAffinity = 0; int32_t core_count = 0; #endif unsigned int len = sizeof(dwProcessAffinity); if (numthreads > 0) return; #ifdef _WIN32 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinity, &dwSystemAffinity); #elif __linux__ sched_getaffinity(0, len, &dwProcessAffinity); #else if (sysctlbyname("hw.logicalcpu", &core_count, &len, 0, 0)) numthreads = core_count; #endif for (unsigned int i = 0; i < len * 8; i++) if (dwProcessAffinity & (1i64 << i)) { numthreads++; printf("Detected core on: %u\n", i); } printf("Affinity: %lx\n", (unsigned long) dwProcessAffinity); printf("Number of threads: %i\n", (int)numthreads); } extern "C" EXPORT unsigned long long BitmessagePOW(unsigned char * starthash, unsigned long long target) { successval = 0; max_val = target; getnumthreads(); initialHash = (unsigned char *)starthash; # ifdef _WIN32 HANDLE* threads = (HANDLE*)calloc(sizeof(HANDLE), numthreads); # else pthread_t* threads = (pthread_t*)calloc(sizeof(pthread_t), numthreads); struct sched_param schparam; # ifdef __linux__ schparam.sched_priority = 0; # else schparam.sched_priority = PTHREAD_MIN_PRIORITY; # endif # endif unsigned int *threaddata = (unsigned int *)calloc(sizeof(unsigned int), numthreads); for (UINT i = 0; i < numthreads; i++) { threaddata[i] = i; # ifdef _WIN32 threads[i] = CreateThread(NULL, 0, threadfunc, (LPVOID)&threaddata[i], 0, NULL); SetThreadPriority(threads[i], THREAD_PRIORITY_IDLE); # else pthread_create(&threads[i], NULL, threadfunc, (void*)&threaddata[i]); # ifdef __linux__ pthread_setschedparam(threads[i], SCHED_IDLE, &schparam); # else pthread_setschedparam(threads[i], SCHED_RR, &schparam) # endif # endif } # ifdef _WIN32 WaitForMultipleObjects(numthreads, threads, TRUE, INFINITE); # else for (int i = 0; i < numthreads; i++) { pthread_join(threads[i], NULL); } # endif free(threads); free(threaddata); return successval; } <commit_msg>Compile fixes<commit_after>// bitmessage cracker, build with g++ or MSVS to a shared library, use included python code for usage under bitmessage #ifdef _WIN32 #include "Winsock.h" #include "Windows.h" #define uint64_t unsigned __int64 #else #include <arpa/inet.h> #include <pthread.h> #include <stdint.h> #endif #include <string.h> #include <stdio.h> #include <stdlib.h> #ifdef __APPLE__ #include <sys/types.h> #include <sys/sysctl.h> #endif #include "openssl/sha.h" #define HASH_SIZE 64 #define BUFLEN 16384 #if defined(__GNUC__) #define EXPORT __attribute__ ((__visibility__("default"))) #elif defined(_WIN32) #define EXPORT __declspec(dllexport) #endif #ifndef __APPLE__ #define ntohll(x) ( ( (uint64_t)(ntohl( (unsigned int)((x << 32) >> 32) )) << 32) | ntohl( ((unsigned int)(x >> 32)) ) ) #endif unsigned long long max_val; unsigned char *initialHash; unsigned long long successval = 0; unsigned int numthreads = 0; #ifdef _WIN32 DWORD WINAPI threadfunc(LPVOID param) { #else void * threadfunc(void* param) { #endif unsigned int incamt = *((unsigned int*)param); SHA512_CTX sha; unsigned char buf[HASH_SIZE + sizeof(uint64_t)] = { 0 }; unsigned char output[HASH_SIZE] = { 0 }; memcpy(buf + sizeof(uint64_t), initialHash, HASH_SIZE); unsigned long long tmpnonce = incamt; unsigned long long * nonce = (unsigned long long *)buf; unsigned long long * hash = (unsigned long long *)output; while (successval == 0) { tmpnonce += numthreads; (*nonce) = ntohll(tmpnonce); /* increment nonce */ SHA512_Init(&sha); SHA512_Update(&sha, buf, HASH_SIZE + sizeof(uint64_t)); SHA512_Final(output, &sha); SHA512_Init(&sha); SHA512_Update(&sha, output, HASH_SIZE); SHA512_Final(output, &sha); if (ntohll(*hash) < max_val) { successval = tmpnonce; } } return NULL; } void getnumthreads() { #ifdef _WIN32 DWORD_PTR dwProcessAffinity, dwSystemAffinity; #elif __linux__ cpu_set_t dwProcessAffinity; #else int dwProcessAffinity = 0; int32_t core_count = 0; #endif size_t len = sizeof(dwProcessAffinity); if (numthreads > 0) return; #ifdef _WIN32 GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinity, &dwSystemAffinity); #elif __linux__ sched_getaffinity(0, len, &dwProcessAffinity); #else if (sysctlbyname("hw.logicalcpu", &core_count, &len, 0, 0) == 0) numthreads = core_count; #endif for (unsigned int i = 0; i < len * 8; i++) #if defined(_WIN32) if (dwProcessAffinity & (1i64 << i)) { #elif defined __linux__ if (CPU_ISSET(i, &dwProcessAffinity)) { #else if (dwProcessAffinity & (1 << i)) { #endif numthreads++; printf("Detected core on: %u\n", i); } printf("Number of threads: %i\n", (int)numthreads); } extern "C" EXPORT unsigned long long BitmessagePOW(unsigned char * starthash, unsigned long long target) { successval = 0; max_val = target; getnumthreads(); initialHash = (unsigned char *)starthash; # ifdef _WIN32 HANDLE* threads = (HANDLE*)calloc(sizeof(HANDLE), numthreads); # else pthread_t* threads = (pthread_t*)calloc(sizeof(pthread_t), numthreads); struct sched_param schparam; schparam.sched_priority = 0; # endif unsigned int *threaddata = (unsigned int *)calloc(sizeof(unsigned int), numthreads); for (unsigned int i = 0; i < numthreads; i++) { threaddata[i] = i; # ifdef _WIN32 threads[i] = CreateThread(NULL, 0, threadfunc, (LPVOID)&threaddata[i], 0, NULL); SetThreadPriority(threads[i], THREAD_PRIORITY_IDLE); # else pthread_create(&threads[i], NULL, threadfunc, (void*)&threaddata[i]); # ifdef __linux__ pthread_setschedparam(threads[i], SCHED_IDLE, &schparam); # else pthread_setschedparam(threads[i], SCHED_RR, &schparam); # endif # endif } # ifdef _WIN32 WaitForMultipleObjects(numthreads, threads, TRUE, INFINITE); # else for (unsigned int i = 0; i < numthreads; i++) { pthread_join(threads[i], NULL); } # endif free(threads); free(threaddata); return successval; } <|endoftext|>
<commit_before>/* Copyright 2015-2021 Igor Petrovic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <avr/power.h> #include <avr/eeprom.h> #include <avr/wdt.h> #include "board/Board.h" #include "board/Internal.h" #include "board/common/io/Helpers.h" #include "core/src/general/ADC.h" #include "core/src/arch/avr/Misc.h" #include "core/src/general/IO.h" #include "core/src/general/Interrupt.h" #include "core/src/general/Timing.h" #include "Pins.h" extern "C" void __cxa_pure_virtual() { while (1) ; } namespace Board { namespace detail { namespace setup { void bootloader() { DISABLE_INTERRUPTS(); //clear reset source MCUSR &= ~(1 << EXTRF); //disable watchdog MCUSR &= ~(1 << WDRF); wdt_disable(); //disable clock division clock_prescale_set(clock_div_1); detail::setup::io(); //relocate the interrupt vector table to the bootloader section MCUCR = (1 << IVCE); MCUCR = (1 << IVSEL); ENABLE_INTERRUPTS(); #if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED) Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD); #endif } void application() { DISABLE_INTERRUPTS(); //relocate the interrupt vector table to the application section MCUCR = (1 << IVCE); MCUCR = (0 << IVSEL); //clear reset source MCUSR &= ~(1 << EXTRF); //disable watchdog MCUSR &= ~(1 << WDRF); wdt_disable(); //disable clock division clock_prescale_set(clock_div_1); detail::setup::io(); detail::setup::adc(); #if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED) Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD); #endif detail::setup::usb(); detail::setup::timers(); ENABLE_INTERRUPTS(); #ifndef USB_LINK_MCU //add some delay and remove initial readout of digital inputs core::timing::waitMs(10); detail::io::flushInputReadings(); #endif } #ifdef ANALOG_SUPPORTED void adc() { core::adc::conf_t adcConfiguration; adcConfiguration.prescaler = core::adc::prescaler_t::p128; #ifdef ADC_EXT_REF adcConfiguration.vref = core::adc::vRef_t::aref; #else adcConfiguration.vref = core::adc::vRef_t::avcc; #endif for (int i = 0; i < MAX_ADC_CHANNELS; i++) core::adc::disconnectDigitalIn(Board::detail::map::adcChannel(i)); core::adc::setup(adcConfiguration); core::adc::setChannel(Board::detail::map::adcChannel(0)); for (int i = 0; i < 3; i++) core::adc::read(); //few dummy reads to init ADC core::adc::enableInterrupt(); core::adc::startConversion(); } #endif void timers() { //set timer0 to ctc, used for millis/led matrix //clear timer0 conf TCCR0A = 0; TCCR0B = 0; TIMSK0 = 0; TCCR0A |= (1 << WGM01); //CTC mode TCCR0B |= (1 << CS01) | (1 << CS00); //prescaler 64 OCR0A = 124; //500us TIMSK0 |= (1 << OCIE0A); //compare match interrupt } void io() { #ifdef NUMBER_OF_IN_SR CORE_IO_CONFIG(SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input); CORE_IO_CONFIG(SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::output); CORE_IO_SET_LOW(SR_IN_CLK_PORT, SR_IN_CLK_PIN); CORE_IO_SET_HIGH(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN); #else for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++) { core::io::mcuPin_t pin = detail::map::buttonPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input); #ifndef BUTTONS_EXT_PULLUPS CORE_IO_SET_HIGH(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); #endif } #endif #ifdef NUMBER_OF_BUTTON_COLUMNS CORE_IO_CONFIG(DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::output); CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0); CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1); CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2); #endif #ifdef NUMBER_OF_OUT_SR CORE_IO_CONFIG(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::output); #ifdef SR_OUT_OE_PORT CORE_IO_CONFIG(SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::output); #endif //init all outputs on shift register CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); detail::io::sr595wait(); CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); #ifdef SR_OUT_OE_PORT CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN); #endif #else #ifdef NUMBER_OF_LED_ROWS CORE_IO_CONFIG(DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::output); CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0); CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1); CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2); for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) #else for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) #endif { core::io::mcuPin_t pin = detail::map::ledPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output); EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #if MAX_ADC_CHANNELS > 0 for (int i = 0; i < MAX_ADC_CHANNELS; i++) { core::io::mcuPin_t pin = detail::map::adcPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input); CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #ifdef NUMBER_OF_MUX CORE_IO_CONFIG(MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::output); CORE_IO_CONFIG(MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::output); CORE_IO_CONFIG(MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::output); #ifdef MUX_PORT_S3 CORE_IO_CONFIG(MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::output); #endif #endif #ifdef BTLDR_BUTTON_PORT CORE_IO_CONFIG(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input); CORE_IO_SET_HIGH(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN); #endif #ifdef LED_INDICATORS CORE_IO_CONFIG(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::output); INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN); INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN); INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN); INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN); #endif #ifdef LED_BTLDR_PORT CORE_IO_CONFIG(LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::output); CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN); #endif #ifdef TOTAL_UNUSED_IO for (int i = 0; i < TOTAL_UNUSED_IO; i++) { core::io::mcuPin_t pin = detail::map::unusedPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output); CORE_IO_SET_STATE(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), detail::map::unusedPinState(i)); } #endif } } // namespace setup } // namespace detail } // namespace Board<commit_msg>board/avr: re/implement __throw_bad_function_call and __cxa_pure_virtual<commit_after>/* Copyright 2015-2021 Igor Petrovic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <avr/power.h> #include <avr/eeprom.h> #include <avr/wdt.h> #include "board/Board.h" #include "board/Internal.h" #include "board/common/io/Helpers.h" #include "core/src/general/ADC.h" #include "core/src/arch/avr/Misc.h" #include "core/src/general/IO.h" #include "core/src/general/Interrupt.h" #include "core/src/general/Timing.h" #include "Pins.h" extern "C" void __cxa_pure_virtual() { Board::detail::errorHandler(); } namespace std { void __throw_bad_function_call() { Board::detail::errorHandler(); } } // namespace std namespace Board { namespace detail { namespace setup { void bootloader() { DISABLE_INTERRUPTS(); //clear reset source MCUSR &= ~(1 << EXTRF); //disable watchdog MCUSR &= ~(1 << WDRF); wdt_disable(); //disable clock division clock_prescale_set(clock_div_1); detail::setup::io(); //relocate the interrupt vector table to the bootloader section MCUCR = (1 << IVCE); MCUCR = (1 << IVSEL); ENABLE_INTERRUPTS(); #if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED) Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD); #endif } void application() { DISABLE_INTERRUPTS(); //relocate the interrupt vector table to the application section MCUCR = (1 << IVCE); MCUCR = (0 << IVSEL); //clear reset source MCUSR &= ~(1 << EXTRF); //disable watchdog MCUSR &= ~(1 << WDRF); wdt_disable(); //disable clock division clock_prescale_set(clock_div_1); detail::setup::io(); detail::setup::adc(); #if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED) Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD); #endif detail::setup::usb(); detail::setup::timers(); ENABLE_INTERRUPTS(); #ifndef USB_LINK_MCU //add some delay and remove initial readout of digital inputs core::timing::waitMs(10); detail::io::flushInputReadings(); #endif } #ifdef ANALOG_SUPPORTED void adc() { core::adc::conf_t adcConfiguration; adcConfiguration.prescaler = core::adc::prescaler_t::p128; #ifdef ADC_EXT_REF adcConfiguration.vref = core::adc::vRef_t::aref; #else adcConfiguration.vref = core::adc::vRef_t::avcc; #endif for (int i = 0; i < MAX_ADC_CHANNELS; i++) core::adc::disconnectDigitalIn(Board::detail::map::adcChannel(i)); core::adc::setup(adcConfiguration); core::adc::setChannel(Board::detail::map::adcChannel(0)); for (int i = 0; i < 3; i++) core::adc::read(); //few dummy reads to init ADC core::adc::enableInterrupt(); core::adc::startConversion(); } #endif void timers() { //set timer0 to ctc, used for millis/led matrix //clear timer0 conf TCCR0A = 0; TCCR0B = 0; TIMSK0 = 0; TCCR0A |= (1 << WGM01); //CTC mode TCCR0B |= (1 << CS01) | (1 << CS00); //prescaler 64 OCR0A = 124; //500us TIMSK0 |= (1 << OCIE0A); //compare match interrupt } void io() { #ifdef NUMBER_OF_IN_SR CORE_IO_CONFIG(SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input); CORE_IO_CONFIG(SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::output); CORE_IO_SET_LOW(SR_IN_CLK_PORT, SR_IN_CLK_PIN); CORE_IO_SET_HIGH(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN); #else for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++) { core::io::mcuPin_t pin = detail::map::buttonPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input); #ifndef BUTTONS_EXT_PULLUPS CORE_IO_SET_HIGH(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); #endif } #endif #ifdef NUMBER_OF_BUTTON_COLUMNS CORE_IO_CONFIG(DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::output); CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0); CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1); CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2); #endif #ifdef NUMBER_OF_OUT_SR CORE_IO_CONFIG(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::output); #ifdef SR_OUT_OE_PORT CORE_IO_CONFIG(SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::output); #endif //init all outputs on shift register CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) { EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN); CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); detail::io::sr595wait(); CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN); } CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN); #ifdef SR_OUT_OE_PORT CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN); #endif #else #ifdef NUMBER_OF_LED_ROWS CORE_IO_CONFIG(DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::output); CORE_IO_CONFIG(DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::output); CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0); CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1); CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2); for (int i = 0; i < NUMBER_OF_LED_ROWS; i++) #else for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++) #endif { core::io::mcuPin_t pin = detail::map::ledPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output); EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #if MAX_ADC_CHANNELS > 0 for (int i = 0; i < MAX_ADC_CHANNELS; i++) { core::io::mcuPin_t pin = detail::map::adcPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input); CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin)); } #endif #ifdef NUMBER_OF_MUX CORE_IO_CONFIG(MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::output); CORE_IO_CONFIG(MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::output); CORE_IO_CONFIG(MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::output); #ifdef MUX_PORT_S3 CORE_IO_CONFIG(MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::output); #endif #endif #ifdef BTLDR_BUTTON_PORT CORE_IO_CONFIG(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input); CORE_IO_SET_HIGH(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN); #endif #ifdef LED_INDICATORS CORE_IO_CONFIG(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::output); CORE_IO_CONFIG(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::output); INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN); INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN); INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN); INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN); #endif #ifdef LED_BTLDR_PORT CORE_IO_CONFIG(LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::output); CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN); #endif #ifdef TOTAL_UNUSED_IO for (int i = 0; i < TOTAL_UNUSED_IO; i++) { core::io::mcuPin_t pin = detail::map::unusedPin(i); CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output); CORE_IO_SET_STATE(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), detail::map::unusedPinState(i)); } #endif } } // namespace setup } // namespace detail } // namespace Board<|endoftext|>
<commit_before>// Copyright (c) 2013 Stanislas Polu. // See the LICENSE file. #include "exo_browser/src/browser/ui/exo_browser.h" #include "base/auto_reset.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_view.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_controller.h" #include "content/public/common/renderer_preferences.h" #include "content/public/browser/favicon_status.h" #include "exo_browser/src/common/switches.h" #include "exo_browser/src/browser/browser_main_parts.h" #include "exo_browser/src/browser/content_browser_client.h" #include "exo_browser/src/browser/ui/dialog/javascript_dialog_manager.h" #include "exo_browser/src/common/messages.h" #include "exo_browser/src/browser/ui/exo_frame.h" #include "exo_browser/src/node/node_thread.h" #include "exo_browser/src/node/api/exo_browser_wrap.h" using namespace content; namespace exo_browser { const int ExoBrowser::kDefaultWindowWidth = 800; const int ExoBrowser::kDefaultWindowHeight = 600; std::vector<ExoBrowser*> ExoBrowser::s_instances; ExoBrowser::ExoBrowser( ExoBrowserWrap* wrapper) : window_(NULL), #if defined(OS_WIN) && !defined(USE_AURA) default_edit_wnd_proc_(0), #endif wrapper_(wrapper), is_killed_(false) { s_instances.push_back(this); } ExoBrowser::~ExoBrowser() { LOG(INFO) << "ExoBrowser Destructor"; PlatformCleanUp(); for (size_t i = 0; i < s_instances.size(); ++i) { if (s_instances[i] == this) { s_instances.erase(s_instances.begin() + i); break; } } } void ExoBrowser::Initialize() { PlatformInitialize( gfx::Size(kDefaultWindowWidth, kDefaultWindowHeight)); } ExoBrowser* ExoBrowser::CreateNew( ExoBrowserWrap* wrapper, const gfx::Size& size) { ExoBrowser* browser = new ExoBrowser(wrapper); browser->PlatformCreateWindow(size.width(), size.height()); return browser; } void ExoBrowser::KillAll() { std::vector<ExoBrowser*> open(s_instances); for (size_t i = 0; i < open.size(); ++i) { open[i]->Kill(); } base::MessageLoop::current()->RunUntilIdle(); } ExoFrame* ExoBrowser::FrameForWebContents( const WebContents* web_contents) { std::map<std::string, ExoFrame*>::iterator p_it; for(p_it = pages_.begin(); p_it != pages_.end(); ++p_it) { if((p_it->second)->web_contents_ == web_contents) { return (p_it->second); } } std::map<CONTROL_TYPE, ExoFrame*>::iterator c_it; for(c_it = controls_.begin(); c_it != controls_.end(); ++c_it) { if((c_it->second)->web_contents_ == web_contents) { return (c_it->second); } } return NULL; } void ExoBrowser::SetControl( CONTROL_TYPE type, ExoFrame* frame) { std::map<CONTROL_TYPE, ExoFrame*>::iterator it = controls_.find(type); if(it == controls_.end()) { UnsetControl(type); } controls_[type] = frame; frame->SetType(ExoFrame::CONTROL_FRAME); frame->SetParent(this); PlatformSetControl(type, frame); } void ExoBrowser::UnsetControl( CONTROL_TYPE type) { std::map<CONTROL_TYPE, ExoFrame*>::iterator it = controls_.find(type); if(it != controls_.end()) { PlatformUnsetControl(it->first, it->second); (it->second)->SetType(ExoFrame::NOTYPE_FRAME); (it->second)->SetParent(NULL); controls_.erase(it); } /* Otherwise, nothing to do */ } void ExoBrowser::SetControlDimension( CONTROL_TYPE type, int size) { PlatformSetControlDimension(type, size); } void ExoBrowser::AddPage( ExoFrame* frame) { frame->SetType(ExoFrame::PAGE_FRAME); frame->SetParent(this); pages_[frame->name()] = frame; PlatformAddPage(frame); } void ExoBrowser::RemovePage( const std::string& name) { std::map<std::string, ExoFrame*>::iterator it = pages_.find(name); if(it != pages_.end()) { PlatformRemovePage(it->second); (it->second)->SetType(ExoFrame::NOTYPE_FRAME); (it->second)->SetParent(NULL); pages_.erase(it); } /* Otherwise, nothing to do */ } void ExoBrowser::ShowPage( const std::string& name) { std::map<std::string, ExoFrame*>::iterator it = pages_.find(name); if(it != pages_.end()) { PlatformShowPage(it->second); } /* Otherwise, nothing to do */ } void ExoBrowser::RemoveFrame( const std::string& name) { std::map<std::string, ExoFrame*>::iterator p_it; for(p_it = pages_.begin(); p_it != pages_.end(); ++p_it) { if((p_it->second)->name() == name) { return RemovePage((p_it->second)->name()); } } std::map<CONTROL_TYPE, ExoFrame*>::iterator c_it; for(c_it = controls_.begin(); c_it != controls_.end(); ++c_it) { if((c_it->second)->name() == name) { return UnsetControl(c_it->first); } } } void ExoBrowser::Kill() { is_killed_ = true; while(pages_.begin() != pages_.end()) { RemovePage((pages_.begin()->second)->name()); } while(controls_.begin() != controls_.end()) { UnsetControl(controls_.begin()->first); } PlatformKill(); NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchKill, wrapper_)); } WebContents* ExoBrowser::OpenURLFromTab( WebContents* source, const OpenURLParams& params) { ExoFrame* frame = FrameForWebContents(source); if(frame) { /* Relevant header files: */ /* ui/base/window_open_disposition.h */ /* content/public/common/page_transition_types_list.h */ /* TODO(spolu): Use params.transition */ /* TODO(spolu): Use params.referrer */ NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchOpenURL, wrapper_, params.url.spec(), params.disposition, frame->name())); } else { /* This is used when a newly created WebContents is not yet assigned to */ /* its fimal ExoFrame/ExoBrowser but needs a delegate to navigate to its */ /* targeted delegate. See ExoBrowser::WebContentsCreated. */ source->GetController().LoadURL( params.url, params.referrer, params.transition, std::string()); } return NULL; } void ExoBrowser::RequestToLockMouse( WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { /* Default implementation */ web_contents->GotResponseToLockMouseRequest(true); } void ExoBrowser::CloseContents( WebContents* source) { ExoFrame* frame = FrameForWebContents(source); if(frame) { NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchFrameClose, wrapper_, frame->name())); } } bool ExoBrowser::PreHandleKeyboardEvent( WebContents* source, const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { ExoFrame* frame = FrameForWebContents(source); if(frame) { NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchFrameKeyboard, wrapper_, frame->name(), event)); } return false; } void ExoBrowser::HandleKeyboardEvent( WebContents* source, const NativeWebKeyboardEvent& event) { //LOG(INFO) << "HandleKeyboardEvent " << event.windowsKeyCode; } void ExoBrowser::NavigationStateChanged( const WebContents* source, unsigned changed_flags) { ExoFrame* frame = FrameForWebContents(source); std::vector<ExoBrowserWrap::NavigationEntry> entries; for(int i = 0; i < frame->web_contents()->GetController().GetEntryCount(); i++) { content::NavigationEntry *entry = frame->web_contents_->GetController().GetEntryAtIndex(i); ExoBrowserWrap::NavigationEntry e; e.url_ = entry->GetURL().spec(); e.virtual_url_ = entry->GetVirtualURL().spec(); e.title_ = UTF16ToUTF8(entry->GetTitle()); /* TODO(spolu): entry->GetFavicon().url.spec() */ e.visible_ = (entry == frame->web_contents()->GetController().GetVisibleEntry()); e.timestamp_ = entry->GetTimestamp().ToInternalValue() / 1000; e.id_ = entry->GetUniqueID(); switch(entry->GetPageType()) { case content::PAGE_TYPE_ERROR: e.type_ = "error"; break; case content::PAGE_TYPE_INTERSTITIAL: e.type_ = "interstitial"; break; default: e.type_ = "normal"; break; } switch(entry->GetSSL().security_style) { case content::SECURITY_STYLE_UNAUTHENTICATED: e.ssl_security_type_ = "unauthenticated"; break; case content::SECURITY_STYLE_AUTHENTICATION_BROKEN: e.ssl_security_type_ = "broken"; break; case content::SECURITY_STYLE_AUTHENTICATED: e.ssl_security_type_ = "authenticated"; break; default: e.ssl_security_type_ = "unknown"; } e.ssl_cert_status_ = entry->GetSSL().cert_status; e.ssl_content_status_ = entry->GetSSL().content_status; entries.push_back(e); } bool can_go_back = frame->web_contents()->GetController().CanGoBack(); bool can_go_forward = frame->web_contents()->GetController().CanGoForward(); if(frame) { NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchNavigationState, wrapper_, frame->name(), entries, can_go_back, can_go_forward)); } } void ExoBrowser::WebContentsCreated( WebContents* source_contents, int64 source_frame_id, const string16& frame_name, const GURL& target_url, WebContents* new_contents) { LOG(INFO) << "WebContentsCreated: " << target_url << "\nframe_name: " << frame_name << "\nsource_frame_id: " << source_frame_id << "\nsource_frame_id: " << source_frame_id << "\nnew_contents: " << new_contents; /* TODO(spolu): Call into API if necessary */ /* We set this ExoBrowser as temporary WebContentsDelegate the */ /* OpenURLForTab method may need to be called for some WebContents, esp. */ /* when clicking on a link with `target="_blank"` and `rel="norerferrer"` */ /* This delegate will get overriden when the new ExoFrame is later */ /* asynchronously added to an ExoBrowser. */ new_contents->SetDelegate(this); } void ExoBrowser::AddNewContents( WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture, bool* was_blocked) { LOG(INFO) << "AddNewContents: " << (was_blocked ? *was_blocked : false) << "\nuser_gesture: " << user_gesture << "\ndisposition: " << disposition << "\nsource: " << source << "\nsource url: " << source->GetVisibleURL() << "\nnew_contents: " << new_contents << "\nnew_contents url: " << new_contents->GetVisibleURL() << "\nRenderProcessHost: " << new_contents->GetRenderProcessHost() << "\nRenderViewHost: " << new_contents->GetRenderViewHost() << "\nView: " << new_contents->GetView() << "\nWaiting Response: " << new_contents->IsWaitingForResponse() << "\nInterstitial: " << new_contents->GetInterstitialPage(); ExoFrame* src_frame = FrameForWebContents(source); DCHECK(src_frame != NULL); if(src_frame) { /* We generate a unique name for this new frame */ std::ostringstream oss; static int pop_cnt = 0; oss << src_frame->name() << "-" << (++pop_cnt); ExoFrame* new_frame = new ExoFrame(oss.str(), new_contents); NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchFrameCreated, wrapper_, src_frame->name(), disposition, initial_pos, new_frame)); } } JavaScriptDialogManager* ExoBrowser::GetJavaScriptDialogManager() { /* TODO(spolu): Eventually Move to API */ if (!dialog_manager_) dialog_manager_.reset(new ExoBrowserJavaScriptDialogManager()); return dialog_manager_.get(); } void ExoBrowser::ActivateContents( WebContents* contents) { LOG(INFO) << "Activate Content"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API */ } void ExoBrowser::DeactivateContents( WebContents* contents) { LOG(INFO) << "Dectivate Content"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API (blur) */ } void ExoBrowser::RendererUnresponsive( WebContents* source) { LOG(INFO) << "RendererUnresponsive"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API */ } void ExoBrowser::WorkerCrashed( WebContents* source) { LOG(INFO) << "WorkerCrashed"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API */ } } // namespace exo_browser <commit_msg>Hotfix<commit_after>// Copyright (c) 2013 Stanislas Polu. // See the LICENSE file. #include "exo_browser/src/browser/ui/exo_browser.h" #include "base/auto_reset.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_view.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_controller.h" #include "content/public/common/renderer_preferences.h" #include "content/public/browser/favicon_status.h" #include "exo_browser/src/common/switches.h" #include "exo_browser/src/browser/browser_main_parts.h" #include "exo_browser/src/browser/content_browser_client.h" #include "exo_browser/src/browser/ui/dialog/javascript_dialog_manager.h" #include "exo_browser/src/common/messages.h" #include "exo_browser/src/browser/ui/exo_frame.h" #include "exo_browser/src/node/node_thread.h" #include "exo_browser/src/node/api/exo_browser_wrap.h" using namespace content; namespace exo_browser { const int ExoBrowser::kDefaultWindowWidth = 800; const int ExoBrowser::kDefaultWindowHeight = 600; std::vector<ExoBrowser*> ExoBrowser::s_instances; ExoBrowser::ExoBrowser( ExoBrowserWrap* wrapper) : window_(NULL), #if defined(OS_WIN) && !defined(USE_AURA) default_edit_wnd_proc_(0), #endif wrapper_(wrapper), is_killed_(false) { s_instances.push_back(this); } ExoBrowser::~ExoBrowser() { LOG(INFO) << "ExoBrowser Destructor"; PlatformCleanUp(); for (size_t i = 0; i < s_instances.size(); ++i) { if (s_instances[i] == this) { s_instances.erase(s_instances.begin() + i); break; } } } void ExoBrowser::Initialize() { PlatformInitialize( gfx::Size(kDefaultWindowWidth, kDefaultWindowHeight)); } ExoBrowser* ExoBrowser::CreateNew( ExoBrowserWrap* wrapper, const gfx::Size& size) { ExoBrowser* browser = new ExoBrowser(wrapper); browser->PlatformCreateWindow(size.width(), size.height()); return browser; } void ExoBrowser::KillAll() { std::vector<ExoBrowser*> open(s_instances); for (size_t i = 0; i < open.size(); ++i) { open[i]->Kill(); } base::MessageLoop::current()->RunUntilIdle(); } ExoFrame* ExoBrowser::FrameForWebContents( const WebContents* web_contents) { std::map<std::string, ExoFrame*>::iterator p_it; for(p_it = pages_.begin(); p_it != pages_.end(); ++p_it) { if((p_it->second)->web_contents_ == web_contents) { return (p_it->second); } } std::map<CONTROL_TYPE, ExoFrame*>::iterator c_it; for(c_it = controls_.begin(); c_it != controls_.end(); ++c_it) { if((c_it->second)->web_contents_ == web_contents) { return (c_it->second); } } return NULL; } void ExoBrowser::SetControl( CONTROL_TYPE type, ExoFrame* frame) { std::map<CONTROL_TYPE, ExoFrame*>::iterator it = controls_.find(type); if(it == controls_.end()) { UnsetControl(type); } controls_[type] = frame; frame->SetType(ExoFrame::CONTROL_FRAME); frame->SetParent(this); PlatformSetControl(type, frame); } void ExoBrowser::UnsetControl( CONTROL_TYPE type) { std::map<CONTROL_TYPE, ExoFrame*>::iterator it = controls_.find(type); if(it != controls_.end()) { PlatformUnsetControl(it->first, it->second); (it->second)->SetType(ExoFrame::NOTYPE_FRAME); (it->second)->SetParent(NULL); controls_.erase(it); } /* Otherwise, nothing to do */ } void ExoBrowser::SetControlDimension( CONTROL_TYPE type, int size) { PlatformSetControlDimension(type, size); } void ExoBrowser::AddPage( ExoFrame* frame) { frame->SetType(ExoFrame::PAGE_FRAME); frame->SetParent(this); pages_[frame->name()] = frame; PlatformAddPage(frame); } void ExoBrowser::RemovePage( const std::string& name) { std::map<std::string, ExoFrame*>::iterator it = pages_.find(name); if(it != pages_.end()) { PlatformRemovePage(it->second); (it->second)->SetType(ExoFrame::NOTYPE_FRAME); (it->second)->SetParent(NULL); pages_.erase(it); } /* Otherwise, nothing to do */ } void ExoBrowser::ShowPage( const std::string& name) { std::map<std::string, ExoFrame*>::iterator it = pages_.find(name); if(it != pages_.end()) { PlatformShowPage(it->second); } /* Otherwise, nothing to do */ } void ExoBrowser::RemoveFrame( const std::string& name) { std::map<std::string, ExoFrame*>::iterator p_it; for(p_it = pages_.begin(); p_it != pages_.end(); ++p_it) { if((p_it->second)->name() == name) { return RemovePage((p_it->second)->name()); } } std::map<CONTROL_TYPE, ExoFrame*>::iterator c_it; for(c_it = controls_.begin(); c_it != controls_.end(); ++c_it) { if((c_it->second)->name() == name) { return UnsetControl(c_it->first); } } } void ExoBrowser::Kill() { is_killed_ = true; while(pages_.begin() != pages_.end()) { RemovePage((pages_.begin()->second)->name()); } while(controls_.begin() != controls_.end()) { UnsetControl(controls_.begin()->first); } PlatformKill(); NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchKill, wrapper_)); } WebContents* ExoBrowser::OpenURLFromTab( WebContents* source, const OpenURLParams& params) { ExoFrame* frame = FrameForWebContents(source); if(frame) { /* Relevant header files: */ /* ui/base/window_open_disposition.h */ /* content/public/common/page_transition_types_list.h */ /* TODO(spolu): Use params.transition */ /* TODO(spolu): Use params.referrer */ NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchOpenURL, wrapper_, params.url.spec(), params.disposition, frame->name())); } else { /* This is used when a newly created WebContents is not yet assigned to */ /* its fimal ExoFrame/ExoBrowser but needs a delegate to navigate to its */ /* targeted delegate. See ExoBrowser::WebContentsCreated. */ source->GetController().LoadURL( params.url, params.referrer, params.transition, std::string()); } return NULL; } void ExoBrowser::RequestToLockMouse( WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { /* Default implementation */ web_contents->GotResponseToLockMouseRequest(true); } void ExoBrowser::CloseContents( WebContents* source) { ExoFrame* frame = FrameForWebContents(source); if(frame) { NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchFrameClose, wrapper_, frame->name())); } } bool ExoBrowser::PreHandleKeyboardEvent( WebContents* source, const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { ExoFrame* frame = FrameForWebContents(source); if(frame) { NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchFrameKeyboard, wrapper_, frame->name(), event)); } return false; } void ExoBrowser::HandleKeyboardEvent( WebContents* source, const NativeWebKeyboardEvent& event) { //LOG(INFO) << "HandleKeyboardEvent " << event.windowsKeyCode; } void ExoBrowser::NavigationStateChanged( const WebContents* source, unsigned changed_flags) { ExoFrame* frame = FrameForWebContents(source); if(!frame) return; std::vector<ExoBrowserWrap::NavigationEntry> entries; for(int i = 0; i < frame->web_contents()->GetController().GetEntryCount(); i++) { content::NavigationEntry *entry = frame->web_contents_->GetController().GetEntryAtIndex(i); ExoBrowserWrap::NavigationEntry e; e.url_ = entry->GetURL().spec(); e.virtual_url_ = entry->GetVirtualURL().spec(); e.title_ = UTF16ToUTF8(entry->GetTitle()); /* TODO(spolu): entry->GetFavicon().url.spec() */ e.visible_ = (entry == frame->web_contents()->GetController().GetVisibleEntry()); e.timestamp_ = entry->GetTimestamp().ToInternalValue() / 1000; e.id_ = entry->GetUniqueID(); switch(entry->GetPageType()) { case content::PAGE_TYPE_ERROR: e.type_ = "error"; break; case content::PAGE_TYPE_INTERSTITIAL: e.type_ = "interstitial"; break; default: e.type_ = "normal"; break; } switch(entry->GetSSL().security_style) { case content::SECURITY_STYLE_UNAUTHENTICATED: e.ssl_security_type_ = "unauthenticated"; break; case content::SECURITY_STYLE_AUTHENTICATION_BROKEN: e.ssl_security_type_ = "broken"; break; case content::SECURITY_STYLE_AUTHENTICATED: e.ssl_security_type_ = "authenticated"; break; default: e.ssl_security_type_ = "unknown"; } e.ssl_cert_status_ = entry->GetSSL().cert_status; e.ssl_content_status_ = entry->GetSSL().content_status; entries.push_back(e); } bool can_go_back = frame->web_contents()->GetController().CanGoBack(); bool can_go_forward = frame->web_contents()->GetController().CanGoForward(); if(frame) { NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchNavigationState, wrapper_, frame->name(), entries, can_go_back, can_go_forward)); } } void ExoBrowser::WebContentsCreated( WebContents* source_contents, int64 source_frame_id, const string16& frame_name, const GURL& target_url, WebContents* new_contents) { LOG(INFO) << "WebContentsCreated: " << target_url << "\nframe_name: " << frame_name << "\nsource_frame_id: " << source_frame_id << "\nsource_frame_id: " << source_frame_id << "\nnew_contents: " << new_contents; /* TODO(spolu): Call into API if necessary */ /* We set this ExoBrowser as temporary WebContentsDelegate the */ /* OpenURLForTab method may need to be called for some WebContents, esp. */ /* when clicking on a link with `target="_blank"` and `rel="norerferrer"` */ /* This delegate will get overriden when the new ExoFrame is later */ /* asynchronously added to an ExoBrowser. */ new_contents->SetDelegate(this); } void ExoBrowser::AddNewContents( WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture, bool* was_blocked) { LOG(INFO) << "AddNewContents: " << (was_blocked ? *was_blocked : false) << "\nuser_gesture: " << user_gesture << "\ndisposition: " << disposition << "\nsource: " << source << "\nsource url: " << source->GetVisibleURL() << "\nnew_contents: " << new_contents << "\nnew_contents url: " << new_contents->GetVisibleURL() << "\nRenderProcessHost: " << new_contents->GetRenderProcessHost() << "\nRenderViewHost: " << new_contents->GetRenderViewHost() << "\nView: " << new_contents->GetView() << "\nWaiting Response: " << new_contents->IsWaitingForResponse() << "\nInterstitial: " << new_contents->GetInterstitialPage(); ExoFrame* src_frame = FrameForWebContents(source); DCHECK(src_frame != NULL); if(src_frame) { /* We generate a unique name for this new frame */ std::ostringstream oss; static int pop_cnt = 0; oss << src_frame->name() << "-" << (++pop_cnt); ExoFrame* new_frame = new ExoFrame(oss.str(), new_contents); NodeThread::Get()->PostTask( FROM_HERE, base::Bind(&ExoBrowserWrap::DispatchFrameCreated, wrapper_, src_frame->name(), disposition, initial_pos, new_frame)); } } JavaScriptDialogManager* ExoBrowser::GetJavaScriptDialogManager() { /* TODO(spolu): Eventually Move to API */ if (!dialog_manager_) dialog_manager_.reset(new ExoBrowserJavaScriptDialogManager()); return dialog_manager_.get(); } void ExoBrowser::ActivateContents( WebContents* contents) { LOG(INFO) << "Activate Content"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API */ } void ExoBrowser::DeactivateContents( WebContents* contents) { LOG(INFO) << "Dectivate Content"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API (blur) */ } void ExoBrowser::RendererUnresponsive( WebContents* source) { LOG(INFO) << "RendererUnresponsive"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API */ } void ExoBrowser::WorkerCrashed( WebContents* source) { LOG(INFO) << "WorkerCrashed"; /* TODO(spolu): find WebContents ExoFrame's name */ /* TODO(spolu): Call into API */ } } // namespace exo_browser <|endoftext|>
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include "command.h" #include "phase_encoding.h" #include "progressbar.h" #include "image.h" #include "algo/threaded_copy.h" #include "dwi/gradient.h" #include "dwi/tensor.h" using namespace MR; using namespace App; using value_type = float; #define DEFAULT_NITER 2 const char* encoding_description = "The tensor coefficients are stored in the output image as follows: \n" "volumes 0-5: D11, D22, D33, D12, D13, D23 ; \n\n" "If diffusion kurtosis is estimated using the -dkt option, these are stored as follows: \n" "volumes 0-2: W1111, W2222, W3333 ; \n" "volumes 3-8: W1112, W1113, W1222, W1333, W2223, W2333 ; \n" "volumes 9-11: W1122, W1133, W2233 ; \n" "volumes 12-14: W1123, W1223, W1233 ;"; void usage () { AUTHOR = "Ben Jeurissen (ben.jeurissen@uantwerpen.be)"; SYNOPSIS = "Diffusion (kurtosis) tensor estimation."; DESCRIPTION + "Estimate diffusion tensor (and optionally its kurtosis) by fitting to " "the log-signal using either ordinary least-squares (OLS) or weighted least-squares (WLS), " "followed by further re-weighted iterations using the previous signals predictions (IWLS)." "By default, the initial fit is performed using WLS, followed by 2 IWLS iterations." + encoding_description; ARGUMENTS + Argument ("dwi", "the input dwi image.").type_image_in () + Argument ("dt", "the output dt image.").type_image_out (); OPTIONS + Option ("ols", "perform initial fit using an ordinary least-squares (OLS) fit, " "instead of the default weighted least-squares (WLS) strategy.") + Option ("mask", "only perform computation within the specified binary brain mask image.") + Argument ("image").type_image_in() + Option ("b0", "the output b0 image.") + Argument ("image").type_image_out() + Option ("dkt", "the output dkt image.") + Argument ("image").type_image_out() + Option ("iter","number of iterative reweightings for IWLS algorithm (default: " + str(DEFAULT_NITER) + ". Set to zero to perform standard OLS or WLS.") + Argument ("integer").type_integer (0, 10) + Option ("predicted_signal", "the predicted dwi image.") + Argument ("image").type_image_out() + DWI::GradImportOptions(); REFERENCES + "References based on fitting algorithm used:" + "* OLS, WLS:\n" "Basser, P.J.; Mattiello, J.; LeBihan, D." "Estimation of the effective self-diffusion tensor from the NMR spin echo." "J Magn Reson B., 1994, 103, 247–254." + "* IWLS:\n" "Veraart, J.; Sijbers, J.; Sunaert, S.; Leemans, A. & Jeurissen, B. " // Internal "Weighted linear least squares estimation of diffusion MRI parameters: strengths, limitations, and pitfalls. " "NeuroImage, 2013, 81, 335-346"; } template <class MASKType, class B0Type, class DKTType, class PredictType> class Processor { MEMALIGN(Processor) public: Processor (const Eigen::MatrixXd& b, const bool ols, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) : mask_image (mask_image), b0_image (b0_image), dkt_image (dkt_image), predict_image (predict_image), dwi(b.rows()), p(b.cols()), w(Eigen::VectorXd::Ones (b.rows())), work(b.cols(),b.cols()), llt(work.rows()), b(b), ols (ols), maxit(iter) { } template <class DWIType, class DTType> void operator() (DWIType& dwi_image, DTType& dt_image) { if (mask_image) { assign_pos_of (dwi_image, 0, 3).to (*mask_image); if (!mask_image->value()) return; } for (auto l = Loop (3) (dwi_image); l; ++l) dwi[dwi_image.index(3)] = dwi_image.value(); double small_intensity = 1.0e-6 * dwi.maxCoeff(); for (int i = 0; i < dwi.rows(); i++) { if (dwi[i] < small_intensity) dwi[i] = small_intensity; w[i] = ( ols ? 1.0 : dwi[i] ); dwi[i] = std::log (dwi[i]); } for (int it = 0; it <= maxit; it++) { work.setZero(); work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose()*w.asDiagonal()); p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*w.asDiagonal()*w.asDiagonal()*dwi); if (maxit > 1) w = (b*p).array().exp(); } for (auto l = Loop(3)(dt_image); l; ++l) { dt_image.value() = p[dt_image.index(3)]; } if (b0_image) { assign_pos_of (dwi_image, 0, 3).to (*b0_image); b0_image->value() = exp(p[6]); } if (dkt_image) { assign_pos_of (dwi_image, 0, 3).to (*dkt_image); double adc_sq = (p[0]+p[1]+p[2])*(p[0]+p[1]+p[2])/9.0; for (auto l = Loop(3)(*dkt_image); l; ++l) { dkt_image->value() = p[dkt_image->index(3)+7]/adc_sq; } } if (predict_image) { assign_pos_of (dwi_image, 0, 3).to (*predict_image); dwi = (b*p).array().exp(); for (auto l = Loop(3)(*predict_image); l; ++l) { predict_image->value() = dwi[predict_image->index(3)]; } } } private: copy_ptr<MASKType> mask_image; copy_ptr<B0Type> b0_image; copy_ptr<DKTType> dkt_image; copy_ptr<PredictType> predict_image; Eigen::VectorXd dwi; Eigen::VectorXd p; Eigen::VectorXd w; Eigen::MatrixXd work; Eigen::LLT<Eigen::MatrixXd> llt; const Eigen::MatrixXd& b; const bool ols; const int maxit; }; template <class MASKType, class B0Type, class DKTType, class PredictType> inline Processor<MASKType, B0Type, DKTType, PredictType> processor (const Eigen::MatrixXd& b, const bool ols, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) { return { b, ols, iter, mask_image, b0_image, dkt_image, predict_image }; } void run () { auto dwi = Header::open (argument[0]).get_image<value_type>(); auto grad = DWI::get_valid_DW_scheme (dwi); Image<bool>* mask = nullptr; auto opt = get_options ("mask"); if (opt.size()) { mask = new Image<bool> (Image<bool>::open (opt[0][0])); check_dimensions (dwi, *mask, 0, 3); } bool ols = get_options ("ols").size(); // depending on whether first (initialisation) loop should be considered an iteration auto iter = get_option_value ("iter", DEFAULT_NITER); Header header (dwi); header.datatype() = DataType::Float32; header.ndim() = 4; DWI::stash_DW_scheme (header, grad); PhaseEncoding::clear_scheme (header); Image<value_type>* predict = nullptr; opt = get_options ("predicted_signal"); if (opt.size()) predict = new Image<value_type> (Image<value_type>::create (opt[0][0], header)); header.size(3) = 6; auto dt = Image<value_type>::create (argument[1], header); Image<value_type>* b0 = nullptr; opt = get_options ("b0"); if (opt.size()) { header.ndim() = 3; b0 = new Image<value_type> (Image<value_type>::create (opt[0][0], header)); } Image<value_type>* dkt = nullptr; opt = get_options ("dkt"); if (opt.size()) { header.ndim() = 4; header.size(3) = 15; dkt = new Image<value_type> (Image<value_type>::create (opt[0][0], header)); } Eigen::MatrixXd b = -DWI::grad2bmatrix<double> (grad, opt.size()>0); ThreadedLoop("computing tensors", dwi, 0, 3).run (processor (b, ols, iter, mask, b0, dkt, predict), dwi, dt); } <commit_msg>dwi2tensor: fix typo in help page<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include "command.h" #include "phase_encoding.h" #include "progressbar.h" #include "image.h" #include "algo/threaded_copy.h" #include "dwi/gradient.h" #include "dwi/tensor.h" using namespace MR; using namespace App; using value_type = float; #define DEFAULT_NITER 2 const char* encoding_description = "The tensor coefficients are stored in the output image as follows: \n" "volumes 0-5: D11, D22, D33, D12, D13, D23 ; \n\n" "If diffusion kurtosis is estimated using the -dkt option, these are stored as follows: \n" "volumes 0-2: W1111, W2222, W3333 ; \n" "volumes 3-8: W1112, W1113, W1222, W1333, W2223, W2333 ; \n" "volumes 9-11: W1122, W1133, W2233 ; \n" "volumes 12-14: W1123, W1223, W1233 ;"; void usage () { AUTHOR = "Ben Jeurissen (ben.jeurissen@uantwerpen.be)"; SYNOPSIS = "Diffusion (kurtosis) tensor estimation."; DESCRIPTION + "Estimate diffusion tensor (and optionally its kurtosis) by fitting to " "the log-signal using either ordinary least-squares (OLS) or weighted least-squares (WLS), " "followed by further re-weighted iterations using the previous signals predictions (IWLS)." "By default, the initial fit is performed using WLS, followed by 2 IWLS iterations." + encoding_description; ARGUMENTS + Argument ("dwi", "the input dwi image.").type_image_in () + Argument ("dt", "the output dt image.").type_image_out (); OPTIONS + Option ("ols", "perform initial fit using an ordinary least-squares (OLS) fit, " "instead of the default weighted least-squares (WLS) strategy.") + Option ("mask", "only perform computation within the specified binary brain mask image.") + Argument ("image").type_image_in() + Option ("b0", "the output b0 image.") + Argument ("image").type_image_out() + Option ("dkt", "the output dkt image.") + Argument ("image").type_image_out() + Option ("iter","number of iterative reweightings for IWLS algorithm (default: " + str(DEFAULT_NITER) + "). Set to zero to perform standard OLS or WLS.") + Argument ("integer").type_integer (0, 10) + Option ("predicted_signal", "the predicted dwi image.") + Argument ("image").type_image_out() + DWI::GradImportOptions(); REFERENCES + "References based on fitting algorithm used:" + "* OLS, WLS:\n" "Basser, P.J.; Mattiello, J.; LeBihan, D." "Estimation of the effective self-diffusion tensor from the NMR spin echo." "J Magn Reson B., 1994, 103, 247–254." + "* IWLS:\n" "Veraart, J.; Sijbers, J.; Sunaert, S.; Leemans, A. & Jeurissen, B. " // Internal "Weighted linear least squares estimation of diffusion MRI parameters: strengths, limitations, and pitfalls. " "NeuroImage, 2013, 81, 335-346"; } template <class MASKType, class B0Type, class DKTType, class PredictType> class Processor { MEMALIGN(Processor) public: Processor (const Eigen::MatrixXd& b, const bool ols, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) : mask_image (mask_image), b0_image (b0_image), dkt_image (dkt_image), predict_image (predict_image), dwi(b.rows()), p(b.cols()), w(Eigen::VectorXd::Ones (b.rows())), work(b.cols(),b.cols()), llt(work.rows()), b(b), ols (ols), maxit(iter) { } template <class DWIType, class DTType> void operator() (DWIType& dwi_image, DTType& dt_image) { if (mask_image) { assign_pos_of (dwi_image, 0, 3).to (*mask_image); if (!mask_image->value()) return; } for (auto l = Loop (3) (dwi_image); l; ++l) dwi[dwi_image.index(3)] = dwi_image.value(); double small_intensity = 1.0e-6 * dwi.maxCoeff(); for (int i = 0; i < dwi.rows(); i++) { if (dwi[i] < small_intensity) dwi[i] = small_intensity; w[i] = ( ols ? 1.0 : dwi[i] ); dwi[i] = std::log (dwi[i]); } for (int it = 0; it <= maxit; it++) { work.setZero(); work.selfadjointView<Eigen::Lower>().rankUpdate (b.transpose()*w.asDiagonal()); p = llt.compute (work.selfadjointView<Eigen::Lower>()).solve(b.transpose()*w.asDiagonal()*w.asDiagonal()*dwi); if (maxit > 1) w = (b*p).array().exp(); } for (auto l = Loop(3)(dt_image); l; ++l) { dt_image.value() = p[dt_image.index(3)]; } if (b0_image) { assign_pos_of (dwi_image, 0, 3).to (*b0_image); b0_image->value() = exp(p[6]); } if (dkt_image) { assign_pos_of (dwi_image, 0, 3).to (*dkt_image); double adc_sq = (p[0]+p[1]+p[2])*(p[0]+p[1]+p[2])/9.0; for (auto l = Loop(3)(*dkt_image); l; ++l) { dkt_image->value() = p[dkt_image->index(3)+7]/adc_sq; } } if (predict_image) { assign_pos_of (dwi_image, 0, 3).to (*predict_image); dwi = (b*p).array().exp(); for (auto l = Loop(3)(*predict_image); l; ++l) { predict_image->value() = dwi[predict_image->index(3)]; } } } private: copy_ptr<MASKType> mask_image; copy_ptr<B0Type> b0_image; copy_ptr<DKTType> dkt_image; copy_ptr<PredictType> predict_image; Eigen::VectorXd dwi; Eigen::VectorXd p; Eigen::VectorXd w; Eigen::MatrixXd work; Eigen::LLT<Eigen::MatrixXd> llt; const Eigen::MatrixXd& b; const bool ols; const int maxit; }; template <class MASKType, class B0Type, class DKTType, class PredictType> inline Processor<MASKType, B0Type, DKTType, PredictType> processor (const Eigen::MatrixXd& b, const bool ols, const int iter, MASKType* mask_image, B0Type* b0_image, DKTType* dkt_image, PredictType* predict_image) { return { b, ols, iter, mask_image, b0_image, dkt_image, predict_image }; } void run () { auto dwi = Header::open (argument[0]).get_image<value_type>(); auto grad = DWI::get_valid_DW_scheme (dwi); Image<bool>* mask = nullptr; auto opt = get_options ("mask"); if (opt.size()) { mask = new Image<bool> (Image<bool>::open (opt[0][0])); check_dimensions (dwi, *mask, 0, 3); } bool ols = get_options ("ols").size(); // depending on whether first (initialisation) loop should be considered an iteration auto iter = get_option_value ("iter", DEFAULT_NITER); Header header (dwi); header.datatype() = DataType::Float32; header.ndim() = 4; DWI::stash_DW_scheme (header, grad); PhaseEncoding::clear_scheme (header); Image<value_type>* predict = nullptr; opt = get_options ("predicted_signal"); if (opt.size()) predict = new Image<value_type> (Image<value_type>::create (opt[0][0], header)); header.size(3) = 6; auto dt = Image<value_type>::create (argument[1], header); Image<value_type>* b0 = nullptr; opt = get_options ("b0"); if (opt.size()) { header.ndim() = 3; b0 = new Image<value_type> (Image<value_type>::create (opt[0][0], header)); } Image<value_type>* dkt = nullptr; opt = get_options ("dkt"); if (opt.size()) { header.ndim() = 4; header.size(3) = 15; dkt = new Image<value_type> (Image<value_type>::create (opt[0][0], header)); } Eigen::MatrixXd b = -DWI::grad2bmatrix<double> (grad, opt.size()>0); ThreadedLoop("computing tensors", dwi, 0, 3).run (processor (b, ols, iter, mask, b0, dkt, predict), dwi, dt); } <|endoftext|>
<commit_before>#include "conversioninfo.h" #include "ditherer.h" #include <iostream> #include <vector> #include <algorithm> #include <stdexcept> namespace ReSampler { // sanitize() : function to allow more permissive parsing. // Removes hyphens after first non-hyphen character and converts to lowercase. // examples: // --flatTPDF => --flattpdf // --flat-tpdf => --flattpdf std::string sanitize(const std::string& str) { std::string r(str); auto s = static_cast<std::string::iterator::difference_type>(r.find_first_not_of('-')); // get position of first non-hyphen r.erase(std::remove(r.begin() + s, r.end(), '-'), r.end()); // remove all hyphens after the first non-hyphen std::transform(r.begin(), r.end(), r.begin(), ::tolower); // change to lower-case return r; } // The following functions are used for fetching commandline parameters: // get numeric parameter value: template<typename T> bool getCmdlineParam(char** begin, char** end, const std::string& option, T& parameter) { std::vector<std::string> args(begin, end); bool found = false; for (auto it = args.begin(); it != args.end(); it++) { if (sanitize(*it) == sanitize(option)) { found = true; auto next = std::next(it); if (next != args.end()) { try { parameter = static_cast<T>(std::stof(*next)); } catch (std::invalid_argument& e) { (void)e; } } break; } } return found; } // get string parameter value: bool getCmdlineParam(char** begin, char** end, const std::string& option, std::string& parameter) { std::vector<std::string> args(begin, end); bool found = false; for (auto it = args.begin(); it != args.end(); it++) { if (sanitize(*it) == sanitize(option)) { found = true; auto next = std::next(it); if (next != args.end()) parameter = *next; break; } } return found; } // get vector of string parameters bool getCmdlineParam(char** begin, char** end, const std::string& option, std::vector<std::string>& parameters) { std::vector<std::string> args(begin, end); bool found = false; for (auto it = args.begin(); it != args.end(); it++) { if (sanitize(*it) == sanitize(option)) { found = true; // read parameters until we hit a hyphen or the end of args for (auto next = std::next(it); next != args.end(); next++) { if ((*next).find("-") == std::string::npos) { parameters.push_back(*next); } } break; } } return found; } // switch only (no parameter value) bool getCmdlineParam(char** begin, char** end, const std::string& option) { bool found = false; std::vector<std::string> args(begin, end); for (auto &arg : args) { if (sanitize(arg) == sanitize(option)) { found = true; break; } } return found; } std::string ConversionInfo::toCmdLineArgs() { std::vector<std::string> args; std::string result; args.emplace_back("-i"); args.push_back(inputFilename); args.emplace_back("-o"); args.push_back(outputFilename); args.emplace_back("-r"); args.push_back(std::to_string(outputSampleRate)); if(bUseDoublePrecision) args.emplace_back("--doubleprecision"); if(bNormalize) { args.emplace_back("-n"); args.push_back(std::to_string(normalizeAmount)); } if(bMinPhase) args.emplace_back("--minphase"); if (lpfMode == custom) { args.emplace_back("--lpf-cutoff"); args.push_back(std::to_string(lpfCutoff)); args.emplace_back("--lpf-transition"); args.push_back(std::to_string(lpfTransitionWidth)); } if (maxStages == 1) { args.emplace_back("--maxStages"); args.push_back(std::to_string(maxStages)); } for(auto it = args.begin(); it != args.end(); it++) { result.append(*it); if(it != std::prev(args.end())) result.append(" "); } return result; } int getDefaultNoiseShape(int sampleRate) { if (sampleRate <= 44100) { return DitherProfileID::standard; } if (sampleRate <= 48000) { return DitherProfileID::standard; } return DitherProfileID::flat_f; } // fromCmdLineArgs() // Return value indicates whether caller should continue execution (ie true: continue, false: terminate) // Some commandline options (eg --version) should result in termination, but not error. // unacceptable parameters are indicated by setting bBadParams to true bool ConversionInfo::fromCmdLineArgs(int argc, char** argv) { // set defaults for EVERYTHING: inputFilename.clear(); outputFilename.clear(); inputSampleRate = 0; outputSampleRate = 0; gain = 1.0; limit = 1.0; bUseDoublePrecision = false; bNormalize = false; normalizeAmount = 1.0; outputFormat = 0; outBitFormat.clear(); bDither = false; ditherAmount = 1.0; ditherProfileID = DitherProfileID::standard; bAutoBlankingEnabled = false; bDelayTrim = true; bMinPhase = false; bSetFlacCompression = false; flacCompressionLevel = 5; bSetVorbisQuality = true; vorbisQuality = 3; disableClippingProtection = false; lpfMode = normal; lpfCutoff = 100.0 * (10.0 / 11.0); lpfTransitionWidth = 100.0 - lpfCutoff; bUseSeed = false; seed = 0; dsfInput = false; dffInput = false; bEnablePeakDetection = true; bMultiThreaded = false; bRf64 = false; bNoPeakChunk = false; bWriteMetaData = true; maxStages = 3; bSingleStage = false; bMultiStage = true; bShowStages = false; bTmpFile = true; bShowTempFile = false; overSamplingFactor = 1; progressUpdates = 10; bBadParams = false; appName.clear(); bRawInput = false; // get core parameters: getCmdlineParam(argv, argv + argc, "-i", inputFilename); getCmdlineParam(argv, argv + argc, "-o", outputFilename); getCmdlineParam(argv, argv + argc, "-r", outputSampleRate); getCmdlineParam(argv, argv + argc, "-b", outBitFormat); // get extended parameters getCmdlineParam(argv, argv + argc, "--gain", gain); bUseDoublePrecision = getCmdlineParam(argv, argv + argc, "--doubleprecision"); disableClippingProtection = getCmdlineParam(argv, argv + argc, "--noClippingProtection"); bNormalize = getCmdlineParam(argv, argv + argc, "-n", normalizeAmount); bDither = getCmdlineParam(argv, argv + argc, "--dither", ditherAmount); ditherProfileID = getDefaultNoiseShape(outputSampleRate); getCmdlineParam(argv, argv + argc, "--ns", ditherProfileID); ditherProfileID = getCmdlineParam(argv, argv + argc, "--flat-tpdf") ? DitherProfileID::flat : ditherProfileID; bAutoBlankingEnabled = getCmdlineParam(argv, argv + argc, "--autoblank"); bUseSeed = getCmdlineParam(argv, argv + argc, "--seed", seed); bDelayTrim = !getCmdlineParam(argv, argv + argc, "--noDelayTrim"); bMinPhase = getCmdlineParam(argv, argv + argc, "--minphase"); bSetFlacCompression = getCmdlineParam(argv, argv + argc, "--flacCompression", flacCompressionLevel); bSetVorbisQuality = getCmdlineParam(argv, argv + argc, "--vorbisQuality", vorbisQuality); bMultiThreaded = getCmdlineParam(argv, argv + argc, "--mt"); bRf64 = getCmdlineParam(argv, argv + argc, "--rf64"); bNoPeakChunk = getCmdlineParam(argv, argv + argc, "--noPeakChunk"); bWriteMetaData = !getCmdlineParam(argv, argv + argc, "--noMetadata"); getCmdlineParam(argv, argv + argc, "--maxStages", maxStages); bSingleStage = getCmdlineParam(argv, argv + argc, "--singleStage"); bMultiStage = getCmdlineParam(argv, argv + argc, "--multiStage"); integerWriteScalingStyle = getCmdlineParam(argv, argv + argc, "--pow2clip") ? IntegerWriteScalingStyle::Pow2Clip : IntegerWriteScalingStyle::Pow2Minus1; getCmdlineParam(argv, argv + argc, "--progress-updates", progressUpdates); #if defined (_WIN32) || defined (_WIN64) getCmdlineParam(argv, argv + argc, "--tempDir", tmpDir); #endif bTmpFile = !getCmdlineParam(argv, argv + argc, "--noTempFile"); bShowTempFile = getCmdlineParam(argv, argv + argc, "--showTempFile"); /* resolve conflicts between singleStage and multiStage, according to this table: IN OUT s m S M ==== === F F F T F T F T (no change) T F T F (no change) T T F T */ if (!bMultiStage && !bSingleStage) bMultiStage = true; else if (bMultiStage && bSingleStage) bSingleStage = false; bShowStages = getCmdlineParam(argv, argv + argc, "--showStages"); // LPFilter settings: if (getCmdlineParam(argv, argv + argc, "--relaxedLPF")) { lpfMode = relaxed; lpfCutoff = 100.0 * (21.0 / 22.0); // late cutoff lpfTransitionWidth = 2 * (100.0 - lpfCutoff); // wide transition (double-width) } if (getCmdlineParam(argv, argv + argc, "--steepLPF")) { lpfMode = steep; lpfCutoff = 100.0 * (21.0 / 22.0); // late cutoff lpfTransitionWidth = 100.0 - lpfCutoff; // steep transition } if (getCmdlineParam(argv, argv + argc, "--lpf-cutoff", lpfCutoff)) { // custom LPF cutoff frequency lpfMode = custom; if (!getCmdlineParam(argv, argv + argc, "--lpf-transition", lpfTransitionWidth)) { lpfTransitionWidth = 100 - lpfCutoff; // auto mode } } if (getCmdlineParam(argv, argv + argc, "--raw-input")) { std::vector<std::string> rawInputParams; if (getCmdlineParam(argv, argv + argc, "--raw-input", rawInputParams)) { if (rawInputParams.size() >= 2) { bRawInput = true; rawInputSampleRate = std::stoi(rawInputParams.at(0)); rawInputBitFormat = rawInputParams.at(1); if (rawInputParams.size() >= 3) { rawInputChannels = std::stoi(rawInputParams.at(2)); } else { rawInputChannels = 1; // default to mono if unspecified } } } } double qb = 0.0; quantize = getCmdlineParam(argv, argv + argc, "--quantize-bits", qb); quantizeBits = static_cast<int>(std::floor(qb)); // constraining functions: auto constrainDouble = [](double& val, double minVal, double maxVal) { val = std::max(minVal, std::min(val, maxVal)); }; auto constrainInt = [](int& val, int minVal, int maxVal) { val = std::max(minVal, std::min(val, maxVal)); }; // set constraints: constrainInt(flacCompressionLevel, 0, 8); constrainDouble(vorbisQuality, -1, 10); constrainInt(maxStages, 1, 10); constrainDouble(lpfCutoff, 1.0, 99.9); constrainDouble(lpfTransitionWidth, 0.1, 400.0); constrainInt(progressUpdates, 0, 100); if (bNormalize) { if (normalizeAmount <= 0.0) normalizeAmount = 1.0; if (normalizeAmount > 1.0) std::cout << "\nWarning: Normalization factor greater than 1.0 - THIS WILL CAUSE CLIPPING !!\n" << std::endl; limit = normalizeAmount; } if (bDither) { if (ditherAmount <= 0.0) ditherAmount = 1.0; } if (ditherProfileID < 0) ditherProfileID = 0; if (ditherProfileID >= DitherProfileID::end) ditherProfileID = getDefaultNoiseShape(outputSampleRate); // test for bad parameters: bBadParams = false; if (outputFilename.empty()) { if (inputFilename.empty()) { std::cout << "Error: Input filename not specified" << std::endl; bBadParams = true; } else { std::cout << "Output filename not specified" << std::endl; outputFilename = inputFilename; if (outputFilename.find('.') != std::string::npos) { auto dot = outputFilename.find_last_of('.'); outputFilename.insert(dot, "(converted)"); } else { outputFilename.append("(converted)"); } std::cout << "defaulting to: " << outputFilename << "\n" << std::endl; } } else if (outputFilename == inputFilename) { std::cout << "\nError: Input and Output filenames cannot be the same" << std::endl; bBadParams = true; } if (outputSampleRate == 0) { std::cout << "Error: Target sample rate not specified" << std::endl; bBadParams = true; } return !bBadParams; } } // namespace ReSampler <commit_msg>cleanup<commit_after>#include "conversioninfo.h" #include "ditherer.h" #include <iostream> #include <vector> #include <algorithm> #include <stdexcept> namespace ReSampler { // sanitize() : function to allow more permissive parsing. // Removes hyphens after first non-hyphen character and converts to lowercase. // examples: // --flatTPDF => --flattpdf // --flat-tpdf => --flattpdf std::string sanitize(const std::string& str) { std::string r(str); auto s = static_cast<std::string::iterator::difference_type>(r.find_first_not_of('-')); // get position of first non-hyphen r.erase(std::remove(r.begin() + s, r.end(), '-'), r.end()); // remove all hyphens after the first non-hyphen std::transform(r.begin(), r.end(), r.begin(), ::tolower); // change to lower-case return r; } // The following functions are used for fetching commandline parameters: // get numeric parameter value: template<typename T> bool getCmdlineParam(char** begin, char** end, const std::string& option, T& parameter) { std::vector<std::string> args(begin, end); bool found = false; for (auto it = args.begin(); it != args.end(); it++) { if (sanitize(*it) == sanitize(option)) { found = true; auto next = std::next(it); if (next != args.end()) { try { parameter = static_cast<T>(std::stof(*next)); } catch (std::invalid_argument& e) { (void)e; } } break; } } return found; } // get string parameter value: bool getCmdlineParam(char** begin, char** end, const std::string& option, std::string& parameter) { std::vector<std::string> args(begin, end); bool found = false; for (auto it = args.begin(); it != args.end(); it++) { if (sanitize(*it) == sanitize(option)) { found = true; auto next = std::next(it); if (next != args.end()) parameter = *next; break; } } return found; } // get vector of string parameters bool getCmdlineParam(char** begin, char** end, const std::string& option, std::vector<std::string>& parameters) { std::vector<std::string> args(begin, end); bool found = false; for (auto it = args.begin(); it != args.end(); it++) { if (sanitize(*it) == sanitize(option)) { found = true; // read parameters until we hit a hyphen or the end of args for (auto next = std::next(it); next != args.end(); next++) { if ((*next).find("-") == std::string::npos) { parameters.push_back(*next); } } break; } } return found; } // switch only (no parameter value) bool getCmdlineParam(char** begin, char** end, const std::string& option) { bool found = false; std::vector<std::string> args(begin, end); for (const auto &arg : args) { if (sanitize(arg) == sanitize(option)) { found = true; break; } } return found; } std::string ConversionInfo::toCmdLineArgs() { std::vector<std::string> args; std::string result; args.emplace_back("-i"); args.push_back(inputFilename); args.emplace_back("-o"); args.push_back(outputFilename); args.emplace_back("-r"); args.push_back(std::to_string(outputSampleRate)); if(bUseDoublePrecision) args.emplace_back("--doubleprecision"); if(bNormalize) { args.emplace_back("-n"); args.push_back(std::to_string(normalizeAmount)); } if(bMinPhase) args.emplace_back("--minphase"); if (lpfMode == custom) { args.emplace_back("--lpf-cutoff"); args.push_back(std::to_string(lpfCutoff)); args.emplace_back("--lpf-transition"); args.push_back(std::to_string(lpfTransitionWidth)); } if (maxStages == 1) { args.emplace_back("--maxStages"); args.push_back(std::to_string(maxStages)); } for(auto it = args.begin(); it != args.end(); it++) { result.append(*it); if(it != std::prev(args.end())) result.append(" "); } return result; } int getDefaultNoiseShape(int sampleRate) { if (sampleRate <= 44100) { return DitherProfileID::standard; } if (sampleRate <= 48000) { return DitherProfileID::standard; } return DitherProfileID::flat_f; } // fromCmdLineArgs() // Return value indicates whether caller should continue execution (ie true: continue, false: terminate) // Some commandline options (eg --version) should result in termination, but not error. // unacceptable parameters are indicated by setting bBadParams to true bool ConversionInfo::fromCmdLineArgs(int argc, char** argv) { // set defaults for EVERYTHING: inputFilename.clear(); outputFilename.clear(); inputSampleRate = 0; outputSampleRate = 0; gain = 1.0; limit = 1.0; bUseDoublePrecision = false; bNormalize = false; normalizeAmount = 1.0; outputFormat = 0; outBitFormat.clear(); bDither = false; ditherAmount = 1.0; ditherProfileID = DitherProfileID::standard; bAutoBlankingEnabled = false; bDelayTrim = true; bMinPhase = false; bSetFlacCompression = false; flacCompressionLevel = 5; bSetVorbisQuality = true; vorbisQuality = 3; disableClippingProtection = false; lpfMode = normal; lpfCutoff = 100.0 * (10.0 / 11.0); lpfTransitionWidth = 100.0 - lpfCutoff; bUseSeed = false; seed = 0; dsfInput = false; dffInput = false; bEnablePeakDetection = true; bMultiThreaded = false; bRf64 = false; bNoPeakChunk = false; bWriteMetaData = true; maxStages = 3; bSingleStage = false; bMultiStage = true; bShowStages = false; bTmpFile = true; bShowTempFile = false; overSamplingFactor = 1; progressUpdates = 10; bBadParams = false; appName.clear(); bRawInput = false; // get core parameters: getCmdlineParam(argv, argv + argc, "-i", inputFilename); getCmdlineParam(argv, argv + argc, "-o", outputFilename); getCmdlineParam(argv, argv + argc, "-r", outputSampleRate); getCmdlineParam(argv, argv + argc, "-b", outBitFormat); // get extended parameters getCmdlineParam(argv, argv + argc, "--gain", gain); bUseDoublePrecision = getCmdlineParam(argv, argv + argc, "--doubleprecision"); disableClippingProtection = getCmdlineParam(argv, argv + argc, "--noClippingProtection"); bNormalize = getCmdlineParam(argv, argv + argc, "-n", normalizeAmount); bDither = getCmdlineParam(argv, argv + argc, "--dither", ditherAmount); ditherProfileID = getDefaultNoiseShape(outputSampleRate); getCmdlineParam(argv, argv + argc, "--ns", ditherProfileID); ditherProfileID = getCmdlineParam(argv, argv + argc, "--flat-tpdf") ? DitherProfileID::flat : ditherProfileID; bAutoBlankingEnabled = getCmdlineParam(argv, argv + argc, "--autoblank"); bUseSeed = getCmdlineParam(argv, argv + argc, "--seed", seed); bDelayTrim = !getCmdlineParam(argv, argv + argc, "--noDelayTrim"); bMinPhase = getCmdlineParam(argv, argv + argc, "--minphase"); bSetFlacCompression = getCmdlineParam(argv, argv + argc, "--flacCompression", flacCompressionLevel); bSetVorbisQuality = getCmdlineParam(argv, argv + argc, "--vorbisQuality", vorbisQuality); bMultiThreaded = getCmdlineParam(argv, argv + argc, "--mt"); bRf64 = getCmdlineParam(argv, argv + argc, "--rf64"); bNoPeakChunk = getCmdlineParam(argv, argv + argc, "--noPeakChunk"); bWriteMetaData = !getCmdlineParam(argv, argv + argc, "--noMetadata"); getCmdlineParam(argv, argv + argc, "--maxStages", maxStages); bSingleStage = getCmdlineParam(argv, argv + argc, "--singleStage"); bMultiStage = getCmdlineParam(argv, argv + argc, "--multiStage"); integerWriteScalingStyle = getCmdlineParam(argv, argv + argc, "--pow2clip") ? IntegerWriteScalingStyle::Pow2Clip : IntegerWriteScalingStyle::Pow2Minus1; getCmdlineParam(argv, argv + argc, "--progress-updates", progressUpdates); #if defined (_WIN32) || defined (_WIN64) getCmdlineParam(argv, argv + argc, "--tempDir", tmpDir); #endif bTmpFile = !getCmdlineParam(argv, argv + argc, "--noTempFile"); bShowTempFile = getCmdlineParam(argv, argv + argc, "--showTempFile"); /* resolve conflicts between singleStage and multiStage, according to this table: IN OUT s m S M ==== === F F F T F T F T (no change) T F T F (no change) T T F T */ if (!bMultiStage && !bSingleStage) bMultiStage = true; else if (bMultiStage && bSingleStage) bSingleStage = false; bShowStages = getCmdlineParam(argv, argv + argc, "--showStages"); // LPFilter settings: if (getCmdlineParam(argv, argv + argc, "--relaxedLPF")) { lpfMode = relaxed; lpfCutoff = 100.0 * (21.0 / 22.0); // late cutoff lpfTransitionWidth = 2 * (100.0 - lpfCutoff); // wide transition (double-width) } if (getCmdlineParam(argv, argv + argc, "--steepLPF")) { lpfMode = steep; lpfCutoff = 100.0 * (21.0 / 22.0); // late cutoff lpfTransitionWidth = 100.0 - lpfCutoff; // steep transition } if (getCmdlineParam(argv, argv + argc, "--lpf-cutoff", lpfCutoff)) { // custom LPF cutoff frequency lpfMode = custom; if (!getCmdlineParam(argv, argv + argc, "--lpf-transition", lpfTransitionWidth)) { lpfTransitionWidth = 100 - lpfCutoff; // auto mode } } if (getCmdlineParam(argv, argv + argc, "--raw-input")) { std::vector<std::string> rawInputParams; if (getCmdlineParam(argv, argv + argc, "--raw-input", rawInputParams)) { if (rawInputParams.size() >= 2) { bRawInput = true; rawInputSampleRate = std::stoi(rawInputParams.at(0)); rawInputBitFormat = rawInputParams.at(1); if (rawInputParams.size() >= 3) { rawInputChannels = std::stoi(rawInputParams.at(2)); } else { rawInputChannels = 1; // default to mono if unspecified } } } } double qb = 0.0; quantize = getCmdlineParam(argv, argv + argc, "--quantize-bits", qb); quantizeBits = static_cast<int>(std::floor(qb)); // constraining functions: auto constrainDouble = [](double& val, double minVal, double maxVal) { val = std::max(minVal, std::min(val, maxVal)); }; auto constrainInt = [](int& val, int minVal, int maxVal) { val = std::max(minVal, std::min(val, maxVal)); }; // set constraints: constrainInt(flacCompressionLevel, 0, 8); constrainDouble(vorbisQuality, -1, 10); constrainInt(maxStages, 1, 10); constrainDouble(lpfCutoff, 1.0, 99.9); constrainDouble(lpfTransitionWidth, 0.1, 400.0); constrainInt(progressUpdates, 0, 100); if (bNormalize) { if (normalizeAmount <= 0.0) normalizeAmount = 1.0; if (normalizeAmount > 1.0) std::cout << "\nWarning: Normalization factor greater than 1.0 - THIS WILL CAUSE CLIPPING !!\n" << std::endl; limit = normalizeAmount; } if (bDither) { if (ditherAmount <= 0.0) ditherAmount = 1.0; } if (ditherProfileID < 0) ditherProfileID = 0; if (ditherProfileID >= DitherProfileID::end) ditherProfileID = getDefaultNoiseShape(outputSampleRate); // test for bad parameters: bBadParams = false; if (outputFilename.empty()) { if (inputFilename.empty()) { std::cout << "Error: Input filename not specified" << std::endl; bBadParams = true; } else { std::cout << "Output filename not specified" << std::endl; outputFilename = inputFilename; if (outputFilename.find('.') != std::string::npos) { auto dot = outputFilename.find_last_of('.'); outputFilename.insert(dot, "(converted)"); } else { outputFilename.append("(converted)"); } std::cout << "defaulting to: " << outputFilename << "\n" << std::endl; } } else if (outputFilename == inputFilename) { std::cout << "\nError: Input and Output filenames cannot be the same" << std::endl; bBadParams = true; } if (outputSampleRate == 0) { std::cout << "Error: Target sample rate not specified" << std::endl; bBadParams = true; } return !bBadParams; } } // namespace ReSampler <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Flacon - audio File Encoder * https://github.com/flacon/flacon * * Copyright: 2012-2013 * Alexander Sokoloff <sokoloff.a@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "gain.h" #include "profiles.h" #include "settings.h" #include <QProcess> #include <QDir> #include <QTextStream> #include <QDebug> #include <QLoggingCategory> namespace { Q_LOGGING_CATEGORY(LOG, "Converter") } using namespace Conv; /************************************************ * ************************************************/ Gain::Gain(const Profile &profile, QObject *parent) : Worker(parent), mProfile(profile) { } /************************************************ * ************************************************/ void Gain::addTrack(const ConvTrack &track, const QString &file) { mJobs << Job { track, file }; } /************************************************ * ************************************************/ void Gain::run() { QStringList files; for (const Job &job : qAsConst(mJobs)) { emit trackProgress(job.track, TrackState::CalcGain, 0); files << QDir::toNativeSeparators(job.file); } QStringList args = programArgs(files, mProfile.gainType()); QString prog = args.takeFirst(); qCDebug(LOG) << "Start gain:" << debugProgramArgs(prog, args); QProcess process; process.start(prog, args); process.waitForFinished(-1); if (process.exitCode() != 0) { qWarning() << "Gain command failed: " << debugProgramArgs(prog, args); QString msg = tr("Gain error:\n") + QString::fromLocal8Bit(process.readAllStandardError()); emit error(mJobs.first().track, msg); } for (const Job &job : qAsConst(mJobs)) { emit trackProgress(job.track, TrackState::WriteGain, 100); emit trackReady(job.track, job.file); } } QString Gain::programPath() const { return Settings::i()->programName(programName()); } <commit_msg>Fix: Incorrect behavior when replay gain error occurred<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Flacon - audio File Encoder * https://github.com/flacon/flacon * * Copyright: 2012-2013 * Alexander Sokoloff <sokoloff.a@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "gain.h" #include "profiles.h" #include "settings.h" #include <QProcess> #include <QDir> #include <QTextStream> #include <QDebug> #include <QLoggingCategory> namespace { Q_LOGGING_CATEGORY(LOG, "Converter") } using namespace Conv; /************************************************ * ************************************************/ Gain::Gain(const Profile &profile, QObject *parent) : Worker(parent), mProfile(profile) { } /************************************************ * ************************************************/ void Gain::addTrack(const ConvTrack &track, const QString &file) { mJobs << Job { track, file }; } /************************************************ * ************************************************/ void Gain::run() { QStringList files; for (const Job &job : qAsConst(mJobs)) { emit trackProgress(job.track, TrackState::CalcGain, 0); files << QDir::toNativeSeparators(job.file); } QStringList args = programArgs(files, mProfile.gainType()); QString prog = args.takeFirst(); qCDebug(LOG) << "Start gain:" << debugProgramArgs(prog, args); QProcess process; process.start(prog, args); process.waitForFinished(-1); if (process.exitCode() != 0) { qWarning() << "Gain command failed: " << debugProgramArgs(prog, args); QString msg = tr("Gain error:\n") + QString::fromLocal8Bit(process.readAllStandardError()); emit error(mJobs.first().track, msg); return; } for (const Job &job : qAsConst(mJobs)) { emit trackProgress(job.track, TrackState::WriteGain, 100); emit trackReady(job.track, job.file); } } QString Gain::programPath() const { return Settings::i()->programName(programName()); } <|endoftext|>
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * Copyright (C) 2014 the FFLAS-FFPACK group * * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr> * * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ /** @file fflas/fflas_ftrsm_mp.inl * @brief triangular system with matrix right hand side over multiprecision domain (either over Z or over Z/pZ) */ #ifndef __FFPACK_ftrsm_mp_INL #define __FFPACK_ftrsm_mp_INL #include <math.h> #include <givaro/modular-integer.h> #include <givaro/givinteger.h> #include "fflas-ffpack/fflas/fflas_bounds.inl" #include "fflas-ffpack/fflas/fflas_level3.inl" #include "fflas-ffpack/field/rns-integer-mod.h" #include "fflas-ffpack/field/rns-integer.h" namespace FFLAS { void ftrsm (const Givaro::Modular<Givaro::Integer> & F, const FFLAS_SIDE Side, const FFLAS_UPLO Uplo, const FFLAS_TRANSPOSE TransA, const FFLAS_DIAG Diag, const size_t M, const size_t N, const Givaro::Integer alpha, const Givaro::Integer * A, const size_t lda, Givaro::Integer * B, const size_t ldb){ #ifdef BENCH_PERF_TRSM_MP double t_init=0, t_trsm=0, t_mod=0, t_rec=0; FFLAS::Timer chrono; chrono.start(); #endif Givaro::Integer p; F.cardinality(p); size_t logp=p.bitsize(); size_t K; if (Side == FFLAS::FflasLeft) K=M; else K=N; if (K==0) return; // compute bit size of feasible prime size_t _k=std::max(K,logp/20), lk=0; while ( _k ) {_k>>=1; ++lk;} size_t prime_bitsize= (53-lk)>>1; // construct rns basis Givaro::Integer maxC= (p-1)*(p-1)*(p-1)*K; size_t n_pr =maxC.bitsize()/prime_bitsize; maxC=(p-1)*(p-1)*K*(1<<prime_bitsize)*n_pr; FFPACK::rns_double RNS(maxC, prime_bitsize, true); FFPACK::RNSIntegerMod<FFPACK::rns_double> Zp(p, RNS); #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_init+=chrono.usertime(); chrono.clear();chrono.start(); #endif // compute A and B in RNS FFPACK::rns_double::Element_ptr Ap,Bp; Ap = FFLAS::fflas_new(Zp,K,K); Bp = FFLAS::fflas_new(Zp,M,N); if (Side == FFLAS::FflasLeft){ finit_rns(Zp,K,K,(logp/16)+(logp%16?1:0),A,lda,Ap); finit_rns(Zp,M,N,(logp/16)+(logp%16?1:0),B,ldb,Bp); } else { finit_trans_rns(Zp,K,K,(logp/16)+(logp%16?1:0),A,lda,Ap); finit_trans_rns(Zp,M,N,(logp/16)+(logp%16?1:0),B,ldb,Bp); } #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_mod+=chrono.usertime(); chrono.clear();chrono.start(); #endif // call ftrsm in rns //ftrsm(Zp, Side, Uplo, TransA, Diag, M, N, Zp.one, Ap, K, Bp, N); if (Side == FFLAS::FflasLeft) ftrsm(Zp, Side, Uplo, TransA, Diag, M, N, Zp.one, Ap, K, Bp, N); else { if (Uplo == FFLAS::FflasUpper) ftrsm(Zp, FFLAS::FflasLeft, FFLAS::FflasLower, TransA, Diag, N, M, Zp.one, Ap, K, Bp, M); else ftrsm(Zp, FFLAS::FflasLeft, FFLAS::FflasUpper, TransA, Diag, N, M, Zp.one, Ap, K, Bp, M); } #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_trsm+=chrono.usertime(); chrono.clear();chrono.start(); #endif // reconstruct the result if (Side == FFLAS::FflasLeft) fconvert_rns(Zp,M,N,F.zero,B,ldb,Bp); else{ fconvert_trans_rns(Zp,M,N,F.zero,B,ldb,Bp); } // reduce it modulo p freduce (F, M, N, B, ldb); // scale it with alpha if (!F.isOne(alpha)) fscalin(F,M,N,alpha,B,ldb); #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_rec+=chrono.usertime(); cout<<"FTRSM RNS PERF:"<<endl; cout<<" *** init : "<<t_init<<endl; cout<<" *** rns mod : "<<t_mod<<endl; cout<<" *** rns trsm : "<<t_trsm<<" ( igemm="<<Zp.t_igemm<<" scal="<<Zp.t_scal<<" modp="<<Zp.t_modp<<endl;; cout<<" *** rns rec : "<<t_rec<<endl; #endif FFLAS::fflas_delete(Ap); FFLAS::fflas_delete(Bp); } inline void cblas_imptrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const FFPACK::rns_double_elt alpha, FFPACK::rns_double_elt_cstptr A, const int lda, FFPACK::rns_double_elt_ptr B, const int ldb) {} #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Protected { template<> inline size_t TRSMBound (const FFPACK::RNSIntegerMod<FFPACK::rns_double> &F) { return 1; } template <> inline size_t DotProdBoundClassic (const FFPACK::RNSIntegerMod<FFPACK::rns_double>& F, const FFPACK::rns_double_elt& beta) { Givaro::Integer p,b,M; F.cardinality(p); p--; F.convert(b,beta); M=F.rns()._M; size_t kmax= (M-b*p)/(p*p); return std::max(1UL,kmax); //return kmax; } #ifndef __FTRSM_MP_FAST #define __FFLAS_MULTIPRECISION #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #endif // #ifdef __FTRSM_MP_FAST } // end of namespace protected #endif // #ifndef DOXYGEN_SHOULD_SKIP_THIS } // END OF NAMESPACE FFLAS #endif <commit_msg>revert cast<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * Copyright (C) 2014 the FFLAS-FFPACK group * * Written by Pascal Giorgi <pascal.giorgi@lirmm.fr> * * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ /** @file fflas/fflas_ftrsm_mp.inl * @brief triangular system with matrix right hand side over multiprecision domain (either over Z or over Z/pZ) */ #ifndef __FFPACK_ftrsm_mp_INL #define __FFPACK_ftrsm_mp_INL #include <math.h> #include <givaro/modular-integer.h> #include <givaro/givinteger.h> #include "fflas-ffpack/fflas/fflas_bounds.inl" #include "fflas-ffpack/fflas/fflas_level3.inl" #include "fflas-ffpack/field/rns-integer-mod.h" #include "fflas-ffpack/field/rns-integer.h" namespace FFLAS { void ftrsm (const Givaro::Modular<Givaro::Integer> & F, const FFLAS_SIDE Side, const FFLAS_UPLO Uplo, const FFLAS_TRANSPOSE TransA, const FFLAS_DIAG Diag, const size_t M, const size_t N, const Givaro::Integer alpha, const Givaro::Integer * A, const size_t lda, Givaro::Integer * B, const size_t ldb){ #ifdef BENCH_PERF_TRSM_MP double t_init=0, t_trsm=0, t_mod=0, t_rec=0; FFLAS::Timer chrono; chrono.start(); #endif Givaro::Integer p; F.cardinality(p); size_t logp=p.bitsize(); size_t K; if (Side == FFLAS::FflasLeft) K=M; else K=N; if (K==0) return; // compute bit size of feasible prime size_t _k=std::max(K,logp/20), lk=0; while ( _k ) {_k>>=1; ++lk;} size_t prime_bitsize= (53-lk)>>1; // construct rns basis Givaro::Integer maxC= (p-1)*(p-1)*(p-1)*K; size_t n_pr =maxC.bitsize()/prime_bitsize; maxC=(p-1)*(p-1)*K*(1<<prime_bitsize)*n_pr; FFPACK::rns_double RNS(maxC, prime_bitsize, true); FFPACK::RNSIntegerMod<FFPACK::rns_double> Zp(p, RNS); #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_init+=chrono.usertime(); chrono.clear();chrono.start(); #endif // compute A and B in RNS FFPACK::rns_double::Element_ptr Ap,Bp; Ap = FFLAS::fflas_new(Zp,K,K); Bp = FFLAS::fflas_new(Zp,M,N); if (Side == FFLAS::FflasLeft){ finit_rns(Zp,K,K,(logp/16)+(logp%16?1:0),A,lda,Ap); finit_rns(Zp,M,N,(logp/16)+(logp%16?1:0),B,ldb,Bp); } else { finit_trans_rns(Zp,K,K,(logp/16)+(logp%16?1:0),A,lda,Ap); finit_trans_rns(Zp,M,N,(logp/16)+(logp%16?1:0),B,ldb,Bp); } #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_mod+=chrono.usertime(); chrono.clear();chrono.start(); #endif // call ftrsm in rns //ftrsm(Zp, Side, Uplo, TransA, Diag, M, N, Zp.one, Ap, K, Bp, N); if (Side == FFLAS::FflasLeft) ftrsm(Zp, Side, Uplo, TransA, Diag, M, N, Zp.one, Ap, K, Bp, N); else { if (Uplo == FFLAS::FflasUpper) ftrsm(Zp, FFLAS::FflasLeft, FFLAS::FflasLower, TransA, Diag, N, M, Zp.one, Ap, K, Bp, M); else ftrsm(Zp, FFLAS::FflasLeft, FFLAS::FflasUpper, TransA, Diag, N, M, Zp.one, Ap, K, Bp, M); } #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_trsm+=chrono.usertime(); chrono.clear();chrono.start(); #endif // reconstruct the result if (Side == FFLAS::FflasLeft) fconvert_rns(Zp,M,N,F.zero,B,ldb,Bp); else{ fconvert_trans_rns(Zp,M,N,F.zero,B,ldb,Bp); } // reduce it modulo p freduce (F, M, N, B, ldb); // scale it with alpha if (!F.isOne(alpha)) fscalin(F,M,N,alpha,B,ldb); #ifdef BENCH_PERF_TRSM_MP chrono.stop(); t_rec+=chrono.usertime(); cout<<"FTRSM RNS PERF:"<<endl; cout<<" *** init : "<<t_init<<endl; cout<<" *** rns mod : "<<t_mod<<endl; cout<<" *** rns trsm : "<<t_trsm<<" ( igemm="<<Zp.t_igemm<<" scal="<<Zp.t_scal<<" modp="<<Zp.t_modp<<endl;; cout<<" *** rns rec : "<<t_rec<<endl; #endif FFLAS::fflas_delete(Ap); FFLAS::fflas_delete(Bp); } inline void cblas_imptrsm(const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, const int M, const int N, const FFPACK::rns_double_elt alpha, FFPACK::rns_double_elt_cstptr A, const int lda, FFPACK::rns_double_elt_ptr B, const int ldb) {} #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Protected { template<> inline size_t TRSMBound (const FFPACK::RNSIntegerMod<FFPACK::rns_double> &F) { return 1; } template <> inline size_t DotProdBoundClassic (const FFPACK::RNSIntegerMod<FFPACK::rns_double>& F, const FFPACK::rns_double_elt& beta) { Givaro::Integer p,b,M; F.cardinality(p); p--; F.convert(b,beta); M=F.rns()._M; size_t kmax= (M-b*p)/(p*p); return std::max((size_t)1,kmax); //return kmax; } #ifndef __FTRSM_MP_FAST #define __FFLAS_MULTIPRECISION #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__LEFT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__LEFT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__UP #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__UP #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__NOTRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__NOTRANSPOSE #undef __FFLAS__UNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__NONUNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__NONUNIT #define __FFLAS__RIGHT #define __FFLAS__LOW #define __FFLAS__TRANSPOSE #define __FFLAS__UNIT #include "fflas_ftrsm_src.inl" #undef __FFLAS__RIGHT #undef __FFLAS__LOW #undef __FFLAS__TRANSPOSE #undef __FFLAS__UNIT #endif // #ifdef __FTRSM_MP_FAST } // end of namespace protected #endif // #ifndef DOXYGEN_SHOULD_SKIP_THIS } // END OF NAMESPACE FFLAS #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ResourceAllocator.h" #include "private/backend/DriverApi.h" #include "details/Texture.h" #include <utils/Log.h> using namespace utils; namespace filament { using namespace backend; using namespace details; namespace fg { // ------------------------------------------------------------------------------------------------ template<typename K, typename V, typename H> UTILS_NOINLINE typename ResourceAllocator::AssociativeContainer<K, V, H>::iterator ResourceAllocator::AssociativeContainer<K, V, H>::erase(iterator it) { return mContainer.erase(it); } template<typename K, typename V, typename H> typename ResourceAllocator::AssociativeContainer<K, V, H>::const_iterator ResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) const { return const_cast<AssociativeContainer*>(this)->find(key); } template<typename K, typename V, typename H> UTILS_NOINLINE typename ResourceAllocator::AssociativeContainer<K, V, H>::iterator ResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) { return std::find_if(mContainer.begin(), mContainer.end(), [&key](auto const& v) { return v.first == key; }); } template<typename K, typename V, typename H> template<typename... ARGS> UTILS_NOINLINE void ResourceAllocator::AssociativeContainer<K, V, H>::emplace(ARGS&& ... args) { mContainer.emplace_back(std::forward<ARGS>(args)...); } // ------------------------------------------------------------------------------------------------ size_t ResourceAllocator::TextureKey::getSize() const noexcept { size_t pixelCount = width * height * depth; size_t size = pixelCount * FTexture::getFormatSize(format); if (levels > 1) { // if we have mip-maps we assume the full pyramid size += size / 3; } size_t s = std::max(uint8_t(1), samples); if (s > 1) { // if we have MSAA, we assume 8 bit extra per pixel size += pixelCount; } return size; } ResourceAllocator::ResourceAllocator(DriverApi& driverApi) noexcept : mBackend(driverApi) { } ResourceAllocator::~ResourceAllocator() noexcept { assert(!mTextureCache.size()); assert(!mInUseTextures.size()); } void ResourceAllocator::terminate() noexcept { assert(!mInUseTextures.size()); auto& textureCache = mTextureCache; for (auto it = textureCache.begin(); it != textureCache.end();) { mBackend.destroyTexture(it->second.handle); it = textureCache.erase(it); } } RenderTargetHandle ResourceAllocator::createRenderTarget(const char* name, TargetBufferFlags targetBufferFlags, uint32_t width, uint32_t height, uint8_t samples, TargetBufferInfo color, TargetBufferInfo depth, TargetBufferInfo stencil) noexcept { return mBackend.createRenderTarget(targetBufferFlags, width, height, samples ? samples : 1u, color, depth, stencil); } void ResourceAllocator::destroyRenderTarget(RenderTargetHandle h) noexcept { return mBackend.destroyRenderTarget(h); } backend::TextureHandle ResourceAllocator::createTexture(const char* name, backend::SamplerType target, uint8_t levels, backend::TextureFormat format, uint8_t samples, uint32_t width, uint32_t height, uint32_t depth, backend::TextureUsage usage) noexcept { if (!(usage & TextureUsage::SAMPLEABLE)) { // If this texture is not going to be sampled, we can round its size up // this helps prevent many reallocations for small size changes. // We round to 16 pixels, which works for 720p btw. width = (width + 15u) & ~15u; height = (height + 15u) & ~15u; } // do we have a suitable texture in the cache? TextureHandle handle; if (mEnabled) { auto& textureCache = mTextureCache; const TextureKey key{ name, target, levels, format, samples, width, height, depth, usage }; auto it = textureCache.find(key); if (UTILS_LIKELY(it != textureCache.end())) { // we do, move the entry to the in-use list, and remove from the cache handle = it->second.handle; mCacheSize -= it->second.size; textureCache.erase(it); } else { // we don't, allocate a new texture and populate the in-use list handle = mBackend.createTexture( target, levels, format, samples, width, height, depth, usage); } mInUseTextures.emplace(handle, key); } else { handle = mBackend.createTexture( target, levels, format, samples, width, height, depth, usage); } return handle; } void ResourceAllocator::destroyTexture(TextureHandle h) noexcept { if (mEnabled) { // find the texture in the in-use list (it must be there!) auto it = mInUseTextures.find(h); assert(it != mInUseTextures.end()); // move it to the cache const TextureKey key = it->second; uint32_t size = key.getSize(); mTextureCache.emplace(key, TextureCachePayload{ h, mAge, size }); mCacheSize += size; // remove it from the in-use list mInUseTextures.erase(it); } else { mBackend.destroyTexture(h); } } void ResourceAllocator::gc() noexcept { // this is called regularly -- usually once per frame of each Renderer // increase our age const size_t age = mAge++; // Purging strategy: // + remove entries that are older than a certain age // - remove only one entry per gc(), unless we're at capacity auto& textureCache = mTextureCache; for (auto it = textureCache.begin(); it != textureCache.end();) { const size_t ageDiff = age - it->second.age; if (ageDiff >= CACHE_MAX_AGE) { mBackend.destroyTexture(it->second.handle); mCacheSize -= it->second.size; //slog.d << "purging " << it->second.handle.getId() << io::endl; it = textureCache.erase(it); if (mCacheSize < CACHE_CAPACITY) { // if we're not at capacity, only purge a single entry per gc, trying to // avoid a burst of work. break; } } else { ++it; } } //if (mAge % 60 == 0) dump(); // TODO: maybe purge LRU entries if we have more than a certain number // TODO: maybe purge LRU entries if the size of the cache is too large } UTILS_NOINLINE void ResourceAllocator::dump() const noexcept { slog.d << "# entries=" << mTextureCache.size() << ", sz=" << mCacheSize / float(1u << 20u) << " MiB" << io::endl; for (auto const & it : mTextureCache) { auto w = it.first.width; auto h = it.first.height; auto f = FTexture::getFormatSize(it.first.format); slog.d << it.first.name << ": w=" << w << ", h=" << h << ", f=" << f << ", sz=" << it.second.size / float(1u << 20u) << io::endl; } } } // namespace fg } // namespace filament <commit_msg>Disable rounding FBO sizes on WebGL.<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ResourceAllocator.h" #include "private/backend/DriverApi.h" #include "details/Texture.h" #include <utils/Log.h> using namespace utils; namespace filament { using namespace backend; using namespace details; namespace fg { // ------------------------------------------------------------------------------------------------ template<typename K, typename V, typename H> UTILS_NOINLINE typename ResourceAllocator::AssociativeContainer<K, V, H>::iterator ResourceAllocator::AssociativeContainer<K, V, H>::erase(iterator it) { return mContainer.erase(it); } template<typename K, typename V, typename H> typename ResourceAllocator::AssociativeContainer<K, V, H>::const_iterator ResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) const { return const_cast<AssociativeContainer*>(this)->find(key); } template<typename K, typename V, typename H> UTILS_NOINLINE typename ResourceAllocator::AssociativeContainer<K, V, H>::iterator ResourceAllocator::AssociativeContainer<K, V, H>::find(key_type const& key) { return std::find_if(mContainer.begin(), mContainer.end(), [&key](auto const& v) { return v.first == key; }); } template<typename K, typename V, typename H> template<typename... ARGS> UTILS_NOINLINE void ResourceAllocator::AssociativeContainer<K, V, H>::emplace(ARGS&& ... args) { mContainer.emplace_back(std::forward<ARGS>(args)...); } // ------------------------------------------------------------------------------------------------ size_t ResourceAllocator::TextureKey::getSize() const noexcept { size_t pixelCount = width * height * depth; size_t size = pixelCount * FTexture::getFormatSize(format); if (levels > 1) { // if we have mip-maps we assume the full pyramid size += size / 3; } size_t s = std::max(uint8_t(1), samples); if (s > 1) { // if we have MSAA, we assume 8 bit extra per pixel size += pixelCount; } return size; } ResourceAllocator::ResourceAllocator(DriverApi& driverApi) noexcept : mBackend(driverApi) { } ResourceAllocator::~ResourceAllocator() noexcept { assert(!mTextureCache.size()); assert(!mInUseTextures.size()); } void ResourceAllocator::terminate() noexcept { assert(!mInUseTextures.size()); auto& textureCache = mTextureCache; for (auto it = textureCache.begin(); it != textureCache.end();) { mBackend.destroyTexture(it->second.handle); it = textureCache.erase(it); } } RenderTargetHandle ResourceAllocator::createRenderTarget(const char* name, TargetBufferFlags targetBufferFlags, uint32_t width, uint32_t height, uint8_t samples, TargetBufferInfo color, TargetBufferInfo depth, TargetBufferInfo stencil) noexcept { return mBackend.createRenderTarget(targetBufferFlags, width, height, samples ? samples : 1u, color, depth, stencil); } void ResourceAllocator::destroyRenderTarget(RenderTargetHandle h) noexcept { return mBackend.destroyRenderTarget(h); } backend::TextureHandle ResourceAllocator::createTexture(const char* name, backend::SamplerType target, uint8_t levels, backend::TextureFormat format, uint8_t samples, uint32_t width, uint32_t height, uint32_t depth, backend::TextureUsage usage) noexcept { // Some WebGL implementations complain about an incomplete framebuffer when the attachment sizes // are heterogeneous. This merits further investigation. #if defined(__EMSCRIPTEN__) if (!(usage & TextureUsage::SAMPLEABLE)) { // If this texture is not going to be sampled, we can round its size up // this helps prevent many reallocations for small size changes. // We round to 16 pixels, which works for 720p btw. width = (width + 15u) & ~15u; height = (height + 15u) & ~15u; } #endif // do we have a suitable texture in the cache? TextureHandle handle; if (mEnabled) { auto& textureCache = mTextureCache; const TextureKey key{ name, target, levels, format, samples, width, height, depth, usage }; auto it = textureCache.find(key); if (UTILS_LIKELY(it != textureCache.end())) { // we do, move the entry to the in-use list, and remove from the cache handle = it->second.handle; mCacheSize -= it->second.size; textureCache.erase(it); } else { // we don't, allocate a new texture and populate the in-use list handle = mBackend.createTexture( target, levels, format, samples, width, height, depth, usage); } mInUseTextures.emplace(handle, key); } else { handle = mBackend.createTexture( target, levels, format, samples, width, height, depth, usage); } return handle; } void ResourceAllocator::destroyTexture(TextureHandle h) noexcept { if (mEnabled) { // find the texture in the in-use list (it must be there!) auto it = mInUseTextures.find(h); assert(it != mInUseTextures.end()); // move it to the cache const TextureKey key = it->second; uint32_t size = key.getSize(); mTextureCache.emplace(key, TextureCachePayload{ h, mAge, size }); mCacheSize += size; // remove it from the in-use list mInUseTextures.erase(it); } else { mBackend.destroyTexture(h); } } void ResourceAllocator::gc() noexcept { // this is called regularly -- usually once per frame of each Renderer // increase our age const size_t age = mAge++; // Purging strategy: // + remove entries that are older than a certain age // - remove only one entry per gc(), unless we're at capacity auto& textureCache = mTextureCache; for (auto it = textureCache.begin(); it != textureCache.end();) { const size_t ageDiff = age - it->second.age; if (ageDiff >= CACHE_MAX_AGE) { mBackend.destroyTexture(it->second.handle); mCacheSize -= it->second.size; //slog.d << "purging " << it->second.handle.getId() << io::endl; it = textureCache.erase(it); if (mCacheSize < CACHE_CAPACITY) { // if we're not at capacity, only purge a single entry per gc, trying to // avoid a burst of work. break; } } else { ++it; } } //if (mAge % 60 == 0) dump(); // TODO: maybe purge LRU entries if we have more than a certain number // TODO: maybe purge LRU entries if the size of the cache is too large } UTILS_NOINLINE void ResourceAllocator::dump() const noexcept { slog.d << "# entries=" << mTextureCache.size() << ", sz=" << mCacheSize / float(1u << 20u) << " MiB" << io::endl; for (auto const & it : mTextureCache) { auto w = it.first.width; auto h = it.first.height; auto f = FTexture::getFormatSize(it.first.format); slog.d << it.first.name << ": w=" << w << ", h=" << h << ", f=" << f << ", sz=" << it.second.size / float(1u << 20u) << io::endl; } } } // namespace fg } // namespace filament <|endoftext|>
<commit_before>/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "JNIHelp" #include "JNIHelp.h" #include <android/log.h> #include "log_compat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /** * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.) */ template<typename T> class scoped_local_ref { public: scoped_local_ref(C_JNIEnv* env, T localRef = NULL) : mEnv(env), mLocalRef(localRef) { } ~scoped_local_ref() { reset(); } void reset(T localRef = NULL) { if (mLocalRef != NULL) { (*mEnv)->DeleteLocalRef(reinterpret_cast<JNIEnv*>(mEnv), mLocalRef); mLocalRef = localRef; } } T get() const { return mLocalRef; } private: C_JNIEnv* mEnv; T mLocalRef; // Disallow copy and assignment. scoped_local_ref(const scoped_local_ref&); void operator=(const scoped_local_ref&); }; static jclass findClass(C_JNIEnv* env, const char* className) { JNIEnv* e = reinterpret_cast<JNIEnv*>(env); return (*env)->FindClass(e, className); } extern "C" int jniRegisterNativeMethods(C_JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) { JNIEnv* e = reinterpret_cast<JNIEnv*>(env); ALOGV("Registering %s's %d native methods...", className, numMethods); scoped_local_ref<jclass> c(env, findClass(env, className)); if (c.get() == NULL) { char* msg; asprintf(&msg, "Native registration unable to find class '%s'; aborting...", className); e->FatalError(msg); } if ((*env)->RegisterNatives(e, c.get(), gMethods, numMethods) < 0) { char* msg; asprintf(&msg, "RegisterNatives failed for '%s'; aborting...", className); e->FatalError(msg); } return 0; } extern "C" int jniThrowException(C_JNIEnv* c_env, const char* className, const char* msg) { JNIEnv* env = reinterpret_cast<JNIEnv*>(c_env); jclass exceptionClass = env->FindClass(className); if (exceptionClass == NULL) { ALOGD("Unable to find exception class %s", className); /* ClassNotFoundException now pending */ return -1; } if (env->ThrowNew(exceptionClass, msg) != JNI_OK) { ALOGD("Failed throwing '%s' '%s'", className, msg); /* an exception, most likely OOM, will now be pending */ return -1; } env->DeleteLocalRef(exceptionClass); return 0; } int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args) { char msgBuf[512]; vsnprintf(msgBuf, sizeof(msgBuf), fmt, args); return jniThrowException(env, className, msgBuf); } int jniThrowNullPointerException(C_JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/NullPointerException", msg); } int jniThrowRuntimeException(C_JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/RuntimeException", msg); } int jniThrowIOException(C_JNIEnv* env, int errnum) { char buffer[80]; const char* message = jniStrError(errnum, buffer, sizeof(buffer)); return jniThrowException(env, "java/io/IOException", message); } const char* jniStrError(int errnum, char* buf, size_t buflen) { #if __GLIBC__ // Note: glibc has a nonstandard strerror_r that returns char* rather than POSIX's int. // char *strerror_r(int errnum, char *buf, size_t n); return strerror_r(errnum, buf, buflen); #else int rc = strerror_r(errnum, buf, buflen); if (rc != 0) { // (POSIX only guarantees a value other than 0. The safest // way to implement this function is to use C++ and overload on the // type of strerror_r to accurately distinguish GNU from POSIX.) snprintf(buf, buflen, "errno %d", errnum); } return buf; #endif } int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor) { JNIEnv* e = reinterpret_cast<JNIEnv*>(env); scoped_local_ref<jclass> localClass(env, e->FindClass("java/io/FileDescriptor")); static jfieldID fid = e->GetFieldID(localClass.get(), "descriptor", "I"); if (fileDescriptor != NULL) { return (*env)->GetIntField(e, fileDescriptor, fid); } else { return -1; } } <commit_msg>Make sure we get the right strerror_r. am: d649eeefe7<commit_after>/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "JNIHelp" // We want the XSI-compliant strerror_r (it's more portable across NDK versions, // and the only one available until android-23), not the GNU one. We haven't // actually defined _GNU_SOURCE ourselves, but the compiler adds it // automatically when building C++. // // Including this header out of the normal order to make sure we import it the // right way. #undef _GNU_SOURCE #include <string.h> // OTOH, we need to have _GNU_SOURCE defined to pick up asprintf from stdio.h. #define _GNU_SOURCE #include <stdio.h> #include "JNIHelp.h" #include <android/log.h> #include "log_compat.h" #include <stdlib.h> #include <assert.h> /** * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.) */ template<typename T> class scoped_local_ref { public: scoped_local_ref(C_JNIEnv* env, T localRef = NULL) : mEnv(env), mLocalRef(localRef) { } ~scoped_local_ref() { reset(); } void reset(T localRef = NULL) { if (mLocalRef != NULL) { (*mEnv)->DeleteLocalRef(reinterpret_cast<JNIEnv*>(mEnv), mLocalRef); mLocalRef = localRef; } } T get() const { return mLocalRef; } private: C_JNIEnv* mEnv; T mLocalRef; // Disallow copy and assignment. scoped_local_ref(const scoped_local_ref&); void operator=(const scoped_local_ref&); }; static jclass findClass(C_JNIEnv* env, const char* className) { JNIEnv* e = reinterpret_cast<JNIEnv*>(env); return (*env)->FindClass(e, className); } extern "C" int jniRegisterNativeMethods(C_JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) { JNIEnv* e = reinterpret_cast<JNIEnv*>(env); ALOGV("Registering %s's %d native methods...", className, numMethods); scoped_local_ref<jclass> c(env, findClass(env, className)); if (c.get() == NULL) { char* msg; asprintf(&msg, "Native registration unable to find class '%s'; aborting...", className); e->FatalError(msg); } if ((*env)->RegisterNatives(e, c.get(), gMethods, numMethods) < 0) { char* msg; asprintf(&msg, "RegisterNatives failed for '%s'; aborting...", className); e->FatalError(msg); } return 0; } extern "C" int jniThrowException(C_JNIEnv* c_env, const char* className, const char* msg) { JNIEnv* env = reinterpret_cast<JNIEnv*>(c_env); jclass exceptionClass = env->FindClass(className); if (exceptionClass == NULL) { ALOGD("Unable to find exception class %s", className); /* ClassNotFoundException now pending */ return -1; } if (env->ThrowNew(exceptionClass, msg) != JNI_OK) { ALOGD("Failed throwing '%s' '%s'", className, msg); /* an exception, most likely OOM, will now be pending */ return -1; } env->DeleteLocalRef(exceptionClass); return 0; } int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args) { char msgBuf[512]; vsnprintf(msgBuf, sizeof(msgBuf), fmt, args); return jniThrowException(env, className, msgBuf); } int jniThrowNullPointerException(C_JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/NullPointerException", msg); } int jniThrowRuntimeException(C_JNIEnv* env, const char* msg) { return jniThrowException(env, "java/lang/RuntimeException", msg); } int jniThrowIOException(C_JNIEnv* env, int errnum) { char buffer[80]; const char* message = jniStrError(errnum, buffer, sizeof(buffer)); return jniThrowException(env, "java/io/IOException", message); } const char* jniStrError(int errnum, char* buf, size_t buflen) { #if __GLIBC__ // Note: glibc has a nonstandard strerror_r that returns char* rather than POSIX's int. // char *strerror_r(int errnum, char *buf, size_t n); return strerror_r(errnum, buf, buflen); #else int rc = strerror_r(errnum, buf, buflen); if (rc != 0) { // (POSIX only guarantees a value other than 0. The safest // way to implement this function is to use C++ and overload on the // type of strerror_r to accurately distinguish GNU from POSIX.) snprintf(buf, buflen, "errno %d", errnum); } return buf; #endif } int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor) { JNIEnv* e = reinterpret_cast<JNIEnv*>(env); scoped_local_ref<jclass> localClass(env, e->FindClass("java/io/FileDescriptor")); static jfieldID fid = e->GetFieldID(localClass.get(), "descriptor", "I"); if (fileDescriptor != NULL) { return (*env)->GetIntField(e, fileDescriptor, fid); } else { return -1; } } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // // ESP32 GPIO ( 40 physical GPIO pads) // // GPIO6-11 used for PSI flash // // GPIO34-39 Only input mode // #include <targetPAL.h> #include "win_dev_gpio_native.h" #include "nf_rt_events_native.h" #include "Esp32_DeviceMapping.h" /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinDriveMode (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum GpioPinDriveMode { GpioPinDriveMode_Input = 0, GpioPinDriveMode_InputPullDown, GpioPinDriveMode_InputPullUp, GpioPinDriveMode_Output, GpioPinDriveMode_OutputOpenDrain, GpioPinDriveMode_OutputOpenDrainPullUp, GpioPinDriveMode_OutputOpenSource, GpioPinDriveMode_OutputOpenSourcePullDown }; /////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinValue (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////// enum GpioPinValue { GpioPinValue_Low = 0, GpioPinValue_High, }; /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// static const char* TAG = "GpioPin"; static bool Gpio_Initialised = false; // this array keeps track of the Gpio pins that are assigned to each channel CLR_RT_HeapBlock* channelPinMapping[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; void Initialize_gpio() { esp_err_t ret = gpio_install_isr_service( 0); if ( ret != ESP_OK ) { ESP_LOGE( TAG, "Install isr service"); } } void Gpio_Interupt_ISR(void * args) { uint32_t pinNumber = (uint32_t)args; NATIVE_INTERRUPT_START CLR_RT_HeapBlock* pThis = channelPinMapping[pinNumber]; if ( pThis == NULL ) { NATIVE_INTERRUPT_END return; } // check if object has been disposed if( pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { // object has been disposed, leave now NATIVE_INTERRUPT_END return; } // flag to determine if there are any callbacks registered in managed code bool callbacksRegistered = (pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___callbacks ].Dereference() != NULL); if ( callbacksRegistered ) { // if handle registed then post a managed event with the current pin reading PostManagedEvent( EVENT_GPIO, 0, pinNumber, gpio_get_level((gpio_num_t)pinNumber) ); } NATIVE_INTERRUPT_END } void Add_Gpio_Interrupt(gpio_num_t pinNumber) { if ( !Gpio_Initialised ) { Initialize_gpio(); Gpio_Initialised = true; } esp_err_t ret = gpio_isr_handler_add( pinNumber, Gpio_Interupt_ISR, (void *)pinNumber); if ( ret != ESP_OK ) { ESP_LOGE( TAG, "Add interrupt to pin"); } } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::Read___WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } gpio_num_t pinNumber = (gpio_num_t)pThis[ FIELD___pinNumber ].NumericByRefConst().s4; stack.SetResult_I4( gpio_get_level(pinNumber) ); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::Toggle___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[ FIELD___driveMode ].NumericByRefConst().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if ((driveMode == GpioPinDriveMode_Output) || (driveMode == GpioPinDriveMode_OutputOpenDrain) || (driveMode == GpioPinDriveMode_OutputOpenDrainPullUp) || (driveMode == GpioPinDriveMode_OutputOpenSource) || (driveMode == GpioPinDriveMode_OutputOpenSourcePullDown)) { // ESP32 GPIO API doesn't offer a 'toggle', so need to rely on the last output value field and toggle that one GpioPinValue state = (GpioPinValue)pThis[ FIELD___lastOutputValue ].NumericByRef().s4; // ...handle the toggle... GpioPinValue newState = GpioPinValue_Low; if(state == GpioPinValue_Low) { newState = GpioPinValue_High; } // ...write back to the GPIO... gpio_set_level((gpio_num_t)pinNumber, newState); // ... and finally store it pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = newState; } } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::DisposeNative___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // set pin to input to save power // clear interrupts // releases the pin int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; if ( channelPinMapping[pinNumber] != NULL ) { // Remove from interrupts gpio_isr_handler_remove((gpio_num_t)pinNumber); // clear this channel in channel pin mapping channelPinMapping[pinNumber] = NULL; } } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeIsDriveModeSupported___BOOLEAN__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4; bool driveModeSupported = false; // check if the requested drive mode is support by ChibiOS config if ((driveMode == GpioPinDriveMode_Input) || (driveMode == GpioPinDriveMode_InputPullDown) || (driveMode == GpioPinDriveMode_InputPullUp) || (driveMode == GpioPinDriveMode_Output) || (driveMode == GpioPinDriveMode_OutputOpenDrain)) { driveModeSupported = true; } // Return value to the managed application stack.SetResult_Boolean( driveModeSupported ) ; } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDriveMode___VOID__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } signed int pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; signed int driveMode = stack.Arg1().NumericByRef().s4; // Valid PinNumber if ( ! GPIO_IS_VALID_GPIO(pinNumber) ) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // Check Pin is output capable if ( driveMode >= 3 && !GPIO_IS_VALID_OUTPUT_GPIO(pinNumber) ) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } gpio_mode_t mode = GPIO_MODE_DISABLE; gpio_pullup_t pull_up_en = GPIO_PULLUP_DISABLE; gpio_pulldown_t pull_down_en = GPIO_PULLDOWN_DISABLE; gpio_int_type_t intr_type = GPIO_INTR_ANYEDGE; switch (driveMode) { case GpioPinDriveMode_Input : mode = GPIO_MODE_INPUT; break; case GpioPinDriveMode_InputPullDown : mode = GPIO_MODE_INPUT; pull_down_en = GPIO_PULLDOWN_ENABLE; break; case GpioPinDriveMode_InputPullUp : pull_up_en = GPIO_PULLUP_ENABLE; break; case GpioPinDriveMode_Output : mode = GPIO_MODE_OUTPUT; break; case GpioPinDriveMode_OutputOpenDrain : driveMode = GPIO_MODE_OUTPUT_OD; break; case GpioPinDriveMode_OutputOpenDrainPullUp : mode = GPIO_MODE_OUTPUT_OD; pull_up_en = GPIO_PULLUP_ENABLE; break; case GpioPinDriveMode_OutputOpenSource: mode = GPIO_MODE_OUTPUT_OD; break; case GpioPinDriveMode_OutputOpenSourcePullDown: mode = GPIO_MODE_OUTPUT_OD; pull_down_en = GPIO_PULLDOWN_ENABLE; break; } gpio_config_t GPIOConfig; GPIOConfig.pin_bit_mask = (1ULL << pinNumber); GPIOConfig.mode = mode; GPIOConfig.pull_up_en = pull_up_en; GPIOConfig.pull_down_en = pull_down_en; GPIOConfig.intr_type = intr_type; gpio_config( &GPIOConfig ); // Enable interrupts for all pins Add_Gpio_Interrupt( (gpio_num_t)pinNumber ); // save pin reference channelPinMapping[pinNumber] = pThis; // protect this from GC so that the callback is where it's supposed to CLR_RT_ProtectFromGC gc( *pThis ); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeInit___BOOLEAN__I4( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); int16_t pinNumber = stack.Arg1().NumericByRef().s4; // TODO is probably a good idea keep track of the used pins, so we can check that here // TODO is probably a good idea to check if this pin exists if ( !GPIO_IS_VALID_GPIO((gpio_num_t)pinNumber) ) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // default to low pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = GpioPinValue_Low; // Return value to the managed application stack.SetResult_Boolean(true ); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDebounceTimeout___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); // nothing to do here as the debounce timeout is grabbed from the managed object when required NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::WriteNative___VOID__WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[ FIELD___driveMode ].NumericByRefConst().s4; GpioPinValue state = (GpioPinValue)stack.Arg1().NumericByRef().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if ((driveMode == GpioPinDriveMode_Output) || (driveMode == GpioPinDriveMode_OutputOpenDrain) || (driveMode == GpioPinDriveMode_OutputOpenDrainPullUp) || (driveMode == GpioPinDriveMode_OutputOpenSource) || (driveMode == GpioPinDriveMode_OutputOpenSourcePullDown)) { gpio_set_level( (gpio_num_t)pinNumber, state); // store the output value in the field pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = state; } else { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } // get pin number and take the port and pad references from that one int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; // get alternate function argument int32_t alternateFunction = stack.Arg1().NumericByRef().s4; Esp32_SetMappedDevicePins( (uint8_t)pinNumber, alternateFunction ); } NANOCLR_NOCLEANUP(); } <commit_msg>Improvement in EPS32 GpioPin toogle (#704)<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // // ESP32 GPIO ( 40 physical GPIO pads) // // GPIO6-11 used for PSI flash // // GPIO34-39 Only input mode // #include <targetPAL.h> #include "win_dev_gpio_native.h" #include "nf_rt_events_native.h" #include "Esp32_DeviceMapping.h" /////////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinDriveMode (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////////// enum GpioPinDriveMode { GpioPinDriveMode_Input = 0, GpioPinDriveMode_InputPullDown, GpioPinDriveMode_InputPullUp, GpioPinDriveMode_Output, GpioPinDriveMode_OutputOpenDrain, GpioPinDriveMode_OutputOpenDrainPullUp, GpioPinDriveMode_OutputOpenSource, GpioPinDriveMode_OutputOpenSourcePullDown }; /////////////////////////////////////////////////////////////////////////////////// // !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinValue (in managed code) !!! // /////////////////////////////////////////////////////////////////////////////////// enum GpioPinValue { GpioPinValue_Low = 0, GpioPinValue_High, }; /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// static const char* TAG = "GpioPin"; static bool Gpio_Initialised = false; // this array keeps track of the Gpio pins that are assigned to each channel CLR_RT_HeapBlock* channelPinMapping[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; void Initialize_gpio() { esp_err_t ret = gpio_install_isr_service( 0); if ( ret != ESP_OK ) { ESP_LOGE( TAG, "Install isr service"); } } void Gpio_Interupt_ISR(void * args) { uint32_t pinNumber = (uint32_t)args; NATIVE_INTERRUPT_START CLR_RT_HeapBlock* pThis = channelPinMapping[pinNumber]; if ( pThis == NULL ) { NATIVE_INTERRUPT_END return; } // check if object has been disposed if( pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { // object has been disposed, leave now NATIVE_INTERRUPT_END return; } // flag to determine if there are any callbacks registered in managed code bool callbacksRegistered = (pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___callbacks ].Dereference() != NULL); if ( callbacksRegistered ) { // if handle registed then post a managed event with the current pin reading PostManagedEvent( EVENT_GPIO, 0, pinNumber, gpio_get_level((gpio_num_t)pinNumber) ); } NATIVE_INTERRUPT_END } void Add_Gpio_Interrupt(gpio_num_t pinNumber) { if ( !Gpio_Initialised ) { Initialize_gpio(); Gpio_Initialised = true; } esp_err_t ret = gpio_isr_handler_add( pinNumber, Gpio_Interupt_ISR, (void *)pinNumber); if ( ret != ESP_OK ) { ESP_LOGE( TAG, "Add interrupt to pin"); } } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::Read___WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } gpio_num_t pinNumber = (gpio_num_t)pThis[ FIELD___pinNumber ].NumericByRefConst().s4; stack.SetResult_I4( gpio_get_level(pinNumber) ); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::Toggle___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[ FIELD___driveMode ].NumericByRefConst().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if ((driveMode == GpioPinDriveMode_Output) || (driveMode == GpioPinDriveMode_OutputOpenDrain) || (driveMode == GpioPinDriveMode_OutputOpenDrainPullUp) || (driveMode == GpioPinDriveMode_OutputOpenSource) || (driveMode == GpioPinDriveMode_OutputOpenSourcePullDown)) { // ESP32 GPIO API doesn't offer a 'toggle', so need to rely on the last output value field and toggle that one GpioPinValue newState = (GpioPinValue)(GpioPinValue_High ^ (GpioPinValue)pThis[ FIELD___lastOutputValue ].NumericByRef().s4); // ...write back to the GPIO... gpio_set_level((gpio_num_t)pinNumber, newState); // ... and finally store it pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = newState; } } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::DisposeNative___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // set pin to input to save power // clear interrupts // releases the pin int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; if ( channelPinMapping[pinNumber] != NULL ) { // Remove from interrupts gpio_isr_handler_remove((gpio_num_t)pinNumber); // clear this channel in channel pin mapping channelPinMapping[pinNumber] = NULL; } } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeIsDriveModeSupported___BOOLEAN__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4; bool driveModeSupported = false; // check if the requested drive mode is support by ChibiOS config if ((driveMode == GpioPinDriveMode_Input) || (driveMode == GpioPinDriveMode_InputPullDown) || (driveMode == GpioPinDriveMode_InputPullUp) || (driveMode == GpioPinDriveMode_Output) || (driveMode == GpioPinDriveMode_OutputOpenDrain)) { driveModeSupported = true; } // Return value to the managed application stack.SetResult_Boolean( driveModeSupported ) ; } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDriveMode___VOID__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } signed int pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; signed int driveMode = stack.Arg1().NumericByRef().s4; // Valid PinNumber if ( ! GPIO_IS_VALID_GPIO(pinNumber) ) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // Check Pin is output capable if ( driveMode >= 3 && !GPIO_IS_VALID_OUTPUT_GPIO(pinNumber) ) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } gpio_mode_t mode = GPIO_MODE_DISABLE; gpio_pullup_t pull_up_en = GPIO_PULLUP_DISABLE; gpio_pulldown_t pull_down_en = GPIO_PULLDOWN_DISABLE; gpio_int_type_t intr_type = GPIO_INTR_ANYEDGE; switch (driveMode) { case GpioPinDriveMode_Input : mode = GPIO_MODE_INPUT; break; case GpioPinDriveMode_InputPullDown : mode = GPIO_MODE_INPUT; pull_down_en = GPIO_PULLDOWN_ENABLE; break; case GpioPinDriveMode_InputPullUp : pull_up_en = GPIO_PULLUP_ENABLE; break; case GpioPinDriveMode_Output : mode = GPIO_MODE_OUTPUT; break; case GpioPinDriveMode_OutputOpenDrain : driveMode = GPIO_MODE_OUTPUT_OD; break; case GpioPinDriveMode_OutputOpenDrainPullUp : mode = GPIO_MODE_OUTPUT_OD; pull_up_en = GPIO_PULLUP_ENABLE; break; case GpioPinDriveMode_OutputOpenSource: mode = GPIO_MODE_OUTPUT_OD; break; case GpioPinDriveMode_OutputOpenSourcePullDown: mode = GPIO_MODE_OUTPUT_OD; pull_down_en = GPIO_PULLDOWN_ENABLE; break; } gpio_config_t GPIOConfig; GPIOConfig.pin_bit_mask = (1ULL << pinNumber); GPIOConfig.mode = mode; GPIOConfig.pull_up_en = pull_up_en; GPIOConfig.pull_down_en = pull_down_en; GPIOConfig.intr_type = intr_type; gpio_config( &GPIOConfig ); // Enable interrupts for all pins Add_Gpio_Interrupt( (gpio_num_t)pinNumber ); // save pin reference channelPinMapping[pinNumber] = pThis; // protect this from GC so that the callback is where it's supposed to CLR_RT_ProtectFromGC gc( *pThis ); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeInit___BOOLEAN__I4( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); int16_t pinNumber = stack.Arg1().NumericByRef().s4; // TODO is probably a good idea keep track of the used pins, so we can check that here // TODO is probably a good idea to check if this pin exists if ( !GPIO_IS_VALID_GPIO((gpio_num_t)pinNumber) ) { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } // default to low pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = GpioPinValue_Low; // Return value to the managed application stack.SetResult_Boolean(true ); } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDebounceTimeout___VOID( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); // nothing to do here as the debounce timeout is grabbed from the managed object when required NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::WriteNative___VOID__WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[ FIELD___driveMode ].NumericByRefConst().s4; GpioPinValue state = (GpioPinValue)stack.Arg1().NumericByRef().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if ((driveMode == GpioPinDriveMode_Output) || (driveMode == GpioPinDriveMode_OutputOpenDrain) || (driveMode == GpioPinDriveMode_OutputOpenDrainPullUp) || (driveMode == GpioPinDriveMode_OutputOpenSource) || (driveMode == GpioPinDriveMode_OutputOpenSourcePullDown)) { gpio_set_level( (gpio_num_t)pinNumber, state); // store the output value in the field pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = state; } else { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } } NANOCLR_NOCLEANUP(); } HRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4( CLR_RT_StackFrame& stack ) { NANOCLR_HEADER(); { CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } // get pin number and take the port and pad references from that one int16_t pinNumber = pThis[ FIELD___pinNumber ].NumericByRefConst().s4; // get alternate function argument int32_t alternateFunction = stack.Arg1().NumericByRef().s4; Esp32_SetMappedDevicePins( (uint8_t)pinNumber, alternateFunction ); } NANOCLR_NOCLEANUP(); } <|endoftext|>
<commit_before>#include "condor_common.h" #include "condor_config.h" #include "condor_state.h" #include "condor_api.h" #include "status_types.h" #include "totals.h" #include "my_hostname.h" #include "get_full_hostname.h" // global variables AttrListPrintMask pm; char *DEFAULT= "<default>"; char *pool = NULL; AdTypes type = (AdTypes) -1; ppOption ppStyle = PP_NOTSET; int wantOnlyTotals = 0; int summarySize = -1; Mode mode = MODE_NOTSET; int diagnose = 0; CondorQuery *query; char buffer[1024]; ClassAdList result; char *myName; // function declarations void usage (); void firstPass (int, char *[]); void secondPass (int, char *[]); void prettyPrint(ClassAdList &, TrackTotals *); int matchPrefix(const char *, const char *); int lessThanFunc(ClassAd*,ClassAd*,void*); extern "C" int SetSyscalls (int) {return 0;} extern void setPPstyle (ppOption, int, char *); extern void setType (char *, int, char *); extern void setMode (Mode, int, char *); int main (int argc, char *argv[]) { // initialize to read from config file myName = argv[0]; config ((ClassAd*)NULL); // The arguments take two passes to process --- the first pass // figures out the mode, after which we can instantiate the required // query object. We add implied constraints from the command line in // the second pass. firstPass (argc, argv); // if the mode has not been set, it is STARTD_NORMAL if (mode == MODE_NOTSET) { setMode (MODE_STARTD_NORMAL, 0, DEFAULT); } // instantiate query object if (!(query = new CondorQuery (type))) { fprintf (stderr, "Error: Out of memory\n"); exit (1); } // set pretty print style implied by the type of entity being queried // but do it with default priority, so that explicitly requested options // can override it switch (type) { case STARTD_AD: setPPstyle(PP_STARTD_NORMAL, 0, DEFAULT); break; case SCHEDD_AD: setPPstyle(PP_SCHEDD_NORMAL, 0, DEFAULT); break; case MASTER_AD: setPPstyle(PP_MASTER_NORMAL, 0, DEFAULT); break; case CKPT_SRVR_AD: setPPstyle(PP_CKPT_SRVR_NORMAL, 0, DEFAULT); break; default: setPPstyle(PP_VERBOSE, 0, DEFAULT); } // set the constraints implied by the mode switch (mode) { case MODE_STARTD_NORMAL: case MODE_MASTER_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: break; case MODE_STARTD_AVAIL: // For now, -avail shows you machines avail to anyone. sprintf (buffer, "(TARGET.%s == TRUE)", ATTR_REQUIREMENTS); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_STATE, state_to_string(claimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addConstraint (buffer); break; default: break; } // second pass: add regular parameters and constraints if (diagnose) { printf ("----------\n"); } secondPass (argc, argv); // initialize the totals object TrackTotals totals(ppStyle); // fetch the query QueryResult q; // if diagnose was requested, just print the query ad if (diagnose) { ClassAd queryAd; // print diagnostic information about inferred internal state setMode ((Mode) 0, 0, NULL); setType (NULL, 0, NULL); setPPstyle ((ppOption) 0, 0, DEFAULT); printf ("----------\n"); q = query->getQueryAd (queryAd); queryAd.fPrint (stdout); printf ("----------\n"); fprintf (stderr, "Result of making query ad was: %d\n", q); exit (1); } if ((q = query->fetchAds (result, pool)) != Q_OK) { fprintf (stderr, "Error: Could not fetch ads --- error %s\n", getStrQueryResult(q)); exit (1); } // sort the ad by ATTR_NAME result.Sort ((SortFunctionType)lessThanFunc); // output result prettyPrint (result, &totals); // be nice ... delete query; return 0; } void usage () { fprintf (stderr,"Usage: %s [options]\n" " where [options] are zero or more of\n" "\t[-avail]\t\tPrint information about available resources\n" "\t[-ckptsrvr]\t\tDisplay checkpoint server attributes\n" "\t[-claimed]\t\tPrint information about claimed resources\n" "\t[-constraint <const>]\tAdd constraint on classads\n" "\t[-diagnose]\t\tPrint out query ad without performing query\n" "\t[-format <fmt> <attr>]\tRegister display format and attribute\n" "\t[-help]\t\t\tThis screen\n" "\t[-long]\t\t\tDisplay entire classads\n" "\t[-master]\t\tDisplay daemon master attributes\n" "\t[-pool <name>]\t\tGet information from collector <name>\n" "\t[-run]\t\t\tSame as -claimed [deprecated]\n" "\t[-schedd]\t\tDisplay attributes of schedds\n" "\t[-server]\t\tDisplay important attributes of resources\n" "\t[-startd]\t\tDisplay resource attributes\n" "\t[-submittors]\tDisplay information about request submittors\n" "\t[-total]\t\tDisplay totals only\n" "\t[-verbose]\t\tSame as -long\n", myName); } void firstPass (int argc, char *argv[]) { // Process arguments: there are dependencies between them // o -l/v and -serv are mutually exclusive // o -sub, -avail and -run are mutually exclusive // o -pool and -entity may be used at most once // o since -c can be processed only after the query has been instantiated, // constraints are added on the second pass for (int i = 1; i < argc; i++) { if (matchPrefix (argv[i], "-avail")) { setMode (MODE_STARTD_AVAIL, i, argv[i]); } else if (matchPrefix (argv[i], "-pool")) { if (pool == NULL) { pool = argv[++i]; } else { fprintf (stderr, "At most one -pool argument may be used\n"); exit (1); } } else if (matchPrefix (argv[i], "-format")) { setPPstyle (PP_CUSTOM, i, argv[i]); i += 2; } else if (matchPrefix (argv[i], "-constraint")) { // can add constraints on second pass only i++; } else if (matchPrefix (argv[i], "-diagnose")) { diagnose = 1; } else if (matchPrefix (argv[i], "-help")) { usage (); exit (1); } else if (matchPrefix (argv[i],"-long") || matchPrefix (argv[i],"-verbose")) { setPPstyle (PP_VERBOSE, i, argv[i]); } else if (matchPrefix (argv[i], "-run") || matchPrefix(argv[i], "-claimed")) { setMode (MODE_STARTD_RUN, i, argv[i]); } else if (matchPrefix (argv[i], "-server")) { setPPstyle (PP_STARTD_SERVER, i, argv[i]); } else if (matchPrefix (argv[i], "-startd")) { setMode (MODE_STARTD_NORMAL,i, argv[i]); } else if (matchPrefix (argv[i], "-schedd")) { setMode (MODE_SCHEDD_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-submittors")) { setMode (MODE_SCHEDD_SUBMITTORS, i, argv[i]); } else if (matchPrefix (argv[i], "-master")) { setMode (MODE_MASTER_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-ckptsrvr")) { setMode (MODE_CKPT_SRVR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-total")) { wantOnlyTotals = 1; } else if (*argv[i] == '-') { fprintf (stderr, "Error: Unknown option %s\n", argv[i]); usage (); exit (1); } } } void secondPass (int argc, char *argv[]) { char *fullname; for (int i = 1; i < argc; i++) { // omit parameters which qualify switches if (matchPrefix (argv[i], "-pool")) { i++; continue; } if (matchPrefix (argv[i], "-format")) { pm.registerFormat (argv[i+1], argv[i+2]); if (diagnose) { printf ("Arg %d --- register format [%s] for [%s]\n", i, argv[i+1], argv[i+2]); } i += 2; continue; } // figure out what the other parameters should do if (*argv[i] != '-') { // display extra information for diagnosis if (diagnose) { printf ("Arg %d (%s) --- adding constraint", i, argv[i]); } if( !(fullname = get_full_hostname(argv[i])) ) { fprintf( stderr, "%s: unknown host %s\n", argv[0], argv[i] ); exit(1); } switch (mode) { case MODE_STARTD_NORMAL: case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: case MODE_MASTER_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_STARTD_AVAIL: sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_NAME, fullname); if (diagnose) { printf ("[%s]\n", buffer); } query->addConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer,"TARGET.%s == \"%s\"",ATTR_REMOTE_USER,argv[i]); if (diagnose) { printf ("[%s]\n", buffer); } query->addConstraint (buffer); break; default: fprintf(stderr,"Error: Don't know how to process %s\n",argv[i]); } } else if (matchPrefix (argv[i], "-constraint")) { if (diagnose) { printf ("[%s]\n", argv[i+1]); } query->addConstraint (argv[i+1]); i++; } } } int matchPrefix (const char *s1, const char *s2) { int lenS1 = strlen (s1); int lenS2 = strlen (s2); int len = (lenS1 < lenS2) ? lenS1 : lenS2; return (strncmp (s1, s2, len) == 0); } int lessThanFunc(ClassAd *ad1, ClassAd *ad2, void *) { char name1[64]; char name2[64]; if (!ad1->LookupString(ATTR_NAME, name1) || !ad2->LookupString(ATTR_NAME, name2)) return 0; return (strcmp (name1, name2) < 0); } <commit_msg>condor_status -avail now only shows you machines in the unclaimed state, which are available to anyone. Just going on requirements == True doesn't do it, since when you're claimed, your START exp evalutes to true as well.<commit_after>#include "condor_common.h" #include "condor_config.h" #include "condor_state.h" #include "condor_api.h" #include "status_types.h" #include "totals.h" #include "my_hostname.h" #include "get_full_hostname.h" // global variables AttrListPrintMask pm; char *DEFAULT= "<default>"; char *pool = NULL; AdTypes type = (AdTypes) -1; ppOption ppStyle = PP_NOTSET; int wantOnlyTotals = 0; int summarySize = -1; Mode mode = MODE_NOTSET; int diagnose = 0; CondorQuery *query; char buffer[1024]; ClassAdList result; char *myName; // function declarations void usage (); void firstPass (int, char *[]); void secondPass (int, char *[]); void prettyPrint(ClassAdList &, TrackTotals *); int matchPrefix(const char *, const char *); int lessThanFunc(ClassAd*,ClassAd*,void*); extern "C" int SetSyscalls (int) {return 0;} extern void setPPstyle (ppOption, int, char *); extern void setType (char *, int, char *); extern void setMode (Mode, int, char *); int main (int argc, char *argv[]) { // initialize to read from config file myName = argv[0]; config ((ClassAd*)NULL); // The arguments take two passes to process --- the first pass // figures out the mode, after which we can instantiate the required // query object. We add implied constraints from the command line in // the second pass. firstPass (argc, argv); // if the mode has not been set, it is STARTD_NORMAL if (mode == MODE_NOTSET) { setMode (MODE_STARTD_NORMAL, 0, DEFAULT); } // instantiate query object if (!(query = new CondorQuery (type))) { fprintf (stderr, "Error: Out of memory\n"); exit (1); } // set pretty print style implied by the type of entity being queried // but do it with default priority, so that explicitly requested options // can override it switch (type) { case STARTD_AD: setPPstyle(PP_STARTD_NORMAL, 0, DEFAULT); break; case SCHEDD_AD: setPPstyle(PP_SCHEDD_NORMAL, 0, DEFAULT); break; case MASTER_AD: setPPstyle(PP_MASTER_NORMAL, 0, DEFAULT); break; case CKPT_SRVR_AD: setPPstyle(PP_CKPT_SRVR_NORMAL, 0, DEFAULT); break; default: setPPstyle(PP_VERBOSE, 0, DEFAULT); } // set the constraints implied by the mode switch (mode) { case MODE_STARTD_NORMAL: case MODE_MASTER_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: break; case MODE_STARTD_AVAIL: // For now, -avail shows you machines avail to anyone. sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_STATE, state_to_string(unclaimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_STATE, state_to_string(claimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addConstraint (buffer); break; default: break; } // second pass: add regular parameters and constraints if (diagnose) { printf ("----------\n"); } secondPass (argc, argv); // initialize the totals object TrackTotals totals(ppStyle); // fetch the query QueryResult q; // if diagnose was requested, just print the query ad if (diagnose) { ClassAd queryAd; // print diagnostic information about inferred internal state setMode ((Mode) 0, 0, NULL); setType (NULL, 0, NULL); setPPstyle ((ppOption) 0, 0, DEFAULT); printf ("----------\n"); q = query->getQueryAd (queryAd); queryAd.fPrint (stdout); printf ("----------\n"); fprintf (stderr, "Result of making query ad was: %d\n", q); exit (1); } if ((q = query->fetchAds (result, pool)) != Q_OK) { fprintf (stderr, "Error: Could not fetch ads --- error %s\n", getStrQueryResult(q)); exit (1); } // sort the ad by ATTR_NAME result.Sort ((SortFunctionType)lessThanFunc); // output result prettyPrint (result, &totals); // be nice ... delete query; return 0; } void usage () { fprintf (stderr,"Usage: %s [options]\n" " where [options] are zero or more of\n" "\t[-avail]\t\tPrint information about available resources\n" "\t[-ckptsrvr]\t\tDisplay checkpoint server attributes\n" "\t[-claimed]\t\tPrint information about claimed resources\n" "\t[-constraint <const>]\tAdd constraint on classads\n" "\t[-diagnose]\t\tPrint out query ad without performing query\n" "\t[-format <fmt> <attr>]\tRegister display format and attribute\n" "\t[-help]\t\t\tThis screen\n" "\t[-long]\t\t\tDisplay entire classads\n" "\t[-master]\t\tDisplay daemon master attributes\n" "\t[-pool <name>]\t\tGet information from collector <name>\n" "\t[-run]\t\t\tSame as -claimed [deprecated]\n" "\t[-schedd]\t\tDisplay attributes of schedds\n" "\t[-server]\t\tDisplay important attributes of resources\n" "\t[-startd]\t\tDisplay resource attributes\n" "\t[-submittors]\tDisplay information about request submittors\n" "\t[-total]\t\tDisplay totals only\n" "\t[-verbose]\t\tSame as -long\n", myName); } void firstPass (int argc, char *argv[]) { // Process arguments: there are dependencies between them // o -l/v and -serv are mutually exclusive // o -sub, -avail and -run are mutually exclusive // o -pool and -entity may be used at most once // o since -c can be processed only after the query has been instantiated, // constraints are added on the second pass for (int i = 1; i < argc; i++) { if (matchPrefix (argv[i], "-avail")) { setMode (MODE_STARTD_AVAIL, i, argv[i]); } else if (matchPrefix (argv[i], "-pool")) { if (pool == NULL) { pool = argv[++i]; } else { fprintf (stderr, "At most one -pool argument may be used\n"); exit (1); } } else if (matchPrefix (argv[i], "-format")) { setPPstyle (PP_CUSTOM, i, argv[i]); i += 2; } else if (matchPrefix (argv[i], "-constraint")) { // can add constraints on second pass only i++; } else if (matchPrefix (argv[i], "-diagnose")) { diagnose = 1; } else if (matchPrefix (argv[i], "-help")) { usage (); exit (1); } else if (matchPrefix (argv[i],"-long") || matchPrefix (argv[i],"-verbose")) { setPPstyle (PP_VERBOSE, i, argv[i]); } else if (matchPrefix (argv[i], "-run") || matchPrefix(argv[i], "-claimed")) { setMode (MODE_STARTD_RUN, i, argv[i]); } else if (matchPrefix (argv[i], "-server")) { setPPstyle (PP_STARTD_SERVER, i, argv[i]); } else if (matchPrefix (argv[i], "-startd")) { setMode (MODE_STARTD_NORMAL,i, argv[i]); } else if (matchPrefix (argv[i], "-schedd")) { setMode (MODE_SCHEDD_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-submittors")) { setMode (MODE_SCHEDD_SUBMITTORS, i, argv[i]); } else if (matchPrefix (argv[i], "-master")) { setMode (MODE_MASTER_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-ckptsrvr")) { setMode (MODE_CKPT_SRVR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-total")) { wantOnlyTotals = 1; } else if (*argv[i] == '-') { fprintf (stderr, "Error: Unknown option %s\n", argv[i]); usage (); exit (1); } } } void secondPass (int argc, char *argv[]) { char *fullname; for (int i = 1; i < argc; i++) { // omit parameters which qualify switches if (matchPrefix (argv[i], "-pool")) { i++; continue; } if (matchPrefix (argv[i], "-format")) { pm.registerFormat (argv[i+1], argv[i+2]); if (diagnose) { printf ("Arg %d --- register format [%s] for [%s]\n", i, argv[i+1], argv[i+2]); } i += 2; continue; } // figure out what the other parameters should do if (*argv[i] != '-') { // display extra information for diagnosis if (diagnose) { printf ("Arg %d (%s) --- adding constraint", i, argv[i]); } if( !(fullname = get_full_hostname(argv[i])) ) { fprintf( stderr, "%s: unknown host %s\n", argv[0], argv[i] ); exit(1); } switch (mode) { case MODE_STARTD_NORMAL: case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: case MODE_MASTER_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_STARTD_AVAIL: sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_NAME, fullname); if (diagnose) { printf ("[%s]\n", buffer); } query->addConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer,"TARGET.%s == \"%s\"",ATTR_REMOTE_USER,argv[i]); if (diagnose) { printf ("[%s]\n", buffer); } query->addConstraint (buffer); break; default: fprintf(stderr,"Error: Don't know how to process %s\n",argv[i]); } } else if (matchPrefix (argv[i], "-constraint")) { if (diagnose) { printf ("[%s]\n", argv[i+1]); } query->addConstraint (argv[i+1]); i++; } } } int matchPrefix (const char *s1, const char *s2) { int lenS1 = strlen (s1); int lenS2 = strlen (s2); int len = (lenS1 < lenS2) ? lenS1 : lenS2; return (strncmp (s1, s2, len) == 0); } int lessThanFunc(ClassAd *ad1, ClassAd *ad2, void *) { char name1[64]; char name2[64]; if (!ad1->LookupString(ATTR_NAME, name1) || !ad2->LookupString(ATTR_NAME, name2)) return 0; return (strcmp (name1, name2) < 0); } <|endoftext|>
<commit_before>#ifndef CONTROLLER_HPP #define CONTROLLER_HPP #include "Position6DOF.hpp" #include "Formation.hpp" #include "ros/ros.h" //Ros messages/services #include "api_application/MoveFormation.h" // ? (D) #include "../matlab/Vector.h" #include "control_application/quadcopter_movement.h" // ? (D) #include "api_application/SetFormation.h" #include "quadcopter_application/find_all.h" #include "quadcopter_application/blink.h" #include "quadcopter_application/quadcopter_status.h" #include "control_application/BuildFormation.h" #include "api_application/Shutdown.h" #include <time.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <string> #include <vector> #include <pthread.h> #include <list> #include "Mutex.hpp" #include <cmath> #include <time.h> #include <sstream> #include <boost/bind.hpp> #define THRUST_MIN 10001 #define THRUST_STAND_STILL 18001 #define THRUST_START 22000 #define THRUST_DECLINE 20000 #define THRUST_STEP 50 #define ROLL_STEP 2 #define PITCH_STEP 2 #define INVALID -1 /* Used for lists */ #define MAX_NUMBER_QUADCOPTER 10 #define POS_CHECK (current[0] != target[0]) || (current[1] != target[1]) || (current[2] != target[2]) class Controller : public IPositionReceiver { class Controller { public: Controller(); /* Initializing */ void initialize(); /* Movement and Positioning */ void calculateMovement(); void sendMovement(); void convertMovement(double* const vector); Position6DOF* getTargetPosition(); void setTargetPosition(); void updatePositions(std::vector<Vector> positions, std::vector<int> ids, std::vector<int> updates); void reachTrackedArea(std::vector<int> ids); /* Formation */ bool buildFormation(control_application::BuildFormation::Request &req, control_application::BuildFormation::Response &res); void shutdownFormation(); bool shutdown(control_application::Shutdown::Request &req, control_application::Shutdown::Response &res); void checkInputMovement(); protected: //Callbacks for Ros subscriber void MoveFormationCallback(const api_application::MoveFormation::ConstPtr& msg); void SetFormationCallback(const api_application::SetFormation::ConstPtr& msg); void QuadStatusCallback(const quadcopter_application::quadcopter_status::ConstPtr& msg, int topicNr); void stopReachTrackedArea(); void moveUp(std::vector<int> ids); private: /* */ /* Position */ std::vector<Position6DOF> targetPosition; std::vector<Position6DOF> currentPosition; //std::vector<rpy-values> sentMovement; std::list<std::vector<Position6DOF> > listPositions; std::list<std::vector<Position6DOF> > listTargets; std::list<std::vector<Position6DOF> > listSendTargets; /* Identification of Quadcopters */ int amount; /* Unknown at start, variable at runtime. */ Formation formation; float formationMovement[3]; /*TODO*/ //Receive data over ROS Formation formation; //TODO needs to be with service find all int totalAmount; int amount; float formationMovement[3]; //Mapping of int id to string id/ hardware id qc[id][uri/hardware id] std::vector<std::string> quadcopters; /* Set data */ /*TODO*/ int thrust; float pitch, roll, yawrate; /* Received data */ /*TODO*/ int id; std::vector<float> pitch_stab; std::vector<float> roll_stab; std::vector<float> yaw_stab; std::vector<unsigned int> thrust_stab; std::vector<float> battery_status; std::string idString; /*int id;*/ int startProcess; /* int newTarget;*/ /* int newCurrent;*/ std::vector<bool> tracked; /* bool newTarget;*/ /* bool newCurrent;*/ std::vector<string> idString; //Control variables //Array of tracked quadcopters std::vector<bool> tracked; //Set when we are in the shutdown process bool shutdownStarted; bool getTracked; /* Mutex */ Mutex curPosMutex; Mutex tarPosMutex; Mutex shutdownMutex; Mutex listPositionsMutex; Mutex getTrackedMutex; /* Threads */ pthread_t tCalc; pthread_t tSend; pthread_t tGetTracked; /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; //Subscriber //Subscriber for the MoveFormation data ros::Subscriber MoveFormation_sub; //Subscriber for Formation data from API ros::Subscriber SetFormation_sub; //Subscriber for Quadcopter data from QuadcopterModul //ros::Subscriber QuadStatus_sub; std::vector<ros::Subscriber> QuadStatus_sub; /* Publisher */ //Publisher for the Movement data of the Quadcopts (1000 is the max. buffered messages) //ros::Publisher Movement_pub; std::vector<ros::Publisher> Movement_pub; /* Services */ //Service for building formation ros::ServiceServer BuildForm_srv; //Service for shutingdown formation ros::ServiceServer Shutdown_srv; //Clients ros::ServiceClient FindAll_client; ros::ServiceClient Blink_client; }; #endif // CONTROLLER_HPP <commit_msg>Removing errors<commit_after>#ifndef CONTROLLER_HPP #define CONTROLLER_HPP #include "Position6DOF.hpp" #include "Formation.hpp" #include "ros/ros.h" //Ros messages/services #include "api_application/MoveFormation.h" // ? (D) #include "../matlab/Vector.h" #include "control_application/quadcopter_movement.h" // ? (D) #include "api_application/SetFormation.h" #include "quadcopter_application/find_all.h" #include "quadcopter_application/blink.h" #include "quadcopter_application/quadcopter_status.h" #include "control_application/BuildFormation.h" //#include "api_application/Shutdown.h" #include "../position/IPositionReceiver.hpp" #include <time.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <string> #include <vector> #include <pthread.h> #include <list> #include "Mutex.hpp" #include <cmath> #include <time.h> #include <sstream> #include <boost/bind.hpp> #define THRUST_MIN 10001 #define THRUST_STAND_STILL 18001 #define THRUST_START 22000 #define THRUST_DECLINE 20000 #define THRUST_STEP 50 #define ROLL_STEP 2 #define PITCH_STEP 2 #define INVALID -1 /* Used for lists */ #define MAX_NUMBER_QUADCOPTER 10 #define POS_CHECK (current[0] != target[0]) || (current[1] != target[1]) || (current[2] != target[2]) class Controller : public IPositionReceiver { //class Controller { public: Controller(); /* Initializing */ void initialize(); /* Movement and Positioning */ void convertMovement(double* const vector); Position6DOF* getTargetPosition(); void setTargetPosition(); void updatePositions(std::vector<Vector> positions, std::vector<int> ids, std::vector<int> updates); void reachTrackedArea(std::vector<int> ids); /* Formation */ bool buildFormation(control_application::BuildFormation::Request &req, control_application::BuildFormation::Response &res); void shutdownFormation(); bool shutdown(control_application::Shutdown::Request &req, control_application::Shutdown::Response &res); void checkInputMovement(); protected: //Callbacks for Ros subscriber void MoveFormationCallback(const api_application::MoveFormation::ConstPtr& msg); void SetFormationCallback(const api_application::SetFormation::ConstPtr& msg); void QuadStatusCallback(const quadcopter_application::quadcopter_status::ConstPtr& msg, int topicNr); void stopReachTrackedArea(); void moveUp(std::vector<int> ids); private: /* */ /* Position */ std::vector<Position6DOF> targetPosition; std::vector<Position6DOF> currentPosition; //std::vector<rpy-values> sentMovement; std::list<std::vector<Position6DOF> > listPositions; std::list<std::vector<Position6DOF> > listTargets; std::list<std::vector<Position6DOF> > listSendTargets; /* Identification of Quadcopters */ //Receive data over ROS Formation formation(); //TODO needs to be with service find all int totalAmount; int amount; float formationMovement[3]; //Mapping of int id to string id/ hardware id qc[id][uri/hardware id] std::vector<std::string> quadcopters; /* Set data */ /*TODO*/ int thrust; float pitch, roll, yawrate; /* Received data */ /*TODO*/ int id; std::vector<float> pitch_stab; std::vector<float> roll_stab; std::vector<float> yaw_stab; std::vector<unsigned int> thrust_stab; std::vector<float> battery_status; int startProcess; /* int newTarget;*/ /* int newCurrent;*/ std::vector<std::string> idString; //Control variables //Array of tracked quadcopters std::vector<bool> tracked; //Set when we are in the shutdown process bool shutdownStarted; bool getTracked; /* Mutex */ Mutex curPosMutex; Mutex tarPosMutex; Mutex shutdownMutex; Mutex listPositionsMutex; Mutex getTrackedMutex; /* Threads */ pthread_t tCalc; pthread_t tSend; pthread_t tGetTracked; /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; //Subscriber //Subscriber for the MoveFormation data ros::Subscriber MoveFormation_sub; //Subscriber for Formation data from API ros::Subscriber SetFormation_sub; //Subscriber for Quadcopter data from QuadcopterModul //ros::Subscriber QuadStatus_sub; std::vector<ros::Subscriber> QuadStatus_sub; /* Publisher */ //Publisher for the Movement data of the Quadcopts (1000 is the max. buffered messages) //ros::Publisher Movement_pub; std::vector<ros::Publisher> Movement_pub; /* Services */ //Service for building formation ros::ServiceServer BuildForm_srv; //Service for shutingdown formation ros::ServiceServer Shutdown_srv; //Clients ros::ServiceClient FindAll_client; ros::ServiceClient Blink_client; }; #endif // CONTROLLER_HPP <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkOpts.h" #include "SkRasterPipeline.h" SkRasterPipeline::SkRasterPipeline() {} void SkRasterPipeline::append(StockStage stage, void* ctx) { #ifdef SK_DEBUG if (fNum == (int)SK_ARRAY_COUNT(fStages)) { this->dump(); } #endif SkASSERT(fNum < (int)SK_ARRAY_COUNT(fStages)); fStages[fNum++] = { stage, ctx }; } void SkRasterPipeline::extend(const SkRasterPipeline& src) { for (int i = 0; i < src.fNum; i++) { const Stage& s = src.fStages[i]; this->append(s.stage, s.ctx); } } void SkRasterPipeline::run(size_t x, size_t y, size_t n) const { SkOpts::run_pipeline(x,y,n, fStages, fNum); } std::function<void(size_t, size_t, size_t)> SkRasterPipeline::compile() const { return SkOpts::compile_pipeline(fStages, fNum); } static bool invariant_in_x(const SkRasterPipeline::Stage& st) { if (st.ctx == nullptr) { // If a stage doesn't have a context pointer, it can't really do anything with x. return true; } // This would be a lot more compact as a blacklist (the loads, the stores, the gathers), // but it's safer to write as a whitelist. If we get it wrong this way, not a big deal. switch (st.stage) { default: return false; case SkRasterPipeline::trace: case SkRasterPipeline::set_rgb: case SkRasterPipeline::constant_color: case SkRasterPipeline::scale_constant_float: case SkRasterPipeline::lerp_constant_float: case SkRasterPipeline::matrix_2x3: case SkRasterPipeline::matrix_3x4: case SkRasterPipeline::matrix_4x5: case SkRasterPipeline::matrix_perspective: case SkRasterPipeline::parametric_r: case SkRasterPipeline::parametric_g: case SkRasterPipeline::parametric_b: case SkRasterPipeline::table_r: case SkRasterPipeline::table_g: case SkRasterPipeline::table_b: case SkRasterPipeline::color_lookup_table: case SkRasterPipeline::lab_to_xyz: case SkRasterPipeline::clamp_x: case SkRasterPipeline::mirror_x: case SkRasterPipeline::repeat_x: case SkRasterPipeline::clamp_y: case SkRasterPipeline::mirror_y: case SkRasterPipeline::repeat_y: case SkRasterPipeline::top_left: case SkRasterPipeline::top_right: case SkRasterPipeline::bottom_left: case SkRasterPipeline::bottom_right: case SkRasterPipeline::accumulate: SkASSERT(st.ctx != nullptr); return true; } return false; } void SkRasterPipeline::dump() const { SkDebugf("SkRasterPipeline, %d stages\n", fNum); bool in_constant_run = false; for (int i = 0; i < fNum; i++) { const char* name = ""; switch (fStages[i].stage) { #define M(x) case x: name = #x; break; SK_RASTER_PIPELINE_STAGES(M) #undef M } char mark = ' '; if (fStages[i].stage == SkRasterPipeline::constant_color) { mark = '*'; in_constant_run = true; } else if (in_constant_run && invariant_in_x(fStages[i])) { mark = '|'; } else { mark = ' '; in_constant_run = false; } SkDebugf("\t%c %s\n", mark, name); } SkDebugf("\n"); } <commit_msg>Revert "Show constant-foldable runs in SkRasterPipeline::dump()."<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkOpts.h" #include "SkRasterPipeline.h" SkRasterPipeline::SkRasterPipeline() {} void SkRasterPipeline::append(StockStage stage, void* ctx) { #ifdef SK_DEBUG if (fNum == (int)SK_ARRAY_COUNT(fStages)) { this->dump(); } #endif SkASSERT(fNum < (int)SK_ARRAY_COUNT(fStages)); fStages[fNum++] = { stage, ctx }; } void SkRasterPipeline::extend(const SkRasterPipeline& src) { for (int i = 0; i < src.fNum; i++) { const Stage& s = src.fStages[i]; this->append(s.stage, s.ctx); } } void SkRasterPipeline::run(size_t x, size_t y, size_t n) const { SkOpts::run_pipeline(x,y,n, fStages, fNum); } std::function<void(size_t, size_t, size_t)> SkRasterPipeline::compile() const { return SkOpts::compile_pipeline(fStages, fNum); } void SkRasterPipeline::dump() const { SkDebugf("SkRasterPipeline, %d stages\n", fNum); for (int i = 0; i < fNum; i++) { const char* name = ""; switch (fStages[i].stage) { #define M(x) case x: name = #x; break; SK_RASTER_PIPELINE_STAGES(M) #undef M } SkDebugf("\t%s\n", name); } SkDebugf("\n"); } <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _POSIX_SOURCE #define _POSIX_SOURCE #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <grpc/support/port_platform.h> #ifdef GPR_LINUX_LOG #include <inttypes.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> #include <string> #include "absl/strings/str_format.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/gprpp/examine_stack.h" int gpr_should_log_stacktrace(gpr_log_severity severity); static long sys_gettid(void) { return syscall(__NR_gettid); } void gpr_log(const char* file, int line, gpr_log_severity severity, const char* format, ...) { /* Avoid message construction if gpr_log_message won't log */ if (gpr_should_log(severity) == 0) { return; } char* message = nullptr; va_list args; va_start(args, format); if (vasprintf(&message, format, args) == -1) { va_end(args); return; } va_end(args); gpr_log_message(file, line, severity, message); /* message has been allocated by vasprintf above, and needs free */ free(message); } void gpr_default_log(gpr_log_func_args* args) { const char* final_slash; const char* display_file; char time_buffer[64]; time_t timer; gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); struct tm tm; static thread_local long tid(0); if (tid == 0) tid = sys_gettid(); timer = static_cast<time_t>(now.tv_sec); final_slash = strrchr(args->file, '/'); if (final_slash == nullptr) { display_file = args->file; } else { display_file = final_slash + 1; } if (!localtime_r(&timer, &tm)) { strcpy(time_buffer, "error:localtime"); } else if (0 == strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) { strcpy(time_buffer, "error:strftime"); } std::string prefix = absl::StrFormat( "%s%s.%09" PRId32 " %7ld %s:%d]", gpr_log_severity_string(args->severity), time_buffer, now.tv_nsec, tid, display_file, args->line); absl::optional<std::string> stack_trace = gpr_should_log_stacktrace(args->severity) ? grpc_core::GetCurrentStackTrace() : absl::nullopt; if (stack_trace) { fprintf(stderr, "%-60s %s\n%s\n", prefix.c_str(), args->message, stack_trace->c_str()); } else { fprintf(stderr, "%-60s %s\n", prefix.c_str(), args->message); } } #endif /* GPR_LINUX_LOG */ <commit_msg>[log] Longer space for filenames (#31432)<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _POSIX_SOURCE #define _POSIX_SOURCE #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <grpc/support/port_platform.h> #ifdef GPR_LINUX_LOG #include <inttypes.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> #include <string> #include "absl/strings/str_format.h" #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/gprpp/examine_stack.h" int gpr_should_log_stacktrace(gpr_log_severity severity); static long sys_gettid(void) { return syscall(__NR_gettid); } void gpr_log(const char* file, int line, gpr_log_severity severity, const char* format, ...) { /* Avoid message construction if gpr_log_message won't log */ if (gpr_should_log(severity) == 0) { return; } char* message = nullptr; va_list args; va_start(args, format); if (vasprintf(&message, format, args) == -1) { va_end(args); return; } va_end(args); gpr_log_message(file, line, severity, message); /* message has been allocated by vasprintf above, and needs free */ free(message); } void gpr_default_log(gpr_log_func_args* args) { const char* final_slash; const char* display_file; char time_buffer[64]; time_t timer; gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); struct tm tm; static thread_local long tid(0); if (tid == 0) tid = sys_gettid(); timer = static_cast<time_t>(now.tv_sec); final_slash = strrchr(args->file, '/'); if (final_slash == nullptr) { display_file = args->file; } else { display_file = final_slash + 1; } if (!localtime_r(&timer, &tm)) { strcpy(time_buffer, "error:localtime"); } else if (0 == strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) { strcpy(time_buffer, "error:strftime"); } std::string prefix = absl::StrFormat( "%s%s.%09" PRId32 " %7ld %s:%d]", gpr_log_severity_string(args->severity), time_buffer, now.tv_nsec, tid, display_file, args->line); absl::optional<std::string> stack_trace = gpr_should_log_stacktrace(args->severity) ? grpc_core::GetCurrentStackTrace() : absl::nullopt; if (stack_trace) { fprintf(stderr, "%-70s %s\n%s\n", prefix.c_str(), args->message, stack_trace->c_str()); } else { fprintf(stderr, "%-70s %s\n", prefix.c_str(), args->message); } } #endif /* GPR_LINUX_LOG */ <|endoftext|>
<commit_before> #include "CPPFORT/HEPEVT.h" #include <cstdlib> #include <cmath> #include <iostream> using namespace std ; using namespace lcio ; namespace HEPEVTIMPL{ void HEPEVT::fromHepEvt(LCEvent * evt){ float* p = new float[3] ; // set event number from stdhep COMMON int* IEVENT = &FTNhep.nevhep ; LCEventImpl* evtimpl = reinterpret_cast<LCEventImpl*>( (evt) ) ; evtimpl->setEventNumber( *IEVENT ) ; // create and add mc particles from stdhep COMMON LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ; // create a particle instance for each HEPEVT entry // and add it to the collection - leave parent relations empty int* NMCPART = &FTNhep.nhep; for(int j=0;j < *NMCPART;j++) { MCParticleImpl* mcp = new MCParticleImpl ; mcp->setPDG( FTNhep.idhep[j] ) ; mcp->setGeneratorStatus( FTNhep.isthep[j] ) ; // now momentum, vertex, charge for(int k=0;k<3;k++) p[k] = (float)FTNhep.phep[j][k]; mcp->setMomentum( p ); mcp->setMass( (float)FTNhep.phep[j][4] ) ; mcp->setVertex( FTNhep.vhep[j] ) ; // finally store pointer and set charge FTNhep1.mcpointerv[j] = reinterpret_cast<PTRTYPE>( (mcp) ) ; mcp->setCharge( FTNhep1.mcchargev[j] ) ; mcVec->push_back( mcp ) ; } // now loop one more time and add parent relations // NB: this assumes that the parent relations are consistent, i.e. any particle // referred to as daughter in the hepevt common block refers to the corresponding // particle as mother for(int j=0;j < *NMCPART;j++) { MCParticleImpl* mcp = dynamic_cast<MCParticleImpl*>( mcVec->getElementAt( j ) ) ; // now get parents if required and set daughter if parent1 is defined int parent1 = FTNhep.jmohep[j][0] ; int parent2 = FTNhep.jmohep[j][1] ; if( parent1 > 0 ) { MCParticle* mom = dynamic_cast<MCParticle*>( mcVec->getElementAt( parent1-1 ) ) ; mcp->addParent( mom ) ; if( parent2 > 0 ) for(int i = parent1 ; i < parent2 ; i++ ){ MCParticle* mom = dynamic_cast<MCParticle*>( mcVec->getElementAt( i ) ) ; mcp->addParent( mom ) ; } } } // add all collection to the event evt->addCollection( (LCCollection*) mcVec , "MCParticle" ) ; delete p ; } // end of fromHepEvt /* ============================================================================================================= */ void HEPEVT::toHepEvt(const LCEvent* evt){ int* kmax = new int ; double* maxxyz = new double; // set event number in stdhep COMMON FTNhep.nevhep = evt->getEventNumber() ; // fill MCParticles into stdhep COMMON LCCollection* mcVec = evt->getCollection( LCIO::MCPARTICLE ) ; FTNhep.nhep = mcVec->getNumberOfElements() ; int* NMCPART = &FTNhep.nhep ; for(int j=0;j < *NMCPART;j++) { //for each MCParticle fill hepevt common line const MCParticle* mcp = dynamic_cast<const MCParticle*>( mcVec->getElementAt( j ) ) ; FTNhep.idhep[j] = mcp->getPDG() ; FTNhep.isthep[j] = mcp->getGeneratorStatus() ; // store mother indices FTNhep.jmohep[j][0] = 0 ; FTNhep.jmohep[j][1] = 0 ; const MCParticle* mcpp = 0 ; int nparents = mcp->getNumberOfParents() ; if( nparents > 0 ) mcpp = mcp->getParent(0) ; try{ for(int jjm=0;jjm < *NMCPART;jjm++) { if (mcpp == dynamic_cast<const MCParticle*>(mcVec->getElementAt( jjm )) ){ FTNhep.jmohep[j][0] = jjm + 1 ; break ; } } }catch(exception& e){ } if ( FTNhep.jmohep[j][0] > 0 ) { try{ const MCParticle* mcpsp = 0 ; if( mcp->getNumberOfParents() > 1 ) mcpsp = mcp->getParent( nparents-1 ) ; for(int jjj=0;jjj < *NMCPART;jjj++) { if (mcpsp == dynamic_cast<const MCParticle*>(mcVec->getElementAt( jjj )) ){ FTNhep.jmohep[j][1] = jjj + 1 ; break ; } } }catch(exception& e){ FTNhep.jmohep[j][1] = 0 ; } } // store daugther indices FTNhep.jdahep[j][0] = 0 ; FTNhep.jdahep[j][1] = 0 ; // for the StdHep convention particles with GeneratorStatus = 3 have no daughters if ( FTNhep.isthep[j] != 3 ) { int ndaugthers = mcp->getNumberOfDaughters() ; if (ndaugthers > 0) { const MCParticle* mcpd = mcp->getDaughter( 0 ) ; for (int jjj=0; jjj < *NMCPART; jjj++) { const MCParticle* mcpdtest = dynamic_cast<const MCParticle*>(mcVec->getElementAt( jjj )) ; if ( mcpd == mcpdtest ) { FTNhep.jdahep[j][0] = jjj + 1 ; FTNhep.jdahep[j][1] = FTNhep.jdahep[j][0] + ndaugthers -1 ; break ; } } } } // now momentum, energy, and mass for(int k=0;k<3;k++) FTNhep.phep[j][k] = (double)mcp->getMomentum()[k] ; FTNhep.phep[j][3] = (double)mcp->getEnergy() ; FTNhep.phep[j][4] = (double)mcp->getMass() ; // get vertex and production time *kmax = 0 ; *maxxyz = 0. ; for(int k=0;k<3;k++){ FTNhep.vhep[j][k] = mcp->getVertex()[k] ; if ( fabs( FTNhep.vhep[j][k] ) > *maxxyz ){ *maxxyz = fabs( FTNhep.vhep[j][k] ) ; *kmax = k ; } } if ( mcpp != 0 && *maxxyz > 0. ) { FTNhep.vhep[j][3] = FTNhep.vhep[FTNhep.jmohep[j][0]-1][3] + (mcp->getVertex()[*kmax] - mcpp->getVertex()[*kmax]) * mcpp->getEnergy() / mcpp->getMomentum()[*kmax] ; } else { FTNhep.vhep[j][3] = 0. ; // no production time for MCParticle } // finally store pointer and get charge FTNhep1.mcpointerv[j] = reinterpret_cast<PTRTYPE>( (mcp) ) ; FTNhep1.mcchargev[j] = mcp->getCharge() ; } delete kmax ; delete maxxyz ; } // end of toHepEvt } //namespace HEPEVTIMPL <commit_msg>modified<commit_after> #include "CPPFORT/HEPEVT.h" #include <cstdlib> #include <cmath> #include <iostream> using namespace std ; using namespace lcio ; namespace HEPEVTIMPL{ void HEPEVT::fromHepEvt(LCEvent * evt){ float* p = new float[3] ; // create and add mc particles from stdhep COMMON LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ; // create a particle instance for each HEPEVT entry // and add it to the collection - leave parent relations empty int* NMCPART = &FTNhep.nhep; for(int j=0;j < *NMCPART;j++) { MCParticleImpl* mcp = new MCParticleImpl ; mcp->setPDG( FTNhep.idhep[j] ) ; mcp->setGeneratorStatus( FTNhep.isthep[j] ) ; // now momentum, vertex, charge for(int k=0;k<3;k++) p[k] = (float)FTNhep.phep[j][k]; mcp->setMomentum( p ); mcp->setMass( (float)FTNhep.phep[j][4] ) ; mcp->setVertex( FTNhep.vhep[j] ) ; // finally store pointer and set charge mcp->setCharge( FTNhep1.mcchargev[j] ) ; mcVec->push_back( mcp ) ; } // now loop one more time and add parent relations // NB: this assumes that the parent relations are consistent, i.e. any particle // referred to as daughter in the hepevt common block refers to the corresponding // particle as mother for(int j=0;j < *NMCPART;j++) { MCParticleImpl* mcp = dynamic_cast<MCParticleImpl*>( mcVec->getElementAt( j ) ) ; // now get parents if required and set daughter if parent1 is defined int parent1 = FTNhep.jmohep[j][0] ; int parent2 = FTNhep.jmohep[j][1] ; if( parent1 > 0 ) { MCParticle* mom = dynamic_cast<MCParticle*>( mcVec->getElementAt( parent1-1 ) ) ; mcp->addParent( mom ) ; if( parent2 > 0 ) for(int i = parent1 ; i < parent2 ; i++ ){ MCParticle* mom = dynamic_cast<MCParticle*>( mcVec->getElementAt( i ) ) ; mcp->addParent( mom ) ; } } } // add all collection to the event evt->addCollection( (LCCollection*) mcVec , "MCParticle" ) ; // now fill pointers for MCParticle collection LCEventImpl* evtimpl = reinterpret_cast<LCEventImpl*>(evt) ; LCCollection* getmcVec = evtimpl->getCollection( "MCParticle" ) ; int nelem = getmcVec->getNumberOfElements() ; for(int j=0;j < nelem; j++) { FTNhep1.mcpointerv[j] = reinterpret_cast<PTRTYPE>( getmcVec->getElementAt( j ) ) ; } delete p ; } // end of fromHepEvt /* ============================================================================================================= */ void HEPEVT::toHepEvt(const LCEvent* evt){ int* kmax = new int ; double* maxxyz = new double; // set event number in stdhep COMMON FTNhep.nevhep = evt->getEventNumber() ; // fill MCParticles into stdhep COMMON LCCollection* mcVec = evt->getCollection( LCIO::MCPARTICLE ) ; FTNhep.nhep = mcVec->getNumberOfElements() ; int* NMCPART = &FTNhep.nhep ; for(int j=0;j < *NMCPART;j++) { //for each MCParticle fill hepevt common line const MCParticle* mcp = dynamic_cast<const MCParticle*>( mcVec->getElementAt( j ) ) ; FTNhep.idhep[j] = mcp->getPDG() ; FTNhep.isthep[j] = mcp->getGeneratorStatus() ; // store mother indices FTNhep.jmohep[j][0] = 0 ; FTNhep.jmohep[j][1] = 0 ; const MCParticle* mcpp = 0 ; int nparents = mcp->getNumberOfParents() ; if( nparents > 0 ) mcpp = mcp->getParent(0) ; try{ for(int jjm=0;jjm < *NMCPART;jjm++) { if (mcpp == dynamic_cast<const MCParticle*>(mcVec->getElementAt( jjm )) ){ FTNhep.jmohep[j][0] = jjm + 1 ; break ; } } }catch(exception& e){ } if ( FTNhep.jmohep[j][0] > 0 ) { try{ const MCParticle* mcpsp = 0 ; if( mcp->getNumberOfParents() > 1 ) mcpsp = mcp->getParent( nparents-1 ) ; for(int jjj=0;jjj < *NMCPART;jjj++) { if (mcpsp == dynamic_cast<const MCParticle*>(mcVec->getElementAt( jjj )) ){ FTNhep.jmohep[j][1] = jjj + 1 ; break ; } } }catch(exception& e){ FTNhep.jmohep[j][1] = 0 ; } } // store daugther indices FTNhep.jdahep[j][0] = 0 ; FTNhep.jdahep[j][1] = 0 ; // for the StdHep convention particles with GeneratorStatus = 3 have no daughters if ( FTNhep.isthep[j] != 3 ) { int ndaugthers = mcp->getNumberOfDaughters() ; if (ndaugthers > 0) { const MCParticle* mcpd = mcp->getDaughter( 0 ) ; for (int jjj=0; jjj < *NMCPART; jjj++) { const MCParticle* mcpdtest = dynamic_cast<const MCParticle*>(mcVec->getElementAt( jjj )) ; if ( mcpd == mcpdtest ) { FTNhep.jdahep[j][0] = jjj + 1 ; FTNhep.jdahep[j][1] = FTNhep.jdahep[j][0] + ndaugthers -1 ; break ; } } } } // now momentum, energy, and mass for(int k=0;k<3;k++) FTNhep.phep[j][k] = (double)mcp->getMomentum()[k] ; FTNhep.phep[j][3] = (double)mcp->getEnergy() ; FTNhep.phep[j][4] = (double)mcp->getMass() ; // get vertex and production time *kmax = 0 ; *maxxyz = 0. ; for(int k=0;k<3;k++){ FTNhep.vhep[j][k] = mcp->getVertex()[k] ; if ( fabs( FTNhep.vhep[j][k] ) > *maxxyz ){ *maxxyz = fabs( FTNhep.vhep[j][k] ) ; *kmax = k ; } } if ( mcpp != 0 && *maxxyz > 0. ) { FTNhep.vhep[j][3] = FTNhep.vhep[FTNhep.jmohep[j][0]-1][3] + (mcp->getVertex()[*kmax] - mcpp->getVertex()[*kmax]) * mcpp->getEnergy() / mcpp->getMomentum()[*kmax] ; } else { FTNhep.vhep[j][3] = 0. ; // no production time for MCParticle } // finally store pointer and get charge FTNhep1.mcpointerv[j] = reinterpret_cast<PTRTYPE>( (mcp) ) ; FTNhep1.mcchargev[j] = mcp->getCharge() ; } delete kmax ; delete maxxyz ; } // end of toHepEvt } //namespace HEPEVTIMPL <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include "fnord/io/fileutil.h" #include "fnord/ieee754.h" #include "fnord/human.h" #include <cstable/CSTableBuilder.h> #include <cstable/CSTableWriter.h> #include "cstable/BitPackedIntColumnWriter.h" #include "cstable/UInt32ColumnWriter.h" #include "cstable/UInt64ColumnWriter.h" #include "cstable/LEB128ColumnWriter.h" #include "cstable/StringColumnWriter.h" #include "cstable/DoubleColumnWriter.h" #include "cstable/BooleanColumnWriter.h" namespace fnord { namespace cstable { CSTableBuilder::CSTableBuilder( const msg::MessageSchema* schema) : schema_(schema), num_records_(0) { for (const auto& f : schema_->fields()) { createColumns("", 0, 0, f); } } void CSTableBuilder::createColumns( const String& prefix, uint32_t r_max, uint32_t d_max, const msg::MessageSchemaField& field) { auto colname = prefix + field.name; auto typesize = field.type_size; if (field.repeated) { ++r_max; } if (field.repeated || field.optional) { ++d_max; } switch (field.type) { case msg::FieldType::OBJECT: for (const auto& f : field.schema->fields()) { createColumns(colname + ".", r_max, d_max, f); } break; case msg::FieldType::UINT32: if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::BitPackedIntColumnWriter(r_max, d_max, typesize)); } else if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::LEB128ColumnWriter(r_max, d_max)); } else { columns_.emplace( colname, new cstable::UInt32ColumnWriter(r_max, d_max)); } break; case msg::FieldType::UINT64: if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::BitPackedIntColumnWriter(r_max, d_max, typesize)); } else if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::LEB128ColumnWriter(r_max, d_max)); } else { columns_.emplace( colname, new cstable::UInt64ColumnWriter(r_max, d_max)); } break; case msg::FieldType::DATETIME: columns_.emplace( colname, new cstable::LEB128ColumnWriter(r_max, d_max)); break; case msg::FieldType::DOUBLE: columns_.emplace( colname, new cstable::DoubleColumnWriter(r_max, d_max)); break; case msg::FieldType::STRING: columns_.emplace( colname, new cstable::StringColumnWriter(r_max, d_max, typesize)); break; case msg::FieldType::BOOLEAN: columns_.emplace( colname, new cstable::BooleanColumnWriter(r_max, d_max)); break; } } void CSTableBuilder::addRecord(const msg::MessageObject& msg) { for (const auto& f : schema_->fields()) { addRecordField(0, 0, 0, msg, "", f); } ++num_records_; } void CSTableBuilder::addRecordField( uint32_t r, uint32_t rmax, uint32_t d, const msg::MessageObject& msg, const String& column, const msg::MessageSchemaField& field) { auto this_r = r; auto next_r = r; auto next_d = d; if (field.repeated) { ++rmax; } if (field.optional || field.repeated) { ++next_d; } size_t n = 0; for (const auto& o : msg.asObject()) { if (o.id != field.id) { continue; } ++n; switch (field.type) { case msg::FieldType::OBJECT: for (const auto& f : field.schema->fields()) { addRecordField( next_r, rmax, next_d, o, column + field.name + ".", f); } break; default: writeField(next_r, next_d, o, column + field.name, field); break; } next_r = rmax; } if (n == 0) { if (!(field.optional || field.repeated)) { RAISEF(kIllegalArgumentError, "missing field: $0", column + field.name); } writeNull(r, d, column + field.name, field); return; } } void CSTableBuilder::writeNull( uint32_t r, uint32_t d, const String& column, const msg::MessageSchemaField& field) { switch (field.type) { case msg::FieldType::OBJECT: for (const auto& f : field.schema->fields()) { writeNull(r, d, column + "." + f.name, f); } break; default: auto col = columns_.find(column); col->second->addNull(r, d); break; } } void CSTableBuilder::writeField( uint32_t r, uint32_t d, const msg::MessageObject& msg, const String& column, const msg::MessageSchemaField& field) { auto col = columns_.find(column); switch (field.type) { case msg::FieldType::STRING: { auto& str = msg.asString(); col->second->addDatum(r, d, str.data(), str.size()); break; } case msg::FieldType::UINT32: { uint32_t val = msg.asUInt32(); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::DATETIME: case msg::FieldType::UINT64: { uint64_t val = msg.asUInt64(); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::DOUBLE: { uint64_t val = IEEE754::toBytes(msg.asDouble()); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::BOOLEAN: { uint8_t val = msg.asBool() ? 1 : 0; col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::OBJECT: RAISE(kIllegalStateError); } } void CSTableBuilder::addRecordsFromCSV(CSVInputStream* csv) { Vector<String> columns; csv->readNextRow(&columns); Set<String> missing_columns; for (const auto& col : columns_) { missing_columns.emplace(col.first); } Vector<RefPtr<ColumnWriter>> column_writers; for (const auto& col : columns) { if (columns_.count(col) == 0) { RAISEF(kRuntimeError, "column '$0' not found in schema", col); } missing_columns.erase(col); column_writers.emplace_back(columns_[col]); } Vector<RefPtr<ColumnWriter>> missing_column_writers; for (const auto& col : missing_columns) { auto writer = columns_[col]; if (writer->maxDefinitionLevel() == 0) { RAISEF(kRuntimeError, "missing required column: $0", col); } missing_column_writers.emplace_back(writer); } Vector<String> row; while (csv->readNextRow(&row)) { for (size_t i = 0; i < row.size() && i < columns.size(); ++i) { const auto& col = column_writers[i]; const auto& val = row[i]; if (Human::isNullOrEmpty(val)) { if (col->maxDefinitionLevel() == 0) { RAISEF( kRuntimeError, "missing value for required column: $0", columns[i]); } col->addNull(0, 0); continue; } switch (col->fieldType()) { case msg::FieldType::STRING: { col->addDatum(0, col->maxDefinitionLevel(), val.data(), val.size()); break; } case msg::FieldType::UINT32: { uint32_t v = std::stoull(val); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::DATETIME: case msg::FieldType::UINT64: { uint64_t v = std::stoull(val); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::DOUBLE: { double v = std::stod(val); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::BOOLEAN: { auto b = Human::parseBoolean(val); uint8_t v = !b.isEmpty() && b.get() ? 1 : 0; col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::OBJECT: RAISE(kIllegalStateError, "can't read OBJECTs from CSV"); } } for (auto& col : missing_column_writers) { col->addNull(0, 0); } ++num_records_; } } void CSTableBuilder::write(CSTableWriter* writer) { for (const auto& col : columns_) { writer->addColumn(col.first, col.second.get()); } } void CSTableBuilder::write(const String& filename) { cstable::CSTableWriter writer(filename + "~", num_records_); write(&writer); writer.commit(); FileUtil::mv(filename + "~", filename); } size_t CSTableBuilder::numRecords() const { return num_records_; } } // namespace cstable } // namespace fnord <commit_msg>handle FieldType::DATETIME in CSTableBuilder<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include "fnord/io/fileutil.h" #include "fnord/ieee754.h" #include "fnord/human.h" #include <cstable/CSTableBuilder.h> #include <cstable/CSTableWriter.h> #include "cstable/BitPackedIntColumnWriter.h" #include "cstable/UInt32ColumnWriter.h" #include "cstable/UInt64ColumnWriter.h" #include "cstable/LEB128ColumnWriter.h" #include "cstable/StringColumnWriter.h" #include "cstable/DoubleColumnWriter.h" #include "cstable/BooleanColumnWriter.h" namespace fnord { namespace cstable { CSTableBuilder::CSTableBuilder( const msg::MessageSchema* schema) : schema_(schema), num_records_(0) { for (const auto& f : schema_->fields()) { createColumns("", 0, 0, f); } } void CSTableBuilder::createColumns( const String& prefix, uint32_t r_max, uint32_t d_max, const msg::MessageSchemaField& field) { auto colname = prefix + field.name; auto typesize = field.type_size; if (field.repeated) { ++r_max; } if (field.repeated || field.optional) { ++d_max; } switch (field.type) { case msg::FieldType::OBJECT: for (const auto& f : field.schema->fields()) { createColumns(colname + ".", r_max, d_max, f); } break; case msg::FieldType::UINT32: if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::BitPackedIntColumnWriter(r_max, d_max, typesize)); } else if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::LEB128ColumnWriter(r_max, d_max)); } else { columns_.emplace( colname, new cstable::UInt32ColumnWriter(r_max, d_max)); } break; case msg::FieldType::UINT64: if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::BitPackedIntColumnWriter(r_max, d_max, typesize)); } else if (field.encoding == msg::EncodingHint::BITPACK) { columns_.emplace( colname, new cstable::LEB128ColumnWriter(r_max, d_max)); } else { columns_.emplace( colname, new cstable::UInt64ColumnWriter(r_max, d_max)); } break; case msg::FieldType::DATETIME: columns_.emplace( colname, new cstable::LEB128ColumnWriter(r_max, d_max)); break; case msg::FieldType::DOUBLE: columns_.emplace( colname, new cstable::DoubleColumnWriter(r_max, d_max)); break; case msg::FieldType::STRING: columns_.emplace( colname, new cstable::StringColumnWriter(r_max, d_max, typesize)); break; case msg::FieldType::BOOLEAN: columns_.emplace( colname, new cstable::BooleanColumnWriter(r_max, d_max)); break; } } void CSTableBuilder::addRecord(const msg::MessageObject& msg) { for (const auto& f : schema_->fields()) { addRecordField(0, 0, 0, msg, "", f); } ++num_records_; } void CSTableBuilder::addRecordField( uint32_t r, uint32_t rmax, uint32_t d, const msg::MessageObject& msg, const String& column, const msg::MessageSchemaField& field) { auto next_r = r; auto next_d = d; if (field.repeated) { ++rmax; } if (field.optional || field.repeated) { ++next_d; } size_t n = 0; for (const auto& o : msg.asObject()) { if (o.id != field.id) { continue; } ++n; switch (field.type) { case msg::FieldType::OBJECT: for (const auto& f : field.schema->fields()) { addRecordField( next_r, rmax, next_d, o, column + field.name + ".", f); } break; default: writeField(next_r, next_d, o, column + field.name, field); break; } next_r = rmax; } if (n == 0) { if (!(field.optional || field.repeated)) { RAISEF(kIllegalArgumentError, "missing field: $0", column + field.name); } writeNull(r, d, column + field.name, field); return; } } void CSTableBuilder::writeNull( uint32_t r, uint32_t d, const String& column, const msg::MessageSchemaField& field) { switch (field.type) { case msg::FieldType::OBJECT: for (const auto& f : field.schema->fields()) { writeNull(r, d, column + "." + f.name, f); } break; default: auto col = columns_.find(column); col->second->addNull(r, d); break; } } void CSTableBuilder::writeField( uint32_t r, uint32_t d, const msg::MessageObject& msg, const String& column, const msg::MessageSchemaField& field) { auto col = columns_.find(column); switch (field.type) { case msg::FieldType::STRING: { auto& str = msg.asString(); col->second->addDatum(r, d, str.data(), str.size()); break; } case msg::FieldType::UINT32: { uint32_t val = msg.asUInt32(); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::DATETIME: { uint64_t val = msg.asUInt64(); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::UINT64: { uint64_t val = msg.asUInt64(); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::DOUBLE: { uint64_t val = IEEE754::toBytes(msg.asDouble()); col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::BOOLEAN: { uint8_t val = msg.asBool() ? 1 : 0; col->second->addDatum(r, d, &val, sizeof(val)); break; } case msg::FieldType::OBJECT: RAISE(kIllegalStateError); } } void CSTableBuilder::addRecordsFromCSV(CSVInputStream* csv) { Vector<String> columns; csv->readNextRow(&columns); Set<String> missing_columns; for (const auto& col : columns_) { missing_columns.emplace(col.first); } Vector<RefPtr<ColumnWriter>> column_writers; Vector<msg::FieldType> field_types; for (const auto& col : columns) { if (columns_.count(col) == 0) { RAISEF(kRuntimeError, "column '$0' not found in schema", col); } missing_columns.erase(col); column_writers.emplace_back(columns_[col]); field_types.emplace_back(schema_->fieldType(schema_->fieldId(col))); } Vector<RefPtr<ColumnWriter>> missing_column_writers; for (const auto& col : missing_columns) { auto writer = columns_[col]; if (writer->maxDefinitionLevel() == 0) { RAISEF(kRuntimeError, "missing required column: $0", col); } missing_column_writers.emplace_back(writer); } Vector<String> row; while (csv->readNextRow(&row)) { for (size_t i = 0; i < row.size() && i < columns.size(); ++i) { const auto& col = column_writers[i]; const auto& val = row[i]; if (Human::isNullOrEmpty(val)) { if (col->maxDefinitionLevel() == 0) { RAISEF( kRuntimeError, "missing value for required column: $0", columns[i]); } col->addNull(0, 0); continue; } switch (field_types[i]) { case msg::FieldType::STRING: { col->addDatum(0, col->maxDefinitionLevel(), val.data(), val.size()); break; } case msg::FieldType::UINT32: { uint32_t v = std::stoull(val); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::DATETIME: { auto t = Human::parseTime(val); if (t.isEmpty()) { RAISEF(kTypeError, "can't convert '$0' to DATETIME", val); } uint64_t v = t.get().unixMicros(); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::UINT64: { uint64_t v = std::stoull(val); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::DOUBLE: { double v = std::stod(val); col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::BOOLEAN: { auto b = Human::parseBoolean(val); uint8_t v = !b.isEmpty() && b.get() ? 1 : 0; col->addDatum(0, col->maxDefinitionLevel(), &v, sizeof(v)); break; } case msg::FieldType::OBJECT: RAISE(kIllegalStateError, "can't read OBJECTs from CSV"); } } for (auto& col : missing_column_writers) { col->addNull(0, 0); } ++num_records_; } } void CSTableBuilder::write(CSTableWriter* writer) { for (const auto& col : columns_) { writer->addColumn(col.first, col.second.get()); } } void CSTableBuilder::write(const String& filename) { cstable::CSTableWriter writer(filename + "~", num_records_); write(&writer); writer.commit(); FileUtil::mv(filename + "~", filename); } size_t CSTableBuilder::numRecords() const { return num_records_; } } // namespace cstable } // namespace fnord <|endoftext|>
<commit_before>#include <algorithm> #include <boost/filesystem.hpp> #include <QMessageBox> #include <QFileDialog> #include <QSqlTableModel> #include <QProgressDialog> #include "image_annotation.h" #include "database_info.h" #include "mainwindow.h" #include "ui_mainwindow.h" namespace fish_annotator { namespace db_uploader { namespace fs = boost::filesystem; namespace { //anonymous static const std::vector<std::string> kDirExtensions = { ".jpg", ".png", ".bmp", ".tif", ".jpeg", ".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"}; } // anonymous namespace MainWindow::MainWindow(QWidget *parent) : ui_(new Ui::MainWindow) , output_db_(new QSqlDatabase()) { ui_->setupUi(this); setWindowTitle("Database Uploader"); #ifdef _WIN32 setWindowIcon(QIcon(":/icons/cvision/cvision_no_text.ico")); #endif fs::path current_path(QDir::currentPath().toStdString()); fs::path default_output = current_path / fs::path("default.output_database"); if(fs::exists(default_output)) { DatabaseInfo output; deserialize(output, default_output.string()); ui_->outputServer->setText(output.getServer().c_str()); ui_->outputDatabase->setText(output.getDatabase().c_str()); ui_->outputUsername->setText(output.getUsername().c_str()); } } void MainWindow::on_connectOutputDb_clicked() { ui_->outputDbStatus->setText("Attempting to connect..."); ui_->outputDbStatus->repaint(); *output_db_ = QSqlDatabase::addDatabase("QODBC3", "output"); if(output_db_->isDriverAvailable("QODBC") == false) { QMessageBox err; err.critical(0, "Error", "ODBC driver is not available!"); } output_db_->setDatabaseName( "DRIVER={SQL Server};SERVER={" + ui_->outputServer->text() + "};DATABASE=" + ui_->outputDatabase->text() + ";Trusted_Connection=no;user_id=" + ui_->outputUsername->text() + ";password=" + ui_->outputPassword->text() + ";WSID=."); output_db_->setUserName(ui_->outputUsername->text()); output_db_->setPassword(ui_->outputPassword->text()); if(output_db_->isValid() == false) { ui_->outputDbStatus->setText("Not connected"); QMessageBox err; err.critical(0, "Error", "Not a valid database!"); } if(output_db_->open() == false) { ui_->outputDbStatus->setText("Not connected"); QMessageBox err; err.critical(0, "Error", output_db_->lastError().text()); } else { ui_->outputDbStatus->setText("Connected"); } if(output_db_->isOpen() == true) { ui_->upload->setEnabled(true); } } void MainWindow::on_browseImageDir_clicked() { ui_->imageDirectory->setText(QFileDialog::getExistingDirectory( this, "Select annotated image directory")); } void MainWindow::on_cancel_clicked() { QApplication::quit(); } void MainWindow::on_upload_clicked() { QString image_dir = ui_->imageDirectory->text(); std::vector<boost::filesystem::path> image_files; fs::directory_iterator dir_it(image_dir.toStdString()); fs::directory_iterator dir_end; for(; dir_it != dir_end; ++dir_it) { fs::path ext(dir_it->path().extension()); for(auto &ok_ext : kDirExtensions) { if(ext == ok_ext) { image_files.push_back(dir_it->path()); } } } std::sort(image_files.begin(), image_files.end()); image_annotator::ImageAnnotationList annotations; annotations.read(image_files); int num_img = static_cast<int>(image_files.size()); QSqlTableModel output_model(this, *output_db_); output_db_->exec("SET IDENTITY_INSERT dbo.STAGING_MEASUREMENTS ON"); if(output_db_->lastError().isValid()) { QMessageBox err; err.critical(0, "Error", "Unable to enable IDENTITY_INSERT."); return; } output_model.setTable("dbo.STAGING_MEASUREMENTS"); output_model.setEditStrategy(QSqlTableModel::OnManualSubmit); output_model.select(); QProgressDialog progress( "Uploading annotations...", "Abort", 0, num_img, this, Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint); progress.setCancelButton(0); progress.setWindowTitle("Uploading Annotations"); progress.setMinimumDuration(10); for(int img_index = 0; img_index < num_img; ++img_index) { progress.setValue(img_index); if(progress.wasCanceled()) { break; } auto ann = annotations.getImageAnnotations(image_files[img_index]); int num_ann = static_cast<int>(ann.size()); for(int ai = 0; ai < num_ann; ++ai) { auto row_count = output_model.rowCount(); if(output_model.insertRows(row_count, 1) == false) { progress.close(); QMessageBox err; err.critical(0, "Error", "Unable to insert row into table."); break; } // measurementPK output_model.setData(output_model.index(row_count, 0), 0); // measurementControlPK output_model.setData(output_model.index(row_count, 1), 0); // updatedPK output_model.setData(output_model.index(row_count, 2), 0); // dfo output_model.setData(output_model.index(row_count, 3), 0); // measurement double meas = 0.0; if(ann[ai]->type_ == kLine) { double xdiff = ann[ai]->area_.x - ann[ai]->area_.w; double ydiff = ann[ai]->area_.y - ann[ai]->area_.h; meas = std::sqrt(xdiff * xdiff + ydiff * ydiff); } output_model.setData(output_model.index(row_count, 4), meas); // areacontrolpk output_model.setData(output_model.index(row_count, 5), 0); // station output_model.setData(output_model.index(row_count, 6), "---"); // quadrat output_model.setData(output_model.index(row_count, 7), 0); // cameracontrolpk output_model.setData(output_model.index(row_count, 8), 0); // area output_model.setData(output_model.index(row_count, 9), ""); // year output_model.setData(output_model.index(row_count, 10), "2017"); } if(output_model.submitAll() == true) { output_model.database().commit(); } else { output_model.database().rollback(); progress.close(); QMessageBox err; err.critical(0, "Error", output_model.lastError().text()); break; } } progress.setValue(num_img); QMessageBox status; status.information(0, "Success", "Database upload succeeded!"); output_db_->exec("SET IDENTITY_INSERT dbo.STAGING_MEASUREMENTS OFF"); if(output_db_->lastError().isValid()) { QMessageBox err; err.warning(0, "Warning", "Unable to disable IDENTITY_INSERT."); return; } } #include "moc_mainwindow.cpp" }} // namespace fish_annotator::db_uploader <commit_msg>Add metadata parsing from path and filename<commit_after>#include <algorithm> #include <boost/filesystem.hpp> #include <QMessageBox> #include <QFileDialog> #include <QSqlTableModel> #include <QProgressDialog> #include "image_annotation.h" #include "database_info.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include <fstream> std::ofstream debug("DEBUG.txt"); namespace fish_annotator { namespace db_uploader { namespace fs = boost::filesystem; namespace { //anonymous static const std::vector<std::string> kDirExtensions = { ".jpg", ".png", ".bmp", ".tif", ".jpeg", ".JPG", ".PNG", ".BMP", ".TIF", ".JPEG"}; } // anonymous namespace MainWindow::MainWindow(QWidget *parent) : ui_(new Ui::MainWindow) , output_db_(new QSqlDatabase()) { ui_->setupUi(this); setWindowTitle("Database Uploader"); #ifdef _WIN32 setWindowIcon(QIcon(":/icons/cvision/cvision_no_text.ico")); #endif fs::path current_path(QDir::currentPath().toStdString()); fs::path default_output = current_path / fs::path("default.output_database"); if(fs::exists(default_output)) { DatabaseInfo output; deserialize(output, default_output.string()); ui_->outputServer->setText(output.getServer().c_str()); ui_->outputDatabase->setText(output.getDatabase().c_str()); ui_->outputUsername->setText(output.getUsername().c_str()); } } void MainWindow::on_connectOutputDb_clicked() { ui_->outputDbStatus->setText("Attempting to connect..."); ui_->outputDbStatus->repaint(); *output_db_ = QSqlDatabase::addDatabase("QODBC3", "output"); if(output_db_->isDriverAvailable("QODBC") == false) { QMessageBox err; err.critical(0, "Error", "ODBC driver is not available!"); } output_db_->setDatabaseName( "DRIVER={SQL Server};SERVER={" + ui_->outputServer->text() + "};DATABASE=" + ui_->outputDatabase->text() + ";Trusted_Connection=no;user_id=" + ui_->outputUsername->text() + ";password=" + ui_->outputPassword->text() + ";WSID=."); //@TODO UNCOMMENT THESE FOR CUSTOMER //output_db_->setUserName(ui_->outputUsername->text()); //output_db_->setPassword(ui_->outputPassword->text()); if(output_db_->isValid() == false) { ui_->outputDbStatus->setText("Not connected"); QMessageBox err; err.critical(0, "Error", "Not a valid database!"); } if(output_db_->open() == false) { ui_->outputDbStatus->setText("Not connected"); QMessageBox err; err.critical(0, "Error", output_db_->lastError().text()); } else { ui_->outputDbStatus->setText("Connected"); } if(output_db_->isOpen() == true) { ui_->upload->setEnabled(true); } } void MainWindow::on_browseImageDir_clicked() { ui_->imageDirectory->setText(QFileDialog::getExistingDirectory( this, "Select annotated image directory")); } void MainWindow::on_cancel_clicked() { QApplication::quit(); } void MainWindow::on_upload_clicked() { QString image_dir = ui_->imageDirectory->text(); std::vector<boost::filesystem::path> image_files; fs::recursive_directory_iterator dir_it(image_dir.toStdString()); fs::recursive_directory_iterator dir_end; for(; dir_it != dir_end; ++dir_it) { fs::path ext(dir_it->path().extension()); for(auto &ok_ext : kDirExtensions) { if(ext == ok_ext) { image_files.push_back(dir_it->path()); } } } std::sort(image_files.begin(), image_files.end()); image_annotator::ImageAnnotationList annotations; annotations.read(image_files); int num_img = static_cast<int>(image_files.size()); QSqlTableModel output_model(this, *output_db_); output_db_->exec("SET IDENTITY_INSERT dbo.STAGING_MEASUREMENTS ON"); if(output_db_->lastError().isValid()) { QMessageBox err; err.critical(0, "Error", "Unable to enable IDENTITY_INSERT."); return; } output_model.setTable("dbo.STAGING_MEASUREMENTS"); output_model.setEditStrategy(QSqlTableModel::OnManualSubmit); output_model.select(); QProgressDialog progress( "Uploading annotations...", "Abort", 0, num_img, this, Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint); progress.setCancelButton(0); progress.setWindowTitle("Uploading Annotations"); progress.setMinimumDuration(10); bool ok = true; for(int img_index = 0; img_index < num_img; ++img_index) { debug << "IMAGE FILE: " << image_files[img_index] << std::endl; // Parse metadata from directory structure std::vector<std::string> dir_parts; for(const auto &sub : image_files[img_index]) { dir_parts.push_back(sub.string()); } auto dir_len = dir_parts.size(); if(dir_len < 6) { QMessageBox err; err.critical(0, "Error", std::string( std::string("Invalid directory structure for image ") + image_files[img_index].string() + std::string("! Aborting...")).c_str()); ok = false; break; } std::string filename = dir_parts[dir_len - 1]; std::string camera_control_camera_name = dir_parts[dir_len - 3]; std::string area_control_short_name = dir_parts[dir_len - 4]; std::string area_control_long_name = dir_parts[dir_len - 5]; std::string area_control_year = dir_parts[dir_len - 6]; debug << "CAMERA NAME: " << camera_control_camera_name << std::endl; debug << "SHORT NAME: " << area_control_short_name << std::endl; debug << "LONG NAME: " << area_control_long_name << std::endl; debug << "YEAR: " << area_control_year << std::endl; // Parse metadata from filename std::vector<std::string> file_parts; std::string file_part; std::istringstream file_stream(filename.c_str()); while(std::getline(file_stream, file_part, '_')) { file_parts.push_back(file_part); } auto file_len = file_parts.size(); if(file_len < 5) { QMessageBox err; err.critical(0, "Error", std::string( std::string("Invalid filename for image ") + image_files[img_index].string() + std::string("! Aborting...")).c_str()); ok = false; break; } std::string area_control_station = file_parts[0].substr(0, 3); std::string area_control_quadrat_str = file_parts[1]; int area_control_quadrat = 0; if(1 != sscanf_s( area_control_station.c_str(), "%dQ", &area_control_quadrat)) { QMessageBox err; err.critical(0, "Error", std::string( std::string("Could not parse quadrat from filename for image ") + image_files[img_index].string() + std::string("! Aborting...")).c_str()); ok = false; break; } debug << "STATION: " << area_control_station << std::endl; debug << "QUADRAT: " << area_control_quadrat << std::endl; progress.setValue(img_index); if(progress.wasCanceled()) { ok = false; break; } auto ann = annotations.getImageAnnotations(image_files[img_index]); int num_ann = static_cast<int>(ann.size()); for(int ai = 0; ai < num_ann; ++ai) { auto row_count = output_model.rowCount(); if(output_model.insertRows(row_count, 1) == false) { QMessageBox err; err.critical(0, "Error", "Unable to insert row into table."); ok = false; break; } // measurementPK output_model.setData(output_model.index(row_count, 0), 0); // measurementControlPK output_model.setData(output_model.index(row_count, 1), 0); // updatedPK output_model.setData(output_model.index(row_count, 2), 0); // dfo output_model.setData(output_model.index(row_count, 3), 0); // measurement double meas = 0.0; if(ann[ai]->type_ == kLine) { double xdiff = ann[ai]->area_.x - ann[ai]->area_.w; double ydiff = ann[ai]->area_.y - ann[ai]->area_.h; meas = std::sqrt(xdiff * xdiff + ydiff * ydiff); } output_model.setData(output_model.index(row_count, 4), meas); // areacontrolpk output_model.setData(output_model.index(row_count, 5), 0); // station output_model.setData(output_model.index(row_count, 6), "---"); // quadrat output_model.setData(output_model.index(row_count, 7), 0); // cameracontrolpk output_model.setData(output_model.index(row_count, 8), 0); // area output_model.setData(output_model.index(row_count, 9), ""); // year output_model.setData(output_model.index(row_count, 10), "2017"); } if(ok == false) { break; } } if(ok == true) { ok = output_model.submitAll(); } if(ok == true) { output_model.database().commit(); progress.setValue(num_img); QMessageBox status; status.information(0, "Success", "Database upload succeeded!"); } else { output_model.database().rollback(); progress.close(); if(output_db_->lastError().isValid()) { QMessageBox err; err.critical(0, "Error", output_model.lastError().text()); } } output_db_->exec("SET IDENTITY_INSERT dbo.STAGING_MEASUREMENTS OFF"); if(output_db_->lastError().isValid()) { QMessageBox err; err.warning(0, "Warning", "Unable to disable IDENTITY_INSERT."); return; } } #include "moc_mainwindow.cpp" }} // namespace fish_annotator::db_uploader <|endoftext|>
<commit_before>#include "dynamic_selection_list.hh" namespace Kakoune { DynamicSelectionList::DynamicSelectionList(const Buffer& buffer, SelectionList selections) : m_buffer(&buffer), SelectionList(std::move(selections)) { m_buffer->change_listeners().insert(this); check_invariant(); } DynamicSelectionList::~DynamicSelectionList() { m_buffer->change_listeners().erase(this); } DynamicSelectionList::DynamicSelectionList(const DynamicSelectionList& other) : SelectionList(other), m_buffer(other.m_buffer) { m_buffer->change_listeners().insert(this); } DynamicSelectionList& DynamicSelectionList::operator=(const DynamicSelectionList& other) { SelectionList::operator=((const SelectionList&)other); if (m_buffer != other.m_buffer) { m_buffer->change_listeners().erase(this); m_buffer = other.m_buffer; m_buffer->change_listeners().insert(this); } check_invariant(); return *this; } DynamicSelectionList::DynamicSelectionList(DynamicSelectionList&& other) : SelectionList(std::move(other)), m_buffer(other.m_buffer) { m_buffer->change_listeners().insert(this); } DynamicSelectionList& DynamicSelectionList::operator=(DynamicSelectionList&& other) { SelectionList::operator=(std::move(other)); if (m_buffer != other.m_buffer) { m_buffer->change_listeners().erase(this); m_buffer = other.m_buffer; m_buffer->change_listeners().insert(this); } check_invariant(); return *this; } DynamicSelectionList& DynamicSelectionList::operator=(SelectionList selections) { SelectionList::operator=(std::move(selections)); check_invariant(); return *this; } void DynamicSelectionList::check_invariant() const { #ifdef KAK_DEBUG for (auto& sel : *this) { assert(m_buffer == &sel.buffer()); sel.check_invariant(); } #endif } static void update_insert(BufferIterator& it, const BufferCoord& begin, const BufferCoord& end) { BufferCoord coord = it.coord(); if (coord < begin) return; if (begin.line == coord.line) coord.column = end.column + coord.column - begin.column; coord.line += end.line - begin.line; it = coord; } static void update_erase(BufferIterator& it, const BufferCoord& begin, const BufferCoord& end) { BufferCoord coord = it.coord(); if (coord < begin) return; if (coord <= end) coord = it.buffer().clamp(begin); else { if (end.line == coord.line) { coord.line = begin.line; coord.column = begin.column + coord.column - end.column; } else coord.line -= end.line - begin.line; } it = coord; } void DynamicSelectionList::on_insert(const BufferIterator& begin, const BufferIterator& end) { const BufferCoord begin_coord{begin.coord()}; const BufferCoord end_coord{end.coord()}; for (auto& sel : *this) { update_insert(sel.first(), begin_coord, end_coord); update_insert(sel.last(), begin_coord, end_coord); } } void DynamicSelectionList::on_erase(const BufferIterator& begin, const BufferIterator& end) { const BufferCoord begin_coord{begin.coord()}; const BufferCoord end_coord{end.coord()}; for (auto& sel : *this) { update_erase(sel.first(), begin_coord, end_coord); update_erase(sel.last(), begin_coord, end_coord); } } } <commit_msg>DynamicSelectionList: optimize updating on buffer modification<commit_after>#include "dynamic_selection_list.hh" namespace Kakoune { DynamicSelectionList::DynamicSelectionList(const Buffer& buffer, SelectionList selections) : m_buffer(&buffer), SelectionList(std::move(selections)) { m_buffer->change_listeners().insert(this); check_invariant(); } DynamicSelectionList::~DynamicSelectionList() { m_buffer->change_listeners().erase(this); } DynamicSelectionList::DynamicSelectionList(const DynamicSelectionList& other) : SelectionList(other), m_buffer(other.m_buffer) { m_buffer->change_listeners().insert(this); } DynamicSelectionList& DynamicSelectionList::operator=(const DynamicSelectionList& other) { SelectionList::operator=((const SelectionList&)other); if (m_buffer != other.m_buffer) { m_buffer->change_listeners().erase(this); m_buffer = other.m_buffer; m_buffer->change_listeners().insert(this); } check_invariant(); return *this; } DynamicSelectionList::DynamicSelectionList(DynamicSelectionList&& other) : SelectionList(std::move(other)), m_buffer(other.m_buffer) { m_buffer->change_listeners().insert(this); } DynamicSelectionList& DynamicSelectionList::operator=(DynamicSelectionList&& other) { SelectionList::operator=(std::move(other)); if (m_buffer != other.m_buffer) { m_buffer->change_listeners().erase(this); m_buffer = other.m_buffer; m_buffer->change_listeners().insert(this); } check_invariant(); return *this; } DynamicSelectionList& DynamicSelectionList::operator=(SelectionList selections) { SelectionList::operator=(std::move(selections)); check_invariant(); return *this; } void DynamicSelectionList::check_invariant() const { #ifdef KAK_DEBUG for (auto& sel : *this) { assert(m_buffer == &sel.buffer()); sel.check_invariant(); } #endif } namespace { template<template <bool, bool> class UpdateFunc> void on_buffer_change(SelectionList& sels, const BufferCoord& begin, const BufferCoord& end, LineCount end_line) { auto update_beg = std::lower_bound(sels.begin(), sels.end(), begin, [](const Selection& s, const BufferCoord& c) { return std::max(s.first(), s.last()).coord() < c; }); auto update_only_line_beg = std::upper_bound(sels.begin(), sels.end(), end_line, [](LineCount l, const Selection& s) { return l < std::min(s.first(), s.last()).line(); }); if (update_beg != update_only_line_beg) { // for the first one, we are not sure if min < begin UpdateFunc<false, false>{}(update_beg->first(), begin, end); UpdateFunc<false, false>{}(update_beg->last(), begin, end); } for (auto it = update_beg+1; it < update_only_line_beg; ++it) { UpdateFunc<false, true>{}(it->first(), begin, end); UpdateFunc<false, true>{}(it->last(), begin, end); } if (end.line > begin.line) { for (auto it = update_only_line_beg; it != sels.end(); ++it) { UpdateFunc<true, true>{}(it->first(), begin, end); UpdateFunc<true, true>{}(it->last(), begin, end); } } } template<bool assume_different_line, bool assume_greater_than_begin> struct UpdateInsert { void operator()(BufferIterator& it, const BufferCoord& begin, const BufferCoord& end) const { BufferCoord coord = it.coord(); if (assume_different_line) assert(begin.line < coord.line); if (not assume_greater_than_begin and coord < begin) return; if (not assume_different_line and begin.line == coord.line) coord.column = end.column + coord.column - begin.column; coord.line += end.line - begin.line; it = coord; } }; template<bool assume_different_line, bool assume_greater_than_begin> struct UpdateErase { void operator()(BufferIterator& it, const BufferCoord& begin, const BufferCoord& end) const { BufferCoord coord = it.coord(); if (not assume_greater_than_begin and coord < begin) return; if (assume_different_line) assert(end.line < coord.line); if (not assume_different_line and coord <= end) coord = it.buffer().clamp(begin); else { if (not assume_different_line and end.line == coord.line) { coord.line = begin.line; coord.column = begin.column + coord.column - end.column; } else coord.line -= end.line - begin.line; } it = coord; } }; } void DynamicSelectionList::on_insert(const BufferIterator& begin, const BufferIterator& end) { on_buffer_change<UpdateInsert>(*this, begin.coord(), end.coord(), begin.line()); } void DynamicSelectionList::on_erase(const BufferIterator& begin, const BufferIterator& end) { on_buffer_change<UpdateErase>(*this, begin.coord(), end.coord(), end.line()); } } <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. //------------------------------------------------------------------------------------------------- // This file is based on Kevin Beason's smallpt global illumination renderer. // Original license (MIT) follows. // /* LICENSE Copyright (c) 2006-2008 Kevin Beason (kevin.beason@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <exception> #include <iostream> #include <ostream> #include <thread> #include <GL/glew.h> #ifdef __CUDACC__ #include <thrust/device_vector.h> #endif #include <Support/CmdLine.h> #include <Support/CmdLineUtil.h> #include <visionaray/math/sphere.h> #include <visionaray/cpu_buffer_rt.h> #include <visionaray/generic_material.h> #include <visionaray/kernels.h> #include <visionaray/material.h> #include <visionaray/scheduler.h> #ifdef __CUDACC__ #include <visionaray/pixel_unpack_buffer_rt.h> #endif #include <common/make_materials.h> #include <common/viewer_glut.h> #ifdef __CUDACC__ #include <common/cuda.h> #endif using namespace visionaray; using viewer_type = viewer_glut; //------------------------------------------------------------------------------------------------- // Visionaray camera generating primary rays similar to how smallpt does // struct smallpt_camera { VSNRAY_FUNC void begin_frame() {} VSNRAY_FUNC void end_frame() {} template <typename R, typename T> VSNRAY_FUNC inline R primary_ray(R /* */, T const& x, T const& y, T const& width, T const& height) const { using V = vector<3, T>; V eye(50.0, 52.0, 295.6); V dir = normalize(V(0.0, -0.042612, -1.0)); V cx(width * 0.5135 / height, 0.0, 0.0); V cy = normalize(cross(cx, dir)) * T(0.5135); V d = cx * ((x - width / 2.0) / width) + cy * ((y - height / 2.0) / height) + dir; return R(eye + d * 140.0, normalize(d)); } }; //------------------------------------------------------------------------------------------------- // Renderer // struct renderer : viewer_type { using host_ray_type = basic_ray<double>; using device_ray_type = basic_ray<double>; using material_type = generic_material<emissive<double>, glass<double>, matte<double>, mirror<double>>; enum device_type { CPU = 0, GPU }; struct empty_light_type {}; renderer() : viewer_type(512, 512, "Visionaray Smallpt Example") , host_sched(std::thread::hardware_concurrency()) #ifdef __CUDACC__ , device_sched(8, 8) #endif { #ifdef __CUDACC__ using namespace support; add_cmdline_option( cl::makeOption<device_type&>({ { "cpu", CPU, "Rendering on the CPU" }, { "gpu", GPU, "Rendering on the GPU" }, }, "device", cl::Desc("Rendering device"), cl::ArgRequired, cl::init(this->dev_type) ) ); #endif } void init_scene() { // Left spheres.push_back(make_sphere(vec3d(1e5 + 1.0, 40.8, 81.6), 1e5)); materials.push_back(make_matte(vec3d(0.75, 0.25, 0.25))); // Right spheres.push_back(make_sphere(vec3d(-1e5 + 99.0, 40.8, 81.6), 1e5)); materials.push_back(make_matte(vec3d(0.25, 0.25, 0.75))); // Back spheres.push_back(make_sphere(vec3d(50.0, 40.8, 1e5), 1e5)); materials.push_back(make_matte(vec3d(0.75, 0.75, 0.75))); // Front spheres.push_back(make_sphere(vec3d(50.0, 40.8, -1e5 + 170), 1e5)); materials.push_back(make_matte(vec3d(0.0))); // Bottom spheres.push_back(make_sphere(vec3d(50.0, 1e5, 81.6), 1e5)); materials.push_back(make_matte(vec3d(0.75, 0.75, 0.75))); // Top spheres.push_back(make_sphere(vec3d(50.0, -1e5 + 81.6, 81.6), 1e5)); materials.push_back(make_matte(vec3d(0.75, 0.75, 0.75))); // Mirror spheres.push_back(make_sphere(vec3d(27.0, 16.5, 47.0), 16.5)); materials.push_back(make_mirror(vec3d(0.999))); // Glass spheres.push_back(make_sphere(vec3d(73.0, 16.5, 78.0), 16.5)); materials.push_back(make_glass(vec3d(0.999))); // Light spheres.push_back(make_sphere(vec3d(50.0, 681.6 - 0.27, 81.6), 600.0)); materials.push_back(make_emissive(vec3d(12.0, 12.0, 12.0))); #ifdef __CUDACC__ // Copy to GPU device_spheres = spheres; device_materials = materials; #endif } smallpt_camera cam; cpu_buffer_rt<PF_RGBA32F, PF_UNSPECIFIED> host_rt; tiled_sched<host_ray_type> host_sched; aligned_vector<basic_sphere<double>> spheres; aligned_vector<material_type> materials; #ifdef __CUDACC__ pixel_unpack_buffer_rt<PF_RGBA32F, PF_UNSPECIFIED> device_rt; cuda_sched<device_ray_type> device_sched; thrust::device_vector<basic_sphere<double>> device_spheres; thrust::device_vector<material_type> device_materials; #endif unsigned frame_num = 0; device_type dev_type = CPU; protected: void on_display(); void on_resize(int w, int h); private: basic_sphere<double> make_sphere(vec3d center, double radius) { static int sphere_id = 0; basic_sphere<double> sphere(center, radius); sphere.prim_id = sphere_id; sphere.geom_id = sphere_id; ++sphere_id; return sphere; } emissive<double> make_emissive(vec3d ce) { emissive<double> mat; mat.ce() = from_rgb(ce); mat.ls() = 1.0; return mat; } glass<double> make_glass(vec3d ct) { glass<double> mat; mat.ct() = from_rgb(ct); mat.kt() = 1.0; mat.cr() = from_rgb(ct); mat.kr() = 1.0; mat.ior() = spectrum<double>(1.5); return mat; } matte<double> make_matte(vec3d cd) { matte<double> mat; mat.cd() = from_rgb(cd); mat.kd() = 1.0; return mat; } mirror<double> make_mirror(vec3d cr) { mirror<double> mat; mat.cr() = from_rgb(cr); mat.kr() = 0.9; mat.ior() = spectrum<double>(0.0); mat.absorption() = spectrum<double>(0.0); return mat; } }; //------------------------------------------------------------------------------------------------- // Display function // void renderer::on_display() { // Enable gamma correction with OpenGL. glEnable(GL_FRAMEBUFFER_SRGB); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // make_kernel_params needs (!) lights // TODO: fix this in visionaray API! empty_light_type* ignore = 0; if (dev_type == GPU) { #ifdef __CUDACC__ auto sparams = make_sched_params( pixel_sampler::jittered_blend_type{}, cam, device_rt ); auto kparams = make_kernel_params( thrust::raw_pointer_cast(device_spheres.data()), thrust::raw_pointer_cast(device_spheres.data()) + device_spheres.size(), thrust::raw_pointer_cast(device_materials.data()), ignore, ignore, 10, 1e-4f, // epsilon vec4(background_color(), 1.0f), vec4(0.0f) ); pathtracing::kernel<decltype(kparams)> kernel; kernel.params = kparams; device_sched.frame(kernel, sparams, ++frame_num); device_rt.display_color_buffer(); #endif } else if (dev_type == CPU) { #ifndef __CUDA_ARCH__ auto sparams = make_sched_params( pixel_sampler::jittered_blend_type{}, cam, host_rt ); auto kparams = make_kernel_params( spheres.data(), spheres.data() + spheres.size(), materials.data(), ignore, ignore, 10, 1e-4f, // epsilon vec4(background_color(), 1.0f), vec4(0.0f) ); pathtracing::kernel<decltype(kparams)> kernel; kernel.params = kparams; host_sched.frame(kernel, sparams, ++frame_num); host_rt.display_color_buffer(); #endif } std::cout << "Num samples: " << frame_num << '\r'; std::cout << std::flush; } //------------------------------------------------------------------------------------------------- // resize event // void renderer::on_resize(int w, int h) { frame_num = 0; host_rt.resize(w, h); host_rt.clear_color_buffer(); #ifdef __CUDACC__ device_rt.resize(w, h); device_rt.clear_color_buffer(); #endif viewer_type::on_resize(w, h); } //------------------------------------------------------------------------------------------------- // Main function, performs initialization // int main(int argc, char** argv) { #ifdef __CUDACC__ if (cuda::init_gl_interop() != cudaSuccess) { std::cerr << "Cannot initialize CUDA OpenGL interop\n"; return EXIT_FAILURE; } #endif renderer rend; try { rend.init(argc, argv); } catch (std::exception const& e) { std::cerr << e.what() << '\n'; return EXIT_FAILURE; } rend.init_scene(); rend.event_loop(); } <commit_msg>Option to compile smallpt ex with single precision<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. //------------------------------------------------------------------------------------------------- // This file is based on Kevin Beason's smallpt global illumination renderer. // Original license (MIT) follows. // /* LICENSE Copyright (c) 2006-2008 Kevin Beason (kevin.beason@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <exception> #include <iostream> #include <ostream> #include <thread> #include <GL/glew.h> #ifdef __CUDACC__ #include <thrust/device_vector.h> #endif #include <Support/CmdLine.h> #include <Support/CmdLineUtil.h> #include <visionaray/math/sphere.h> #include <visionaray/cpu_buffer_rt.h> #include <visionaray/generic_material.h> #include <visionaray/kernels.h> #include <visionaray/material.h> #include <visionaray/scheduler.h> #ifdef __CUDACC__ #include <visionaray/pixel_unpack_buffer_rt.h> #endif #include <common/make_materials.h> #include <common/viewer_glut.h> #ifdef __CUDACC__ #include <common/cuda.h> #endif using namespace visionaray; using viewer_type = viewer_glut; //------------------------------------------------------------------------------------------------- // Switch between single and double precision implementation // #define USE_DOUBLE_PRECISION 1 //------------------------------------------------------------------------------------------------- // Visionaray camera generating primary rays similar to how smallpt does // struct smallpt_camera { VSNRAY_FUNC void begin_frame() {} VSNRAY_FUNC void end_frame() {} template <typename R, typename T> VSNRAY_FUNC inline R primary_ray(R /* */, T const& x, T const& y, T const& width, T const& height) const { using V = vector<3, T>; V eye(50.0, 52.0, 295.6); V dir = normalize(V(0.0, -0.042612, -1.0)); V cx(width * 0.5135 / height, 0.0, 0.0); V cy = normalize(cross(cx, dir)) * T(0.5135); V d = cx * ((x - width / T(2.0)) / width) + cy * ((y - height / T(2.0)) / height) + dir; return R(eye + d * T(140.0), normalize(d)); } }; //------------------------------------------------------------------------------------------------- // Renderer // struct renderer : viewer_type { #if USE_DOUBLE_PRECISION using S = double; using Vec = vec3d; #else using S = float; using Vec = vec3f; #endif using host_ray_type = basic_ray<S>; using device_ray_type = basic_ray<S>; using material_type = generic_material<emissive<S>, glass<S>, matte<S>, mirror<S>>; enum device_type { CPU = 0, GPU }; struct empty_light_type {}; renderer() : viewer_type(512, 512, "Visionaray Smallpt Example") , host_sched(std::thread::hardware_concurrency()) #ifdef __CUDACC__ , device_sched(8, 8) #endif { #ifdef __CUDACC__ using namespace support; add_cmdline_option( cl::makeOption<device_type&>({ { "cpu", CPU, "Rendering on the CPU" }, { "gpu", GPU, "Rendering on the GPU" }, }, "device", cl::Desc("Rendering device"), cl::ArgRequired, cl::init(this->dev_type) ) ); #endif } void init_scene() { #if USE_DOUBLE_PRECISION S base_size = 1e5; #else S base_size = 1e4; #endif // Left spheres.push_back(make_sphere(Vec(base_size + 1.0, 40.8, 81.6), base_size)); materials.push_back(make_matte(Vec(0.75, 0.25, 0.25))); // Right spheres.push_back(make_sphere(Vec(-base_size + 99.0, 40.8, 81.6), base_size)); materials.push_back(make_matte(Vec(0.25, 0.25, 0.75))); // Back spheres.push_back(make_sphere(Vec(50.0, 40.8, base_size), base_size)); materials.push_back(make_matte(Vec(0.75, 0.75, 0.75))); // Front spheres.push_back(make_sphere(Vec(50.0, 40.8, -base_size + 170), base_size)); materials.push_back(make_matte(Vec(0.0))); // Bottom spheres.push_back(make_sphere(Vec(50.0, base_size, 81.6), base_size)); materials.push_back(make_matte(Vec(0.75, 0.75, 0.75))); // Top spheres.push_back(make_sphere(Vec(50.0, -base_size + 81.6, 81.6), base_size)); materials.push_back(make_matte(Vec(0.75, 0.75, 0.75))); // Mirror spheres.push_back(make_sphere(Vec(27.0, 16.5, 47.0), 16.5)); materials.push_back(make_mirror(Vec(0.999))); // Glass spheres.push_back(make_sphere(Vec(73.0, 16.5, 78.0), 16.5)); materials.push_back(make_glass(Vec(0.999))); // Light spheres.push_back(make_sphere(Vec(50.0, 681.6 - 0.27, 81.6), 600.0)); materials.push_back(make_emissive(Vec(12.0, 12.0, 12.0))); #ifdef __CUDACC__ // Copy to GPU device_spheres = spheres; device_materials = materials; #endif } smallpt_camera cam; cpu_buffer_rt<PF_RGBA32F, PF_UNSPECIFIED> host_rt; tiled_sched<host_ray_type> host_sched; aligned_vector<basic_sphere<S>> spheres; aligned_vector<material_type> materials; #ifdef __CUDACC__ pixel_unpack_buffer_rt<PF_RGBA32F, PF_UNSPECIFIED> device_rt; cuda_sched<device_ray_type> device_sched; thrust::device_vector<basic_sphere<S>> device_spheres; thrust::device_vector<material_type> device_materials; #endif unsigned frame_num = 0; device_type dev_type = CPU; protected: void on_display(); void on_resize(int w, int h); private: basic_sphere<S> make_sphere(Vec center, S radius) { static int sphere_id = 0; basic_sphere<S> sphere(center, radius); sphere.prim_id = sphere_id; sphere.geom_id = sphere_id; ++sphere_id; return sphere; } emissive<S> make_emissive(Vec ce) { emissive<S> mat; mat.ce() = from_rgb(ce); mat.ls() = S(1.0); return mat; } glass<S> make_glass(Vec ct) { glass<S> mat; mat.ct() = from_rgb(ct); mat.kt() = S(1.0); mat.cr() = from_rgb(ct); mat.kr() = S(1.0); mat.ior() = spectrum<S>(1.5); return mat; } matte<S> make_matte(Vec cd) { matte<S> mat; mat.cd() = from_rgb(cd); mat.kd() = S(1.0); return mat; } mirror<S> make_mirror(Vec cr) { mirror<S> mat; mat.cr() = from_rgb(cr); mat.kr() = S(0.9); mat.ior() = spectrum<S>(0.0); mat.absorption() = spectrum<S>(0.0); return mat; } }; //------------------------------------------------------------------------------------------------- // Display function // void renderer::on_display() { // Enable gamma correction with OpenGL. glEnable(GL_FRAMEBUFFER_SRGB); glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // make_kernel_params needs (!) lights // TODO: fix this in visionaray API! empty_light_type* ignore = 0; #if USE_DOUBLE_PRECISION float epsilon = 1e-4f; #else float epsilon = 1.5e-2f; #endif if (dev_type == GPU) { #ifdef __CUDACC__ auto sparams = make_sched_params( pixel_sampler::jittered_blend_type{}, cam, device_rt ); auto kparams = make_kernel_params( thrust::raw_pointer_cast(device_spheres.data()), thrust::raw_pointer_cast(device_spheres.data()) + device_spheres.size(), thrust::raw_pointer_cast(device_materials.data()), ignore, ignore, 10, epsilon, vec4(background_color(), 1.0f), vec4(0.0f) ); pathtracing::kernel<decltype(kparams)> kernel; kernel.params = kparams; device_sched.frame(kernel, sparams, ++frame_num); device_rt.display_color_buffer(); #endif } else if (dev_type == CPU) { #ifndef __CUDA_ARCH__ auto sparams = make_sched_params( pixel_sampler::jittered_blend_type{}, cam, host_rt ); auto kparams = make_kernel_params( spheres.data(), spheres.data() + spheres.size(), materials.data(), ignore, ignore, 10, epsilon, vec4(background_color(), 1.0f), vec4(0.0f) ); pathtracing::kernel<decltype(kparams)> kernel; kernel.params = kparams; host_sched.frame(kernel, sparams, ++frame_num); host_rt.display_color_buffer(); #endif } std::cout << "Num samples: " << frame_num << '\r'; std::cout << std::flush; } //------------------------------------------------------------------------------------------------- // resize event // void renderer::on_resize(int w, int h) { frame_num = 0; host_rt.resize(w, h); host_rt.clear_color_buffer(); #ifdef __CUDACC__ device_rt.resize(w, h); device_rt.clear_color_buffer(); #endif viewer_type::on_resize(w, h); } //------------------------------------------------------------------------------------------------- // Main function, performs initialization // int main(int argc, char** argv) { #ifdef __CUDACC__ if (cuda::init_gl_interop() != cudaSuccess) { std::cerr << "Cannot initialize CUDA OpenGL interop\n"; return EXIT_FAILURE; } #endif renderer rend; try { rend.init(argc, argv); } catch (std::exception const& e) { std::cerr << e.what() << '\n'; return EXIT_FAILURE; } rend.init_scene(); rend.event_loop(); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "mmfexporter.h" #include <QRegExp> //Added by qt3to4: #include <Q3ValueList> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kapplication.h> #include <kglobal.h> #include "backends/recipedb.h" #include "datablocks/mixednumber.h" #include "mmdata.h" MMFExporter::MMFExporter( const QString& filename, const QString& format ) : BaseExporter( filename, format ) {} MMFExporter::~MMFExporter() {} int MMFExporter::supportedItems() const { return RecipeDB::All ^ RecipeDB::Photo ^ RecipeDB::Ratings ^ RecipeDB::Authors; } QString MMFExporter::createContent( const RecipeList& recipes ) { QString content; RecipeList::const_iterator recipe_it; for ( recipe_it = recipes.begin(); recipe_it != recipes.end(); ++recipe_it ) { writeMMFHeader( content, *recipe_it ); content += "\n"; writeMMFIngredients( content, *recipe_it ); content += "\n"; writeMMFDirections( content, *recipe_it ); content += "\n"; content += "-----\n"; //end of recipe indicator } return content; } /* Header: * Line 1 - contains five hyphens and "Meal-Master" somewhere in the line * Line 2 - "Title:" followed by a blank space; maximum of 60 char * Line 3 - "Categories:" followed by a blank space; Maximum of 5 * Line 4 - Numeric quantity representing the # of servings (1-9999) */ void MMFExporter::writeMMFHeader( QString &content, const Recipe &recipe ) { content += QString( "----- Exported by Krecipes v%1 [Meal-Master Export Format] -----\n\n" ).arg( krecipes_version() ); QString title = recipe.title; title.truncate( 60 ); content += " Title: " + title + "\n"; int i = 0; QStringList categories; for ( ElementList::const_iterator cat_it = recipe.categoryList.begin(); cat_it != recipe.categoryList.end(); ++cat_it ) { i++; if ( i == 6 ) break; //maximum of 5 categories categories << ( *cat_it ).name; } QString cat_str = " Categories: " + categories.join( ", " ); cat_str.truncate( 67 ); content += cat_str + "\n"; content += " Servings: " + QString::number( qMin( 9999.0, recipe.yield.amount ) ) + "\n"; //some yield info is lost here, but hey, that's the MM format } /* Ingredient lines: * Positions 1-7 contains a numeric quantity * Positions 9-10 Meal-Master unit of measure codes * Positions 12-39 contain text for an ingredient name, or a "-" * in position 12 and text in positions 13-39 (the latter is a * "continuation" line for the previous ingredient name) */ void MMFExporter::writeMMFIngredients( QString &content, const Recipe &recipe ) { //this format requires ingredients without a group to be written first for ( IngredientList::const_iterator ing_it = recipe.ingList.begin(); ing_it != recipe.ingList.end(); ++ing_it ) { if ( ( *ing_it ).groupID == -1 ) { writeSingleIngredient( content, *ing_it, (*ing_it).substitutes.count() > 0 ); for ( Ingredient::SubstitutesList::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ) { Ingredient::SubstitutesList::const_iterator save_it = sub_it; ++sub_it; writeSingleIngredient( content, *save_it, sub_it != (*ing_it).substitutes.end() ); } } } IngredientList list_copy = recipe.ingList; for ( IngredientList group_list = list_copy.firstGroup(); group_list.count() != 0; group_list = list_copy.nextGroup() ) { if ( group_list[ 0 ].groupID == -1 ) //we already handled this group continue; QString group = group_list[ 0 ].group.left( 76 ); //just use the first's name... they're all the same if ( !group.isEmpty() ) { int length = group.length(); QString filler_lt = QString().fill( '-', ( 76 - length ) / 2 ); QString filler_rt = ( length % 2 ) ? QString().fill( '-', ( 76 - length ) / 2 + 1 ) : filler_lt; content += filler_lt + group + filler_rt + "\n"; } for ( IngredientList::const_iterator ing_it = group_list.begin(); ing_it != group_list.end(); ++ing_it ) { writeSingleIngredient( content, *ing_it, (*ing_it).substitutes.count() > 0 ); for ( Ingredient::SubstitutesList::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ) { Ingredient::SubstitutesList::const_iterator save_it = sub_it; ++sub_it; writeSingleIngredient( content, *save_it, sub_it != (*ing_it).substitutes.end() ); } } } } void MMFExporter::writeSingleIngredient( QString &content, const Ingredient &ing, bool is_sub ) { KConfigGroup config = KConfigGroup(KGlobal::config(), "Formatting" ); MixedNumber::Format number_format = ( config.readEntry( "Fraction" ) ).isEmpty() ? MixedNumber::MixedNumberFormat : MixedNumber::DecimalFormat; //columns 1-7 if ( ing.amount > 0 ) content += MixedNumber( ing.amount ).toString( number_format, false ).rightJustified( 7, ' ', true ) + " "; else content += " "; //columns 9-10 bool found_short_form = false; for ( int i = 0; unit_info[ i ].short_form; i++ ) { if ( unit_info[ i ].expanded_form == ing.units.name || unit_info[ i ].plural_expanded_form == ing.units.plural || unit_info[ i ].short_form == ing.units.name ) { found_short_form = true; content += QString( unit_info[ i ].short_form ).leftJustified( 2 ) + " "; break; } } if ( !found_short_form ) { kDebug() << "Warning: unable to find Meal-Master abbreviation for: " << ing.units.name ; kDebug() << " This ingredient (" << ing.name << ") will be exported without a unit" ; content += " "; } //columns 12-39 QString ing_name( ing.name ); if ( ing.prepMethodList.count() > 0 ) ing_name += "; " + ing.prepMethodList.join(", "); if ( is_sub ) ing_name += ", or"; if ( !found_short_form ) ing_name.prepend( ( ing.amount > 1 ? ing.units.plural : ing.units.name ) + " " ); //try and split the ingredient on a word boundary int split_index; if ( ing_name.length() > 28 ) { split_index = ing_name.left(28).lastIndexOf(" ")+1; if ( split_index == 0 ) split_index = 28; } else split_index = 28; content += ing_name.left(split_index) + "\n"; for ( int i = 0; i < ( ing_name.length() - 1 ) / 28; i++ ) //if longer than 28 chars, continue on next line(s) content += " -" + ing_name.mid( 28 * ( i ) + split_index, 28 ) + "\n"; } void MMFExporter::writeMMFDirections( QString &content, const Recipe &recipe ) { QStringList lines; if (recipe.instructions.isEmpty()) lines = QStringList(); else lines = recipe.instructions.split( "\n", QString::KeepEmptyParts); for ( QStringList::const_iterator it = lines.constBegin(); it != lines.constEnd(); ++it ) { content += wrapText( *it, 80 ).join( "\n" ) + "\n"; } } QStringList MMFExporter::wrapText( const QString& str, int at ) const { QStringList ret; QString copy( str ); bool stop = false; while ( !stop ) { QString line( copy.left( at ) ); if ( line.length() >= copy.length() ) stop = true; else { QRegExp rxp( "(\\s\\S*)$", Qt::CaseInsensitive ); // last word in the new line rxp.setMinimal( true ); // one word, only one word, please line = line.replace( rxp, "" ); // remove last word } copy = copy.remove( 0, line.length() ); line = line.trimmed(); line.prepend( " " ); // indent line by one char ret << line; // output of current line } return ret; } <commit_msg>Fix Krazy warnings: doublequote_chars - src/exporters/mmfexporter.cpp<commit_after>/*************************************************************************** * Copyright © 2003 Jason Kivlighn <jkivlighn@gmail.com> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "mmfexporter.h" #include <QRegExp> //Added by qt3to4: #include <Q3ValueList> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kapplication.h> #include <kglobal.h> #include "backends/recipedb.h" #include "datablocks/mixednumber.h" #include "mmdata.h" MMFExporter::MMFExporter( const QString& filename, const QString& format ) : BaseExporter( filename, format ) {} MMFExporter::~MMFExporter() {} int MMFExporter::supportedItems() const { return RecipeDB::All ^ RecipeDB::Photo ^ RecipeDB::Ratings ^ RecipeDB::Authors; } QString MMFExporter::createContent( const RecipeList& recipes ) { QString content; RecipeList::const_iterator recipe_it; for ( recipe_it = recipes.begin(); recipe_it != recipes.end(); ++recipe_it ) { writeMMFHeader( content, *recipe_it ); content += '\n'; writeMMFIngredients( content, *recipe_it ); content += '\n'; writeMMFDirections( content, *recipe_it ); content += '\n'; content += "-----\n"; //end of recipe indicator } return content; } /* Header: * Line 1 - contains five hyphens and "Meal-Master" somewhere in the line * Line 2 - "Title:" followed by a blank space; maximum of 60 char * Line 3 - "Categories:" followed by a blank space; Maximum of 5 * Line 4 - Numeric quantity representing the # of servings (1-9999) */ void MMFExporter::writeMMFHeader( QString &content, const Recipe &recipe ) { content += QString( "----- Exported by Krecipes v%1 [Meal-Master Export Format] -----\n\n" ).arg( krecipes_version() ); QString title = recipe.title; title.truncate( 60 ); content += " Title: " + title + '\n'; int i = 0; QStringList categories; for ( ElementList::const_iterator cat_it = recipe.categoryList.begin(); cat_it != recipe.categoryList.end(); ++cat_it ) { i++; if ( i == 6 ) break; //maximum of 5 categories categories << ( *cat_it ).name; } QString cat_str = " Categories: " + categories.join( ", " ); cat_str.truncate( 67 ); content += cat_str + '\n'; content += " Servings: " + QString::number( qMin( 9999.0, recipe.yield.amount ) ) + '\n'; //some yield info is lost here, but hey, that's the MM format } /* Ingredient lines: * Positions 1-7 contains a numeric quantity * Positions 9-10 Meal-Master unit of measure codes * Positions 12-39 contain text for an ingredient name, or a "-" * in position 12 and text in positions 13-39 (the latter is a * "continuation" line for the previous ingredient name) */ void MMFExporter::writeMMFIngredients( QString &content, const Recipe &recipe ) { //this format requires ingredients without a group to be written first for ( IngredientList::const_iterator ing_it = recipe.ingList.begin(); ing_it != recipe.ingList.end(); ++ing_it ) { if ( ( *ing_it ).groupID == -1 ) { writeSingleIngredient( content, *ing_it, (*ing_it).substitutes.count() > 0 ); for ( Ingredient::SubstitutesList::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ) { Ingredient::SubstitutesList::const_iterator save_it = sub_it; ++sub_it; writeSingleIngredient( content, *save_it, sub_it != (*ing_it).substitutes.end() ); } } } IngredientList list_copy = recipe.ingList; for ( IngredientList group_list = list_copy.firstGroup(); group_list.count() != 0; group_list = list_copy.nextGroup() ) { if ( group_list[ 0 ].groupID == -1 ) //we already handled this group continue; QString group = group_list[ 0 ].group.left( 76 ); //just use the first's name... they're all the same if ( !group.isEmpty() ) { int length = group.length(); QString filler_lt = QString().fill( '-', ( 76 - length ) / 2 ); QString filler_rt = ( length % 2 ) ? QString().fill( '-', ( 76 - length ) / 2 + 1 ) : filler_lt; content += filler_lt + group + filler_rt + '\n'; } for ( IngredientList::const_iterator ing_it = group_list.begin(); ing_it != group_list.end(); ++ing_it ) { writeSingleIngredient( content, *ing_it, (*ing_it).substitutes.count() > 0 ); for ( Ingredient::SubstitutesList::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ) { Ingredient::SubstitutesList::const_iterator save_it = sub_it; ++sub_it; writeSingleIngredient( content, *save_it, sub_it != (*ing_it).substitutes.end() ); } } } } void MMFExporter::writeSingleIngredient( QString &content, const Ingredient &ing, bool is_sub ) { KConfigGroup config = KConfigGroup(KGlobal::config(), "Formatting" ); MixedNumber::Format number_format = ( config.readEntry( "Fraction" ) ).isEmpty() ? MixedNumber::MixedNumberFormat : MixedNumber::DecimalFormat; //columns 1-7 if ( ing.amount > 0 ) content += MixedNumber( ing.amount ).toString( number_format, false ).rightJustified( 7, ' ', true ) + ' '; else content += " "; //columns 9-10 bool found_short_form = false; for ( int i = 0; unit_info[ i ].short_form; i++ ) { if ( unit_info[ i ].expanded_form == ing.units.name || unit_info[ i ].plural_expanded_form == ing.units.plural || unit_info[ i ].short_form == ing.units.name ) { found_short_form = true; content += QString( unit_info[ i ].short_form ).leftJustified( 2 ) + ' '; break; } } if ( !found_short_form ) { kDebug() << "Warning: unable to find Meal-Master abbreviation for: " << ing.units.name ; kDebug() << " This ingredient (" << ing.name << ") will be exported without a unit" ; content += " "; } //columns 12-39 QString ing_name( ing.name ); if ( ing.prepMethodList.count() > 0 ) ing_name += "; " + ing.prepMethodList.join(", "); if ( is_sub ) ing_name += ", or"; if ( !found_short_form ) ing_name.prepend( ( ing.amount > 1 ? ing.units.plural : ing.units.name ) + ' ' ); //try and split the ingredient on a word boundary int split_index; if ( ing_name.length() > 28 ) { split_index = ing_name.left(28).lastIndexOf(" ")+1; if ( split_index == 0 ) split_index = 28; } else split_index = 28; content += ing_name.left(split_index) + '\n'; for ( int i = 0; i < ( ing_name.length() - 1 ) / 28; i++ ) //if longer than 28 chars, continue on next line(s) content += " -" + ing_name.mid( 28 * ( i ) + split_index, 28 ) + '\n'; } void MMFExporter::writeMMFDirections( QString &content, const Recipe &recipe ) { QStringList lines; if (recipe.instructions.isEmpty()) lines = QStringList(); else lines = recipe.instructions.split( '\n', QString::KeepEmptyParts); for ( QStringList::const_iterator it = lines.constBegin(); it != lines.constEnd(); ++it ) { content += wrapText( *it, 80 ).join( "\n" ) + '\n'; } } QStringList MMFExporter::wrapText( const QString& str, int at ) const { QStringList ret; QString copy( str ); bool stop = false; while ( !stop ) { QString line( copy.left( at ) ); if ( line.length() >= copy.length() ) stop = true; else { QRegExp rxp( "(\\s\\S*)$", Qt::CaseInsensitive ); // last word in the new line rxp.setMinimal( true ); // one word, only one word, please line = line.remove( rxp ); // remove last word } copy = copy.remove( 0, line.length() ); line = line.trimmed(); line.prepend( ' ' ); // indent line by one char ret << line; // output of current line } return ret; } <|endoftext|>
<commit_before>//===- Reassociate.cpp - Reassociate binary expressions -------------------===// // // This pass reassociates commutative expressions in an order that is designed // to promote better constant propagation, GCSE, LICM, PRE... // // For example: 4 + (x + 5) -> x + (4 + 5) // // Note that this pass works best if left shifts have been promoted to explicit // multiplies before this pass executes. // // In the implementation of this algorithm, constants are assigned rank = 0, // function arguments are rank = 1, and other values are assigned ranks // corresponding to the reverse post order traversal of current function // (starting at 2), which effectively gives values in deep loops higher rank // than values not in loops. // // This code was originally written by Chris Lattner, and was then cleaned up // and perfected by Casey Carter. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/iOperators.h" #include "llvm/Type.h" #include "llvm/Pass.h" #include "llvm/Constant.h" #include "llvm/Support/CFG.h" #include "Support/Debug.h" #include "Support/PostOrderIterator.h" #include "Support/Statistic.h" namespace { Statistic<> NumLinear ("reassociate","Number of insts linearized"); Statistic<> NumChanged("reassociate","Number of insts reassociated"); Statistic<> NumSwapped("reassociate","Number of insts with operands swapped"); class Reassociate : public FunctionPass { std::map<BasicBlock*, unsigned> RankMap; std::map<Instruction*, unsigned> InstRankMap; public: bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } private: void BuildRankMap(Function &F); unsigned getRank(Value *V); bool ReassociateExpr(BinaryOperator *I); bool ReassociateBB(BasicBlock *BB); }; RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions"); } Pass *createReassociatePass() { return new Reassociate(); } void Reassociate::BuildRankMap(Function &F) { unsigned i = 2; ReversePostOrderTraversal<Function*> RPOT(&F); for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) RankMap[*I] = ++i << 16; } unsigned Reassociate::getRank(Value *V) { if (isa<Argument>(V)) return 1; // Function argument... if (Instruction *I = dyn_cast<Instruction>(V)) { // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that // we can reassociate expressions for code motion! Since we do not recurse // for PHI nodes, we cannot have infinite recursion here, because there // cannot be loops in the value graph that do not go through PHI nodes. // if (I->getOpcode() == Instruction::PHINode || I->getOpcode() == Instruction::Alloca || I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) || I->mayWriteToMemory()) // Cannot move inst if it writes to memory! return RankMap[I->getParent()]; unsigned &CachedRank = InstRankMap[I]; if (CachedRank) return CachedRank; // Rank already known? // If not, compute it! unsigned Rank = 0, MaxRank = RankMap[I->getParent()]; for (unsigned i = 0, e = I->getNumOperands(); i != e && Rank != MaxRank; ++i) Rank = std::max(Rank, getRank(I->getOperand(i))); DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = " << Rank+1 << "\n"); return CachedRank = Rank+1; } // Otherwise it's a global or constant, rank 0. return 0; } bool Reassociate::ReassociateExpr(BinaryOperator *I) { Value *LHS = I->getOperand(0); Value *RHS = I->getOperand(1); unsigned LHSRank = getRank(LHS); unsigned RHSRank = getRank(RHS); bool Changed = false; // Make sure the LHS of the operand always has the greater rank... if (LHSRank < RHSRank) { bool Success = !I->swapOperands(); assert(Success && "swapOperands failed"); std::swap(LHS, RHS); std::swap(LHSRank, RHSRank); Changed = true; ++NumSwapped; DEBUG(std::cerr << "Transposed: " << I /* << " Result BB: " << I->getParent()*/); } // If the LHS is the same operator as the current one is, and if we are the // only expression using it... // if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS)) if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) { // If the rank of our current RHS is less than the rank of the LHS's LHS, // then we reassociate the two instructions... unsigned TakeOp = 0; if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0))) if (IOp->getOpcode() == LHSI->getOpcode()) TakeOp = 1; // Hoist out non-tree portion if (RHSRank < getRank(LHSI->getOperand(TakeOp))) { // Convert ((a + 12) + 10) into (a + (12 + 10)) I->setOperand(0, LHSI->getOperand(TakeOp)); LHSI->setOperand(TakeOp, RHS); I->setOperand(1, LHSI); // Move the LHS expression forward, to ensure that it is dominated by // its operands. LHSI->getParent()->getInstList().remove(LHSI); I->getParent()->getInstList().insert(I, LHSI); ++NumChanged; DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: " << I->getParent()*/); // Since we modified the RHS instruction, make sure that we recheck it. ReassociateExpr(LHSI); ReassociateExpr(I); return true; } } return Changed; } // NegateValue - Insert instructions before the instruction pointed to by BI, // that computes the negative version of the value specified. The negative // version of the value is returned, and BI is left pointing at the instruction // that should be processed next by the reassociation pass. // static Value *NegateValue(Value *V, BasicBlock::iterator &BI) { // We are trying to expose opportunity for reassociation. One of the things // that we want to do to achieve this is to push a negation as deep into an // expression chain as possible, to expose the add instructions. In practice, // this means that we turn this: // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate // the constants. We assume that instcombine will clean up the mess later if // we introduce tons of unneccesary negation instructions... // if (Instruction *I = dyn_cast<Instruction>(V)) if (I->getOpcode() == Instruction::Add && I->use_size() == 1) { Value *RHS = NegateValue(I->getOperand(1), BI); Value *LHS = NegateValue(I->getOperand(0), BI); // We must actually insert a new add instruction here, because the neg // instructions do not dominate the old add instruction in general. By // adding it now, we are assured that the neg instructions we just // inserted dominate the instruction we are about to insert after them. // return BinaryOperator::create(Instruction::Add, LHS, RHS, I->getName()+".neg", cast<Instruction>(RHS)->getNext()); } // Insert a 'neg' instruction that subtracts the value from zero to get the // negation. // return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI); } bool Reassociate::ReassociateBB(BasicBlock *BB) { bool Changed = false; for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) { DEBUG(std::cerr << "Processing: " << *BI); if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) { // Convert a subtract into an add and a neg instruction... so that sub // instructions can be commuted with other add instructions... // // Calculate the negative value of Operand 1 of the sub instruction... // and set it as the RHS of the add instruction we just made... // std::string Name = BI->getName(); BI->setName(""); Instruction *New = BinaryOperator::create(Instruction::Add, BI->getOperand(0), BI->getOperand(1), Name, BI); // Everyone now refers to the add instruction... BI->replaceAllUsesWith(New); // Put the new add in the place of the subtract... deleting the subtract BB->getInstList().erase(BI); BI = New; New->setOperand(1, NegateValue(New->getOperand(1), BI)); Changed = true; DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/); } // If this instruction is a commutative binary operator, and the ranks of // the two operands are sorted incorrectly, fix it now. // if (BI->isAssociative()) { BinaryOperator *I = cast<BinaryOperator>(BI); if (!I->use_empty()) { // Make sure that we don't have a tree-shaped computation. If we do, // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D // Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0)); Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1)); if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() && RHSI && (int)RHSI->getOpcode() == I->getOpcode() && RHSI->use_size() == 1) { // Insert a new temporary instruction... (A+B)+C BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI, RHSI->getOperand(0), RHSI->getName()+".ra", BI); BI = Tmp; I->setOperand(0, Tmp); I->setOperand(1, RHSI->getOperand(1)); // Process the temporary instruction for reassociation now. I = Tmp; ++NumLinear; Changed = true; DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/); } // Make sure that this expression is correctly reassociated with respect // to it's used values... // Changed |= ReassociateExpr(I); } } } return Changed; } bool Reassociate::runOnFunction(Function &F) { // Recalculate the rank map for F BuildRankMap(F); bool Changed = false; for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) Changed |= ReassociateBB(FI); // We are done with the rank map... RankMap.clear(); InstRankMap.clear(); return Changed; } <commit_msg>Assign arguments different ranks so they get grouped together<commit_after>//===- Reassociate.cpp - Reassociate binary expressions -------------------===// // // This pass reassociates commutative expressions in an order that is designed // to promote better constant propagation, GCSE, LICM, PRE... // // For example: 4 + (x + 5) -> x + (4 + 5) // // Note that this pass works best if left shifts have been promoted to explicit // multiplies before this pass executes. // // In the implementation of this algorithm, constants are assigned rank = 0, // function arguments are rank = 1, and other values are assigned ranks // corresponding to the reverse post order traversal of current function // (starting at 2), which effectively gives values in deep loops higher rank // than values not in loops. // // This code was originally written by Chris Lattner, and was then cleaned up // and perfected by Casey Carter. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/iOperators.h" #include "llvm/Type.h" #include "llvm/Pass.h" #include "llvm/Constant.h" #include "llvm/Support/CFG.h" #include "Support/Debug.h" #include "Support/PostOrderIterator.h" #include "Support/Statistic.h" namespace { Statistic<> NumLinear ("reassociate","Number of insts linearized"); Statistic<> NumChanged("reassociate","Number of insts reassociated"); Statistic<> NumSwapped("reassociate","Number of insts with operands swapped"); class Reassociate : public FunctionPass { std::map<BasicBlock*, unsigned> RankMap; std::map<Value*, unsigned> ValueRankMap; public: bool runOnFunction(Function &F); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); } private: void BuildRankMap(Function &F); unsigned getRank(Value *V); bool ReassociateExpr(BinaryOperator *I); bool ReassociateBB(BasicBlock *BB); }; RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions"); } Pass *createReassociatePass() { return new Reassociate(); } void Reassociate::BuildRankMap(Function &F) { unsigned i = 2; // Assign distinct ranks to function arguments for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I) ValueRankMap[I] = ++i; ReversePostOrderTraversal<Function*> RPOT(&F); for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) RankMap[*I] = ++i << 16; } unsigned Reassociate::getRank(Value *V) { if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument... if (Instruction *I = dyn_cast<Instruction>(V)) { // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that // we can reassociate expressions for code motion! Since we do not recurse // for PHI nodes, we cannot have infinite recursion here, because there // cannot be loops in the value graph that do not go through PHI nodes. // if (I->getOpcode() == Instruction::PHINode || I->getOpcode() == Instruction::Alloca || I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) || I->mayWriteToMemory()) // Cannot move inst if it writes to memory! return RankMap[I->getParent()]; unsigned &CachedRank = ValueRankMap[I]; if (CachedRank) return CachedRank; // Rank already known? // If not, compute it! unsigned Rank = 0, MaxRank = RankMap[I->getParent()]; for (unsigned i = 0, e = I->getNumOperands(); i != e && Rank != MaxRank; ++i) Rank = std::max(Rank, getRank(I->getOperand(i))); DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = " << Rank+1 << "\n"); return CachedRank = Rank+1; } // Otherwise it's a global or constant, rank 0. return 0; } bool Reassociate::ReassociateExpr(BinaryOperator *I) { Value *LHS = I->getOperand(0); Value *RHS = I->getOperand(1); unsigned LHSRank = getRank(LHS); unsigned RHSRank = getRank(RHS); bool Changed = false; // Make sure the LHS of the operand always has the greater rank... if (LHSRank < RHSRank) { bool Success = !I->swapOperands(); assert(Success && "swapOperands failed"); std::swap(LHS, RHS); std::swap(LHSRank, RHSRank); Changed = true; ++NumSwapped; DEBUG(std::cerr << "Transposed: " << I /* << " Result BB: " << I->getParent()*/); } // If the LHS is the same operator as the current one is, and if we are the // only expression using it... // if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS)) if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) { // If the rank of our current RHS is less than the rank of the LHS's LHS, // then we reassociate the two instructions... unsigned TakeOp = 0; if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0))) if (IOp->getOpcode() == LHSI->getOpcode()) TakeOp = 1; // Hoist out non-tree portion if (RHSRank < getRank(LHSI->getOperand(TakeOp))) { // Convert ((a + 12) + 10) into (a + (12 + 10)) I->setOperand(0, LHSI->getOperand(TakeOp)); LHSI->setOperand(TakeOp, RHS); I->setOperand(1, LHSI); // Move the LHS expression forward, to ensure that it is dominated by // its operands. LHSI->getParent()->getInstList().remove(LHSI); I->getParent()->getInstList().insert(I, LHSI); ++NumChanged; DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: " << I->getParent()*/); // Since we modified the RHS instruction, make sure that we recheck it. ReassociateExpr(LHSI); ReassociateExpr(I); return true; } } return Changed; } // NegateValue - Insert instructions before the instruction pointed to by BI, // that computes the negative version of the value specified. The negative // version of the value is returned, and BI is left pointing at the instruction // that should be processed next by the reassociation pass. // static Value *NegateValue(Value *V, BasicBlock::iterator &BI) { // We are trying to expose opportunity for reassociation. One of the things // that we want to do to achieve this is to push a negation as deep into an // expression chain as possible, to expose the add instructions. In practice, // this means that we turn this: // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate // the constants. We assume that instcombine will clean up the mess later if // we introduce tons of unneccesary negation instructions... // if (Instruction *I = dyn_cast<Instruction>(V)) if (I->getOpcode() == Instruction::Add && I->use_size() == 1) { Value *RHS = NegateValue(I->getOperand(1), BI); Value *LHS = NegateValue(I->getOperand(0), BI); // We must actually insert a new add instruction here, because the neg // instructions do not dominate the old add instruction in general. By // adding it now, we are assured that the neg instructions we just // inserted dominate the instruction we are about to insert after them. // return BinaryOperator::create(Instruction::Add, LHS, RHS, I->getName()+".neg", cast<Instruction>(RHS)->getNext()); } // Insert a 'neg' instruction that subtracts the value from zero to get the // negation. // return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI); } bool Reassociate::ReassociateBB(BasicBlock *BB) { bool Changed = false; for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) { DEBUG(std::cerr << "Processing: " << *BI); if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) { // Convert a subtract into an add and a neg instruction... so that sub // instructions can be commuted with other add instructions... // // Calculate the negative value of Operand 1 of the sub instruction... // and set it as the RHS of the add instruction we just made... // std::string Name = BI->getName(); BI->setName(""); Instruction *New = BinaryOperator::create(Instruction::Add, BI->getOperand(0), BI->getOperand(1), Name, BI); // Everyone now refers to the add instruction... BI->replaceAllUsesWith(New); // Put the new add in the place of the subtract... deleting the subtract BB->getInstList().erase(BI); BI = New; New->setOperand(1, NegateValue(New->getOperand(1), BI)); Changed = true; DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/); } // If this instruction is a commutative binary operator, and the ranks of // the two operands are sorted incorrectly, fix it now. // if (BI->isAssociative()) { BinaryOperator *I = cast<BinaryOperator>(BI); if (!I->use_empty()) { // Make sure that we don't have a tree-shaped computation. If we do, // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D // Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0)); Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1)); if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() && RHSI && (int)RHSI->getOpcode() == I->getOpcode() && RHSI->use_size() == 1) { // Insert a new temporary instruction... (A+B)+C BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI, RHSI->getOperand(0), RHSI->getName()+".ra", BI); BI = Tmp; I->setOperand(0, Tmp); I->setOperand(1, RHSI->getOperand(1)); // Process the temporary instruction for reassociation now. I = Tmp; ++NumLinear; Changed = true; DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/); } // Make sure that this expression is correctly reassociated with respect // to it's used values... // Changed |= ReassociateExpr(I); } } } return Changed; } bool Reassociate::runOnFunction(Function &F) { // Recalculate the rank map for F BuildRankMap(F); bool Changed = false; for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) Changed |= ReassociateBB(FI); // We are done with the rank map... RankMap.clear(); ValueRankMap.clear(); return Changed; } <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrColorSpaceXform.h" #include "SkColorSpace.h" #include "SkColorSpace_Base.h" #include "SkMatrix44.h" #include "SkSpinlock.h" class GrColorSpaceXformCache { public: using NewValueFn = std::function<sk_sp<GrColorSpaceXform>(void)>; GrColorSpaceXformCache() : fSequence(0) {} sk_sp<GrColorSpaceXform> findOrAdd(uint64_t key, NewValueFn newValue) { int oldest = 0; for (int i = 0; i < kEntryCount; ++i) { if (fEntries[i].fKey == key) { fEntries[i].fLastUse = fSequence++; return fEntries[i].fXform; } if (fEntries[i].fLastUse < fEntries[oldest].fLastUse) { oldest = i; } } fEntries[oldest].fKey = key; fEntries[oldest].fXform = newValue(); fEntries[oldest].fLastUse = fSequence++; return fEntries[oldest].fXform; } private: enum { kEntryCount = 32 }; struct Entry { // The default Entry is "valid". Any 64-bit key that is the same 32-bit value repeated // implies no xform is necessary, so nullptr should be returned. This particular case should // never happen, but by initializing all entries with this data, we can avoid special cases // for the array not yet being full. Entry() : fKey(0), fXform(nullptr), fLastUse(0) {} uint64_t fKey; sk_sp<GrColorSpaceXform> fXform; uint64_t fLastUse; }; Entry fEntries[kEntryCount]; uint64_t fSequence; }; GrColorSpaceXform::GrColorSpaceXform(const SkMatrix44& srcToDst) : fSrcToDst(srcToDst) {} static SkSpinlock gColorSpaceXformCacheSpinlock; sk_sp<GrColorSpaceXform> GrColorSpaceXform::Make(SkColorSpace* src, SkColorSpace* dst) { if (!src || !dst) { // Invalid return nullptr; } if (src == dst) { // Quick equality check - no conversion needed in this case return nullptr; } const SkMatrix44* toXYZD50 = as_CSB(src)->toXYZD50(); const SkMatrix44* fromXYZD50 = as_CSB(dst)->fromXYZD50(); if (!toXYZD50 || !fromXYZD50) { // unsupported colour spaces -- cannot specify gamut as a matrix return nullptr; } uint32_t srcHash = as_CSB(src)->toXYZD50Hash(); uint32_t dstHash = as_CSB(dst)->toXYZD50Hash(); if (srcHash == dstHash) { // Identical gamut - no conversion needed in this case SkASSERT(*toXYZD50 == *as_CSB(dst)->toXYZD50() && "Hash collision"); return nullptr; } auto deferredResult = [fromXYZD50, toXYZD50]() { SkMatrix44 srcToDst(SkMatrix44::kUninitialized_Constructor); srcToDst.setConcat(*fromXYZD50, *toXYZD50); return sk_make_sp<GrColorSpaceXform>(srcToDst); }; if (gColorSpaceXformCacheSpinlock.tryAcquire()) { static GrColorSpaceXformCache* gCache; if (nullptr == gCache) { gCache = new GrColorSpaceXformCache(); } uint64_t key = static_cast<uint64_t>(srcHash) << 32 | static_cast<uint64_t>(dstHash); sk_sp<GrColorSpaceXform> xform = gCache->findOrAdd(key, deferredResult); gColorSpaceXformCacheSpinlock.release(); return xform; } else { // Rather than wait for the spin lock, just bypass the cache return deferredResult(); } } bool GrColorSpaceXform::Equals(const GrColorSpaceXform* a, const GrColorSpaceXform* b) { if (a == b) { return true; } if (!a || !b) { return false; } return a->fSrcToDst == b->fSrcToDst; } GrColor4f GrColorSpaceXform::apply(const GrColor4f& srcColor) { GrColor4f result; fSrcToDst.mapScalars(srcColor.fRGBA, result.fRGBA); return result; } <commit_msg>Clamp colors after gamut xform in Ganesh<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrColorSpaceXform.h" #include "SkColorSpace.h" #include "SkColorSpace_Base.h" #include "SkMatrix44.h" #include "SkSpinlock.h" class GrColorSpaceXformCache { public: using NewValueFn = std::function<sk_sp<GrColorSpaceXform>(void)>; GrColorSpaceXformCache() : fSequence(0) {} sk_sp<GrColorSpaceXform> findOrAdd(uint64_t key, NewValueFn newValue) { int oldest = 0; for (int i = 0; i < kEntryCount; ++i) { if (fEntries[i].fKey == key) { fEntries[i].fLastUse = fSequence++; return fEntries[i].fXform; } if (fEntries[i].fLastUse < fEntries[oldest].fLastUse) { oldest = i; } } fEntries[oldest].fKey = key; fEntries[oldest].fXform = newValue(); fEntries[oldest].fLastUse = fSequence++; return fEntries[oldest].fXform; } private: enum { kEntryCount = 32 }; struct Entry { // The default Entry is "valid". Any 64-bit key that is the same 32-bit value repeated // implies no xform is necessary, so nullptr should be returned. This particular case should // never happen, but by initializing all entries with this data, we can avoid special cases // for the array not yet being full. Entry() : fKey(0), fXform(nullptr), fLastUse(0) {} uint64_t fKey; sk_sp<GrColorSpaceXform> fXform; uint64_t fLastUse; }; Entry fEntries[kEntryCount]; uint64_t fSequence; }; GrColorSpaceXform::GrColorSpaceXform(const SkMatrix44& srcToDst) : fSrcToDst(srcToDst) {} static SkSpinlock gColorSpaceXformCacheSpinlock; sk_sp<GrColorSpaceXform> GrColorSpaceXform::Make(SkColorSpace* src, SkColorSpace* dst) { if (!src || !dst) { // Invalid return nullptr; } if (src == dst) { // Quick equality check - no conversion needed in this case return nullptr; } const SkMatrix44* toXYZD50 = as_CSB(src)->toXYZD50(); const SkMatrix44* fromXYZD50 = as_CSB(dst)->fromXYZD50(); if (!toXYZD50 || !fromXYZD50) { // unsupported colour spaces -- cannot specify gamut as a matrix return nullptr; } uint32_t srcHash = as_CSB(src)->toXYZD50Hash(); uint32_t dstHash = as_CSB(dst)->toXYZD50Hash(); if (srcHash == dstHash) { // Identical gamut - no conversion needed in this case SkASSERT(*toXYZD50 == *as_CSB(dst)->toXYZD50() && "Hash collision"); return nullptr; } auto deferredResult = [fromXYZD50, toXYZD50]() { SkMatrix44 srcToDst(SkMatrix44::kUninitialized_Constructor); srcToDst.setConcat(*fromXYZD50, *toXYZD50); return sk_make_sp<GrColorSpaceXform>(srcToDst); }; if (gColorSpaceXformCacheSpinlock.tryAcquire()) { static GrColorSpaceXformCache* gCache; if (nullptr == gCache) { gCache = new GrColorSpaceXformCache(); } uint64_t key = static_cast<uint64_t>(srcHash) << 32 | static_cast<uint64_t>(dstHash); sk_sp<GrColorSpaceXform> xform = gCache->findOrAdd(key, deferredResult); gColorSpaceXformCacheSpinlock.release(); return xform; } else { // Rather than wait for the spin lock, just bypass the cache return deferredResult(); } } bool GrColorSpaceXform::Equals(const GrColorSpaceXform* a, const GrColorSpaceXform* b) { if (a == b) { return true; } if (!a || !b) { return false; } return a->fSrcToDst == b->fSrcToDst; } GrColor4f GrColorSpaceXform::apply(const GrColor4f& srcColor) { GrColor4f result; fSrcToDst.mapScalars(srcColor.fRGBA, result.fRGBA); for (int i = 0; i < 4; ++i) { result.fRGBA[i] = SkTPin(result.fRGBA[i], 0.0f, 1.0f); } return result; } <|endoftext|>
<commit_before>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "nomlib/graphics/RendererInfo.hpp" namespace nom { RendererInfo::RendererInfo ( void ) : flags ( 0 ), texture_width ( 0 ), texture_height ( 0 ) { //NOM_LOG_TRACE(NOM); } RendererInfo::~RendererInfo ( void ) { //NOM_LOG_TRACE(NOM); } uint32 RendererInfo::optimal_texture_format ( void ) const { return this->texture_formats.front(); } bool RendererInfo::target_texture ( void ) const { if ( this->flags & SDL_RENDERER_TARGETTEXTURE ) return true; return false; } std::ostream& operator << ( std::ostream& os, const RendererInfo& info ) { os << "Renderer Name: " << info.name << std::endl << std::endl << "Device Capabilities: " << std::endl << std::endl; if ( info.flags & SDL_RENDERER_TARGETTEXTURE ) { os << "SDL_RENDERER_TARGETTEXTURE" << std::endl; } if ( info.flags & SDL_RENDERER_ACCELERATED ) { os << "SDL_RENDERER_ACCELERATED" << std::endl; } if ( info.flags & SDL_RENDERER_PRESENTVSYNC ) { os << "SDL_RENDERER_PRESENTVSYNC" << std::endl; } os << std::endl << "Texture Formats: " << std::endl << std::endl; for ( nom::uint32 idx = 0; idx < info.texture_formats.size(); ++idx ) { os << PIXEL_FORMAT_NAME( info.texture_formats[idx] ) << std::endl; } os << "Texture Width: " << info.texture_width << std::endl; os << "Texture Height: " << info.texture_height << std::endl; return os; } } // namespace nom <commit_msg>RendererInfo: Use implemented method call to check target_texture flag<commit_after>/****************************************************************************** nomlib - C++11 cross-platform game engine Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "nomlib/graphics/RendererInfo.hpp" namespace nom { RendererInfo::RendererInfo ( void ) : flags ( 0 ), texture_width ( 0 ), texture_height ( 0 ) { //NOM_LOG_TRACE(NOM); } RendererInfo::~RendererInfo ( void ) { //NOM_LOG_TRACE(NOM); } uint32 RendererInfo::optimal_texture_format ( void ) const { return this->texture_formats.front(); } bool RendererInfo::target_texture ( void ) const { if ( this->flags & SDL_RENDERER_TARGETTEXTURE ) return true; return false; } std::ostream& operator << ( std::ostream& os, const RendererInfo& info ) { os << "Renderer Name: " << info.name << std::endl << std::endl << "Device Capabilities: " << std::endl << std::endl; if ( info.target_texture() ) { os << "SDL_RENDERER_TARGETTEXTURE" << std::endl; } if ( info.flags & SDL_RENDERER_ACCELERATED ) { os << "SDL_RENDERER_ACCELERATED" << std::endl; } if ( info.flags & SDL_RENDERER_PRESENTVSYNC ) { os << "SDL_RENDERER_PRESENTVSYNC" << std::endl; } os << std::endl << "Texture Formats: " << std::endl << std::endl; for ( nom::uint32 idx = 0; idx < info.texture_formats.size(); ++idx ) { os << PIXEL_FORMAT_NAME( info.texture_formats[idx] ) << std::endl; } os << "Texture Width: " << info.texture_width << std::endl; os << "Texture Height: " << info.texture_height << std::endl; return os; } } // namespace nom <|endoftext|>
<commit_before>#include "instruments/population/GenerationFitnessCSV.hpp" #include <cmath> #include <string> GenerationFitnessCSV::GenerationFitnessCSV( PopulationNode* target, std::string outFile, float bottomFitness, float topFitness, float resolution ) : CSVInstrument(target, outFile) { std::vector<float> buckets; std::vector<std::string> headerBuckets; for (float i = bottomFitness; i <= topFitness; i+= resolution) { buckets.push_back(i); headerBuckets.push_back(std::to_string(i)); } this->buckets = buckets; this->resolution = resolution; this->addToHeader("Generation"); this->addToHeader(headerBuckets); } float GenerationFitnessCSV::bucket(float actual) { float mod = fmod(actual, this->resolution); return (mod < this->resolution/2 ? actual - mod : actual - mod + resolution); } std::map<std::string, unsigned int> GenerationFitnessCSV::buildEmptyMap() { std::map<std::string, unsigned int> counts; for (float fitness: this->buckets) counts.emplace(std::to_string(fitness), 0); return counts; } void GenerationFitnessCSV::reportFitnesses() { std::map<std::string, unsigned int> output = this->buildEmptyMap(); output.emplace("Generation", this->target->currentGeneration()); std::vector<float> fitnesses = this->target->getFitnesses(); for (float fitness: fitnesses) output[std::to_string(fitness)]++; this->write(output, (unsigned int)0); } void GenerationFitnessCSV::initialReport() { this->reportFitnesses(); } void GenerationFitnessCSV::runtimeReport() { this->reportFitnesses(); } void GenerationFitnessCSV::endReport() { this->reportFitnesses(); } <commit_msg>[GenerationFitnessCSV]: Fixed duplicated last generation<commit_after>#include "instruments/population/GenerationFitnessCSV.hpp" #include <cmath> #include <string> GenerationFitnessCSV::GenerationFitnessCSV( PopulationNode* target, std::string outFile, float bottomFitness, float topFitness, float resolution ) : CSVInstrument(target, outFile) { std::vector<float> buckets; std::vector<std::string> headerBuckets; for (float i = bottomFitness; i <= topFitness; i+= resolution) { buckets.push_back(i); headerBuckets.push_back(std::to_string(i)); } this->buckets = buckets; this->resolution = resolution; this->addToHeader("Generation"); this->addToHeader(headerBuckets); } float GenerationFitnessCSV::bucket(float actual) { float mod = fmod(actual, this->resolution); return (mod < this->resolution/2 ? actual - mod : actual - mod + resolution); } std::map<std::string, unsigned int> GenerationFitnessCSV::buildEmptyMap() { std::map<std::string, unsigned int> counts; for (float fitness: this->buckets) counts.emplace(std::to_string(fitness), 0); return counts; } void GenerationFitnessCSV::reportFitnesses() { std::map<std::string, unsigned int> output = this->buildEmptyMap(); output.emplace("Generation", this->target->currentGeneration()); std::vector<float> fitnesses = this->target->getFitnesses(); for (float fitness: fitnesses) output[std::to_string(fitness)]++; this->write(output, (unsigned int)0); } void GenerationFitnessCSV::initialReport() { this->reportFitnesses(); } void GenerationFitnessCSV::runtimeReport() { this->reportFitnesses(); } // The same as the runtime report after the last generation void GenerationFitnessCSV::endReport() {} <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkScalarListLookupTableProperty.h" #include "mitkScalarListLookupTablePropertySerializer.h" #include <tinyxml2.h> tinyxml2::XMLElement* mitk::ScalarListLookupTablePropertySerializer::Serialize(tinyxml2::XMLDocument& doc) { const ScalarListLookupTableProperty* prop = dynamic_cast<const ScalarListLookupTableProperty*>(m_Property.GetPointer()); if (prop == nullptr) { MITK_ERROR << "Serialization: Property is NULL"; return nullptr; } ScalarListLookupTable lut = prop->GetValue(); const ScalarListLookupTable::LookupTableType& map = lut.GetLookupTable(); auto* mapElement = doc.NewElement("ScalarListLookupTable"); for (ScalarListLookupTable::LookupTableType::const_iterator mapIter = map.begin(); mapIter != map.end(); ++mapIter) { const ScalarListLookupTable::ValueType& list = mapIter->second; auto* listElement = doc.NewElement("List"); listElement->SetAttribute("name", mapIter->first.c_str()); for (ScalarListLookupTable::ValueType::const_iterator listIter = list.begin(); listIter != list.end(); ++listIter) { auto* valueElement = doc.NewElement("Element"); valueElement->SetAttribute("value", *listIter); listElement->InsertEndChild(valueElement); } mapElement->InsertEndChild(listElement); } return mapElement; } mitk::BaseProperty::Pointer mitk::ScalarListLookupTablePropertySerializer::Deserialize(const tinyxml2::XMLElement* element) { if (!element) { MITK_ERROR << "Deserialization: Element is NULL"; return nullptr; } ScalarListLookupTable lut; for (auto* listElement = element->FirstChildElement("List"); listElement != nullptr; listElement = listElement->NextSiblingElement("List")) { std::string name; if (listElement->Attribute("name") != nullptr) { name = listElement->Attribute("name"); } else { MITK_ERROR << "Deserialization: No element with attribute 'name' found"; return nullptr; } ScalarListLookupTable::ValueType list; for (auto* valueElement = listElement->FirstChildElement("Element"); valueElement != nullptr; valueElement = valueElement->NextSiblingElement("Element")) { double value; if (valueElement->QueryDoubleAttribute("value", &value) != tinyxml2::XML_SUCCESS) { MITK_ERROR << "Deserialization: No element with attribute 'value' found"; return nullptr; } list.push_back(value); } lut.SetTableValue(name, list); } return ScalarListLookupTableProperty::New(lut).GetPointer(); } MITK_REGISTER_SERIALIZER(ScalarListLookupTablePropertySerializer); ::std::string mitk::PropertyPersistenceSerialization::serializeScalarListLookupTablePropertyToXML( const mitk::BaseProperty *prop) { mitk::ScalarListLookupTablePropertySerializer::Pointer lutSerializer = mitk::ScalarListLookupTablePropertySerializer::New(); lutSerializer->SetProperty(prop); tinyxml2::XMLDocument doc; auto xmlLut = lutSerializer->Serialize(doc); tinyxml2::XMLPrinter printer; doc.Print(&printer); return printer.CStr(); } mitk::BaseProperty::Pointer mitk::PropertyPersistenceDeserialization::deserializeXMLToScalarListLookupTableProperty( const std::string &value) { mitk::ScalarListLookupTablePropertySerializer::Pointer lutSerializer = mitk::ScalarListLookupTablePropertySerializer::New(); tinyxml2::XMLDocument doc; doc.Parse(value.c_str()); return lutSerializer->Deserialize(doc.RootElement()); } <commit_msg>Fix unused variable<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkScalarListLookupTableProperty.h" #include "mitkScalarListLookupTablePropertySerializer.h" #include <tinyxml2.h> tinyxml2::XMLElement* mitk::ScalarListLookupTablePropertySerializer::Serialize(tinyxml2::XMLDocument& doc) { const ScalarListLookupTableProperty* prop = dynamic_cast<const ScalarListLookupTableProperty*>(m_Property.GetPointer()); if (prop == nullptr) { MITK_ERROR << "Serialization: Property is NULL"; return nullptr; } ScalarListLookupTable lut = prop->GetValue(); const ScalarListLookupTable::LookupTableType& map = lut.GetLookupTable(); auto* mapElement = doc.NewElement("ScalarListLookupTable"); for (ScalarListLookupTable::LookupTableType::const_iterator mapIter = map.begin(); mapIter != map.end(); ++mapIter) { const ScalarListLookupTable::ValueType& list = mapIter->second; auto* listElement = doc.NewElement("List"); listElement->SetAttribute("name", mapIter->first.c_str()); for (ScalarListLookupTable::ValueType::const_iterator listIter = list.begin(); listIter != list.end(); ++listIter) { auto* valueElement = doc.NewElement("Element"); valueElement->SetAttribute("value", *listIter); listElement->InsertEndChild(valueElement); } mapElement->InsertEndChild(listElement); } return mapElement; } mitk::BaseProperty::Pointer mitk::ScalarListLookupTablePropertySerializer::Deserialize(const tinyxml2::XMLElement* element) { if (!element) { MITK_ERROR << "Deserialization: Element is NULL"; return nullptr; } ScalarListLookupTable lut; for (auto* listElement = element->FirstChildElement("List"); listElement != nullptr; listElement = listElement->NextSiblingElement("List")) { std::string name; if (listElement->Attribute("name") != nullptr) { name = listElement->Attribute("name"); } else { MITK_ERROR << "Deserialization: No element with attribute 'name' found"; return nullptr; } ScalarListLookupTable::ValueType list; for (auto* valueElement = listElement->FirstChildElement("Element"); valueElement != nullptr; valueElement = valueElement->NextSiblingElement("Element")) { double value; if (valueElement->QueryDoubleAttribute("value", &value) != tinyxml2::XML_SUCCESS) { MITK_ERROR << "Deserialization: No element with attribute 'value' found"; return nullptr; } list.push_back(value); } lut.SetTableValue(name, list); } return ScalarListLookupTableProperty::New(lut).GetPointer(); } MITK_REGISTER_SERIALIZER(ScalarListLookupTablePropertySerializer); ::std::string mitk::PropertyPersistenceSerialization::serializeScalarListLookupTablePropertyToXML( const mitk::BaseProperty *prop) { mitk::ScalarListLookupTablePropertySerializer::Pointer lutSerializer = mitk::ScalarListLookupTablePropertySerializer::New(); lutSerializer->SetProperty(prop); tinyxml2::XMLDocument doc; lutSerializer->Serialize(doc); tinyxml2::XMLPrinter printer; doc.Print(&printer); return printer.CStr(); } mitk::BaseProperty::Pointer mitk::PropertyPersistenceDeserialization::deserializeXMLToScalarListLookupTableProperty( const std::string &value) { mitk::ScalarListLookupTablePropertySerializer::Pointer lutSerializer = mitk::ScalarListLookupTablePropertySerializer::New(); tinyxml2::XMLDocument doc; doc.Parse(value.c_str()); return lutSerializer->Deserialize(doc.RootElement()); } <|endoftext|>
<commit_before>/** * @file IntegralImageProvider.cpp * * Implementation of class IntegralImageProvider * */ #include "IntegralImageProvider.h" IntegralImageProvider::IntegralImageProvider() {} IntegralImageProvider::~IntegralImageProvider() {} void IntegralImageProvider::execute(CameraInfo::CameraID id) { cameraID = id; makeIntegralBild(getBallDetectorIntegralImage()); } void IntegralImageProvider::makeIntegralBild( BallDetectorIntegralImage& integralImage) const { const int32_t FACTOR = integralImage.FACTOR; const uint32_t MAX_COLOR = integralImage.MAX_COLOR; const uint32_t imgWidth = getImage().width() / FACTOR; const uint32_t imgHeight = getImage().height() / FACTOR; integralImage.setDimension(imgWidth, imgHeight); uint32_t* dataPtr = integralImage.getDataPointer(); // NOTE: a pixel consists of two Y values (YUYV format). // When skipping a pixel using this pointer, you effectivly skip two Y // values. const Pixel* imgPtr = reinterpret_cast<Pixel*>(getImage().data()); const int32_t FACTOR_HALF = integralImage.FACTOR / 2; // We need to skip FACTOR-1 lines in the image after after each processed // line. The image pixels contain 2 Y values, and thus only half of the // pixels are skipped. uint32_t pixels2SkipAfterLine = (FACTOR - 1) * (imgWidth * FACTOR_HALF); // iterate over first line uint32_t* curRowPtr = dataPtr; { uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint32_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i]; } // Increment current row by one step curRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } } imgPtr += pixels2SkipAfterLine; // set a pointer to the start of the first line uint32_t* prevRowPtr = dataPtr; // iterate over all remaining lines using the previously accumulated values for (uint16_t y = 1; y < imgHeight; ++y) { // reset accumalator in each line uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint32_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i] + prevRowPtr[i]; } // Both the current row and the previous row are incremented by one // step curRowPtr += MAX_COLOR; prevRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } imgPtr += pixels2SkipAfterLine; } }<commit_msg>Type can be smaller<commit_after>/** * @file IntegralImageProvider.cpp * * Implementation of class IntegralImageProvider * */ #include "IntegralImageProvider.h" IntegralImageProvider::IntegralImageProvider() {} IntegralImageProvider::~IntegralImageProvider() {} void IntegralImageProvider::execute(CameraInfo::CameraID id) { cameraID = id; makeIntegralBild(getBallDetectorIntegralImage()); } void IntegralImageProvider::makeIntegralBild( BallDetectorIntegralImage& integralImage) const { const int32_t FACTOR = integralImage.FACTOR; const uint32_t MAX_COLOR = integralImage.MAX_COLOR; const uint32_t imgWidth = getImage().width() / FACTOR; const uint32_t imgHeight = getImage().height() / FACTOR; integralImage.setDimension(imgWidth, imgHeight); uint32_t* dataPtr = integralImage.getDataPointer(); // NOTE: a pixel consists of two Y values (YUYV format). // When skipping a pixel using this pointer, you effectivly skip two Y // values. const Pixel* imgPtr = reinterpret_cast<Pixel*>(getImage().data()); const int32_t FACTOR_HALF = integralImage.FACTOR / 2; // We need to skip FACTOR-1 lines in the image after after each processed // line. The image pixels contain 2 Y values, and thus only half of the // pixels are skipped. uint32_t pixels2SkipAfterLine = (FACTOR - 1) * (imgWidth * FACTOR_HALF); // iterate over first line uint32_t* curRowPtr = dataPtr; { uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint16_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i]; } // Increment current row by one step curRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } } imgPtr += pixels2SkipAfterLine; // set a pointer to the start of the first line uint32_t* prevRowPtr = dataPtr; // iterate over all remaining lines using the previously accumulated values for (uint16_t y = 1; y < imgHeight; ++y) { // reset accumalator in each line uint32_t akk[MAX_COLOR] = {}; for (uint16_t x = 0; x < imgWidth; ++x) { if (getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) { ++akk[1]; } else { akk[0] += (imgPtr->y0); } for (uint16_t i = 0; i < MAX_COLOR; ++i) { curRowPtr[i] = akk[i] + prevRowPtr[i]; } // Both the current row and the previous row are incremented by one // step curRowPtr += MAX_COLOR; prevRowPtr += MAX_COLOR; // The image pointer needs to skip 4 Y values == 2 image pixels imgPtr += FACTOR_HALF; } imgPtr += pixels2SkipAfterLine; } }<|endoftext|>
<commit_before>#pragma once #pragma execution_character_set("utf-8") #include <iostream> #include "paramenters.h" #include "spikedetect.h" #include "probe.h" #include "preprossingdata.h" #include "klustakwik.h" #define CHANNELS 32 #define SAMPLES 1000 using namespace std; int main() { /*-----------------------------test_paramenter.h-------------------------------------------*/ Params p; std::cout << p.get_chunk_overlap_seconds() << " " << p.get_chunk_size_seconds()<< std::endl; /*--------------------------------------------------------------------------------------------*/ /*------------------------------------test_probe.h-------------------------------------------*/ Probe prb; map <int, vector < int > > probe_adjacency_list; prb.edges_to_adjacency_list(probe_adjacency_list); prb.test_output(); //ȥŵ vector<int> dead_ch(CHANNELS, 0); prb.dead_channels(dead_ch, CHANNELS); for (int i = 0; i < CHANNELS; i++) cout << dead_ch[i] << " "; cout << endl; /*--------------------------------------------------------------------------------------------*/ /*------------------------------test_spikedetect.h-------------------------------------------*/ SpikeDetect s("traces_f.txt"); s.threshold(); s.transform(); std::map <int, std::vector < std::pair<int, int> > > comps; s.detect(comps); std::cout << "=============line1=================" << std::endl; std::vector < std::pair<int, int> > tmp; std::vector< std::vector< std::vector <float> > > waveforms; std::vector< std::vector <float> > masks; for (unsigned int i = 0; i < comps.size(); i++) { tmp = comps[i]; //ʾʱķΧ[s_min,s_max] int s_min = tmp[0].first; int s_max = tmp[0].first; //ʾcomponentڱεŵ,ڱΪ0δڱΪ1 std::vector<int > mask_bin(CHANNELS, 0); mask_bin[ tmp[0].second ] = 1; for (unsigned int ii = 1; ii < tmp.size(); ii++){ if (s_min > tmp[ii].first) s_min = tmp[ii].first; if (s_max < tmp[ii].first) s_max = tmp[ii].first; mask_bin[ tmp[ii].second ] = 1; } //ȡwaveform std::vector <std::vector <float> > wave((s_max - s_min), std::vector<float>(CHANNELS,0)); s.comp_wave(s_min, s_max, tmp,wave); //ڱ std::vector<float > mask(CHANNELS, 0.0);//δڱŵķֵһֵ s.mask(mask, mask_bin, wave); masks.push_back(mask); //Ķʱ float s_aligned; s.spike_sample_aligned(s_min, s_max, wave, s_aligned); //ʱȡ׼ std::vector <std::vector <float> > waveform(p.get_extract_s_before()+p.get_extract_s_after(), vector<float>(CHANNELS, 0)); s.extract(s_aligned, waveform); waveforms.push_back(waveform); } //PCA ȡεɷ int n_spikes = comps.size(); int n_pca = p.get_n_features_per_channel(); std::vector< std::vector< std::vector <float> > > out(n_spikes, std::vector<std::vector<float> > (CHANNELS, vector<float>(n_pca )) ); s.PCA(n_spikes, waveforms, masks, out); //s.output(); /*-------------------------------------preprossingdata.h------------------------------------*/ Preprossingdata data(n_spikes, CHANNELS, n_pca,out, masks); std::vector<float > all_features; std::vector<float > all_masks ; std::vector<int > all_unmasked; std::vector<int > offsets; std::vector<float >noise_mean; std::vector<float > noise_variance; std::vector<float > correction_terms; std::vector<float > float_num_unmasked(n_spikes,0.0); data.rawsparsedata(all_features, all_masks, all_unmasked, offsets, noise_mean, noise_variance, correction_terms, float_num_unmasked); system("Pause"); } //#include<iostream> //#include<algorithm> //#include<cstdlib> //#include<fstream> //#include "Eigen/Dense" //using namespace std; //using namespace Eigen; //void featurenormalize(MatrixXf &X) //{ // ÿһάȾֵ // MatrixXf meanval = X.colwise().mean(); // RowVectorXf meanvecRow = meanval; // ֵΪ0 // X.rowwise() -= meanvecRow; //} //void computeCov(MatrixXf &X, MatrixXf &covMat) //{ // ЭC = XTX /(n-1); // covMat = X.adjoint() * X; // covMat = covMat.array() / (X.rows() - 1); //} //void computeEig(MatrixXf &C, MatrixXf &vec, MatrixXf &val) //{ // ֵʹselfadjontն㷨ȥ㣬òvecval // SelfAdjointEigenSolver<MatrixXf> eig(C); // vec = eig.eigenvectors(); // val = eig.eigenvalues(); //} //int computeDim(MatrixXf &val) //{ // int dim; // double sum = 0; // for (int i = val.rows() - 1; i >= 0; --i) // { // sum += val(i, 0); // dim = i; // // if (sum / val.sum() >= 0.95) // break; // } // return val.rows() - dim; //} //int main() //{ // ifstream fin("input.txt"); // ofstream fout("output.txt"); // const int m = 2, n = 10; // MatrixXf X(2, 10), C(10, 10); // MatrixXf vec, val; // // ȡ // double in[200]; // for(int i = 0; i < m; ++i) // { // for (int j = 0; j < n; ++j){ // fin >> in[j]; // X(i, j) = in[j]; // } // } // pca // // ֵ // featurenormalize(X); // Э // cout << X << endl; // computeCov(X, C); // cout << C << endl; // ֵ // computeEig(C, vec, val); // cout << vec << endl << val; // ʧʣȷά // int dim = computeDim(val); // // MatrixXf res = X * vec.rightCols(3); // cout << vec.rightCols(3) << endl; // // cout << "the result is " << res.rows() << "x" << res.cols() << " after pca algorithm." << endl; // cout << res; // system("pause"); // return 0; //}<commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <multimedia/qmediaresource.h> #include <QtCore/qsize.h> #include <QtCore/qurl.h> #include <QtCore/qvariant.h> /*! \class QMediaResource \preliminary \brief The QMediaResource class provides a description of a media resource. */ /*! \typedef QMediaResourceList Synonym for \c QList<QMediaResource> */ /*! Constructs a null media resource. */ QMediaResource::QMediaResource() { } /*! Constructs a media resource with the given \a mimeType from a \a uri. */ QMediaResource::QMediaResource(const QUrl &uri, const QString &mimeType) { values.insert(Uri, qVariantFromValue(uri)); values.insert(MimeType, mimeType); } /*! Constructs a copy of a media resource \a other. */ QMediaResource::QMediaResource(const QMediaResource &other) : values(other.values) { } /*! Assigns the value of \a other to a media resource. */ QMediaResource &QMediaResource::operator =(const QMediaResource &other) { values = other.values; return *this; } /*! Destroys a media resource. */ QMediaResource::~QMediaResource() { } /*! Compares a media resource to \a other. Returns true if the resources are identical, and false otherwise. */ bool QMediaResource::operator ==(const QMediaResource &other) const { return values == other.values; } /*! Compares a media resource to \a other. Returns true if they are different, and false otherwise. */ bool QMediaResource::operator !=(const QMediaResource &other) const { return values != other.values; } /*! Identifies if a media resource is null. Returns true if the resource is null, and false otherwise. */ bool QMediaResource::isNull() const { return values.isEmpty(); } /*! Returns the URI of a media resource. */ QUrl QMediaResource::uri() const { return qvariant_cast<QUrl>(values.value(Uri)); } /*! Returns the MIME type of a media resource. This may be null if the MIME type is unknown. */ QString QMediaResource::mimeType() const { return qvariant_cast<QString>(values.value(MimeType)); } /*! Returns the language of a media resource as an ISO 639-2 code. This may be null if the language is unknown. */ QString QMediaResource::language() const { return qvariant_cast<QString>(values.value(Language)); } /*! Sets the \a language of a media resource. */ void QMediaResource::setLanguage(const QString &language) { if (!language.isNull()) values.insert(Language, language); else values.remove(Language); } /*! Returns the audio codec of a media resource. This may be null if the media resource does not contain an audio stream, or the codec is unknown. */ QString QMediaResource::audioCodec() const { return qvariant_cast<QString>(values.value(AudioCodec)); } /*! Sets the audio \a codec of a media resource. */ void QMediaResource::setAudioCodec(const QString &codec) { if (!codec.isNull()) values.insert(AudioCodec, codec); else values.remove(AudioCodec); } /*! Returns the video codec of a media resource. This may be null if the media resource does not contain a video stream, or the codec is unknonwn. */ QString QMediaResource::videoCodec() const { return qvariant_cast<QString>(values.value(VideoCodec)); } /*! Sets the video \a codec of media resource. */ void QMediaResource::setVideoCodec(const QString &codec) { if (!codec.isNull()) values.insert(VideoCodec, codec); else values.remove(VideoCodec); } /*! Returns the size in bytes of a media resource. This may be zero if the size is unknown. */ qint64 QMediaResource::size() const { return qvariant_cast<qint64>(values.value(Size)); } /*! Sets the \a size in bytes of a media resource. */ void QMediaResource::setSize(const qint64 size) { if (size != 0) values.insert(Size, size); else values.remove(Size); } /*! Returns the duration in milliseconds of a media resource. This may be zero if the duration is unknown, or the resource has no explicit duration (i.e. the resource is an image, or a live stream). */ qint64 QMediaResource::duration() const { return qvariant_cast<qint64>(values.value(Duration)); } /*! Sets the \a duration in milliseconds of a media resource. */ void QMediaResource::setDuration(qint64 duration) { if (duration != 0) values.insert(Duration, duration); else values.remove(Duration); } /*! Returns the bit rate in bits per second of a media resource's audio stream. This may be zero if the bit rate is unknown, or the resource contains no audio stream. */ int QMediaResource::audioBitRate() const { return values.value(AudioBitRate).toInt(); } /*! Sets the bit \a rate in bits per second of a media resource's video stream. */ void QMediaResource::setAudioBitRate(int rate) { if (rate != 0) values.insert(AudioBitRate, rate); else values.remove(AudioBitRate); } /*! Returns the audio sample size in bits per sample of a media resource. This may return zero if the sample size is unknown, or the resource contains no audio stream. */ int QMediaResource::sampleSize() const { return qvariant_cast<int>(values.value(SampleSize)); } /*! Sets the audio sample \a size of a media resource. */ void QMediaResource::setSampleSize(int size) { if (size != 0) values.insert(SampleSize, size); else values.remove(SampleSize); } /*! Returns the audio sample frequency of a media resource. This may be zero if the sample size is unknown, or the resource contains no audio stream. */ int QMediaResource::frequency() const { return qvariant_cast<int>(values.value(Frequency)); } /*! Sets the audio sample \a frequency of a media resource. */ void QMediaResource::setFrequency(int frequency) { if (frequency != 0) values.insert(Frequency, frequency); else values.remove(Frequency); } /*! Returns the number of audio channels in a media resource. This may be zero if the sample size is unknown, or the resource contains no audio stream. */ int QMediaResource::channels() const { return qvariant_cast<int>(values.value(Channels)); } /*! Sets the number of audio \a channels in a media resource. */ void QMediaResource::setChannels(int channels) { if (channels != 0) values.insert(Channels, channels); else values.remove(Channels); } /*! Returns the bit rate in bits per second of a media resource's video stream. This may be zero if the bit rate is unknown, or the resource contains no video stream. */ int QMediaResource::videoBitRate() const { return values.value(VideoBitRate).toInt(); } /*! Sets the bit \a rate in bits per second of a media resource's video stream. */ void QMediaResource::setVideoBitRate(int rate) { if (rate != 0) values.insert(VideoBitRate, rate); else values.remove(VideoBitRate); } /*! Returns the resolution in pixels of a media resource. This may be null is the resolution is unknown, or the resource contains no pixel data (i.e. the resource is an audio stream. */ QSize QMediaResource::resolution() const { return qvariant_cast<QSize>(values.value(Resolution)); } /*! Sets the \a resolution in pixels of a media resource. */ void QMediaResource::setResolution(const QSize &resolution) { if (resolution.width() != -1 || resolution.height() != -1) values.insert(Resolution, resolution); else values.remove(Resolution); } /*! Sets the \a width and \a height in pixels of a media resource. */ void QMediaResource::setResolution(int width, int height) { if (width != -1 || height != -1) values.insert(Resolution, QSize(width, height)); else values.remove(Resolution); } <commit_msg>Class doc for QMediaResource.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <multimedia/qmediaresource.h> #include <QtCore/qsize.h> #include <QtCore/qurl.h> #include <QtCore/qvariant.h> /*! \class QMediaResource \preliminary \brief The QMediaResource class provides a description of a media resource. A media resource is composed of a \l {uri()}{URI} containing the location of the resource and a set of properties that describe the format of the resource. The properties provide a means to assess a resource without first attempting to load it, and in situations where media be represented by multiple alternative representations provide a means to select the appropriate resource. Media made available by a remote services can often be available in multiple encodings or quality levels, this allows a client to select an appropriate resource based on considerations such as codecs supported, network bandwidth, and display constraints. QMediaResource includes information such as the \l {mimeType()}{MIME type}, \l {audioCodec()}{audio} and \l {videoCodec()}{video} codecs, \l {audioBitRate()}{audio} and \l {videoBitRate()}{video} bit rates, and \l {resolution()}{resolution} so these constraints and others can be evaluated. The only mandatory property of a QMediaResource is the uri(). \sa QMediaContent */ /*! \typedef QMediaResourceList Synonym for \c QList<QMediaResource> */ /*! Constructs a null media resource. */ QMediaResource::QMediaResource() { } /*! Constructs a media resource with the given \a mimeType from a \a uri. */ QMediaResource::QMediaResource(const QUrl &uri, const QString &mimeType) { values.insert(Uri, qVariantFromValue(uri)); values.insert(MimeType, mimeType); } /*! Constructs a copy of a media resource \a other. */ QMediaResource::QMediaResource(const QMediaResource &other) : values(other.values) { } /*! Assigns the value of \a other to a media resource. */ QMediaResource &QMediaResource::operator =(const QMediaResource &other) { values = other.values; return *this; } /*! Destroys a media resource. */ QMediaResource::~QMediaResource() { } /*! Compares a media resource to \a other. Returns true if the resources are identical, and false otherwise. */ bool QMediaResource::operator ==(const QMediaResource &other) const { return values == other.values; } /*! Compares a media resource to \a other. Returns true if they are different, and false otherwise. */ bool QMediaResource::operator !=(const QMediaResource &other) const { return values != other.values; } /*! Identifies if a media resource is null. Returns true if the resource is null, and false otherwise. */ bool QMediaResource::isNull() const { return values.isEmpty(); } /*! Returns the URI of a media resource. */ QUrl QMediaResource::uri() const { return qvariant_cast<QUrl>(values.value(Uri)); } /*! Returns the MIME type of a media resource. This may be null if the MIME type is unknown. */ QString QMediaResource::mimeType() const { return qvariant_cast<QString>(values.value(MimeType)); } /*! Returns the language of a media resource as an ISO 639-2 code. This may be null if the language is unknown. */ QString QMediaResource::language() const { return qvariant_cast<QString>(values.value(Language)); } /*! Sets the \a language of a media resource. */ void QMediaResource::setLanguage(const QString &language) { if (!language.isNull()) values.insert(Language, language); else values.remove(Language); } /*! Returns the audio codec of a media resource. This may be null if the media resource does not contain an audio stream, or the codec is unknown. */ QString QMediaResource::audioCodec() const { return qvariant_cast<QString>(values.value(AudioCodec)); } /*! Sets the audio \a codec of a media resource. */ void QMediaResource::setAudioCodec(const QString &codec) { if (!codec.isNull()) values.insert(AudioCodec, codec); else values.remove(AudioCodec); } /*! Returns the video codec of a media resource. This may be null if the media resource does not contain a video stream, or the codec is unknonwn. */ QString QMediaResource::videoCodec() const { return qvariant_cast<QString>(values.value(VideoCodec)); } /*! Sets the video \a codec of media resource. */ void QMediaResource::setVideoCodec(const QString &codec) { if (!codec.isNull()) values.insert(VideoCodec, codec); else values.remove(VideoCodec); } /*! Returns the size in bytes of a media resource. This may be zero if the size is unknown. */ qint64 QMediaResource::size() const { return qvariant_cast<qint64>(values.value(Size)); } /*! Sets the \a size in bytes of a media resource. */ void QMediaResource::setSize(const qint64 size) { if (size != 0) values.insert(Size, size); else values.remove(Size); } /*! Returns the duration in milliseconds of a media resource. This may be zero if the duration is unknown, or the resource has no explicit duration (i.e. the resource is an image, or a live stream). */ qint64 QMediaResource::duration() const { return qvariant_cast<qint64>(values.value(Duration)); } /*! Sets the \a duration in milliseconds of a media resource. */ void QMediaResource::setDuration(qint64 duration) { if (duration != 0) values.insert(Duration, duration); else values.remove(Duration); } /*! Returns the bit rate in bits per second of a media resource's audio stream. This may be zero if the bit rate is unknown, or the resource contains no audio stream. */ int QMediaResource::audioBitRate() const { return values.value(AudioBitRate).toInt(); } /*! Sets the bit \a rate in bits per second of a media resource's video stream. */ void QMediaResource::setAudioBitRate(int rate) { if (rate != 0) values.insert(AudioBitRate, rate); else values.remove(AudioBitRate); } /*! Returns the audio sample size in bits per sample of a media resource. This may return zero if the sample size is unknown, or the resource contains no audio stream. */ int QMediaResource::sampleSize() const { return qvariant_cast<int>(values.value(SampleSize)); } /*! Sets the audio sample \a size of a media resource. */ void QMediaResource::setSampleSize(int size) { if (size != 0) values.insert(SampleSize, size); else values.remove(SampleSize); } /*! Returns the audio sample frequency of a media resource. This may be zero if the sample size is unknown, or the resource contains no audio stream. */ int QMediaResource::frequency() const { return qvariant_cast<int>(values.value(Frequency)); } /*! Sets the audio sample \a frequency of a media resource. */ void QMediaResource::setFrequency(int frequency) { if (frequency != 0) values.insert(Frequency, frequency); else values.remove(Frequency); } /*! Returns the number of audio channels in a media resource. This may be zero if the sample size is unknown, or the resource contains no audio stream. */ int QMediaResource::channels() const { return qvariant_cast<int>(values.value(Channels)); } /*! Sets the number of audio \a channels in a media resource. */ void QMediaResource::setChannels(int channels) { if (channels != 0) values.insert(Channels, channels); else values.remove(Channels); } /*! Returns the bit rate in bits per second of a media resource's video stream. This may be zero if the bit rate is unknown, or the resource contains no video stream. */ int QMediaResource::videoBitRate() const { return values.value(VideoBitRate).toInt(); } /*! Sets the bit \a rate in bits per second of a media resource's video stream. */ void QMediaResource::setVideoBitRate(int rate) { if (rate != 0) values.insert(VideoBitRate, rate); else values.remove(VideoBitRate); } /*! Returns the resolution in pixels of a media resource. This may be null is the resolution is unknown, or the resource contains no pixel data (i.e. the resource is an audio stream. */ QSize QMediaResource::resolution() const { return qvariant_cast<QSize>(values.value(Resolution)); } /*! Sets the \a resolution in pixels of a media resource. */ void QMediaResource::setResolution(const QSize &resolution) { if (resolution.width() != -1 || resolution.height() != -1) values.insert(Resolution, resolution); else values.remove(Resolution); } /*! Sets the \a width and \a height in pixels of a media resource. */ void QMediaResource::setResolution(int width, int height) { if (width != -1 || height != -1) values.insert(Resolution, QSize(width, height)); else values.remove(Resolution); } <|endoftext|>
<commit_before>/* * C700VST.cpp * Chip700 * * Created by osoumen on 12/10/13. * Copyright 2012 __MyCompanyName__. All rights reserved. * */ #include "C700VST.h" #include <stdio.h> AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { return new C700VST(audioMaster); } //----------------------------------------------------------------------------------------- C700VST::C700VST(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, NUM_PRESETS, kNumberOfParameters) { mEfx = new C700Kernel(); mEfx->SetPropertyNotifyFunc(PropertyNotifyFunc, this); mEfx->SetParameterSetFunc(ParameterSetFunc, this); //setProgram(0); mCurrentPreset = 0; if (audioMaster) { setNumInputs(0); // no inputs setNumOutputs(NUM_OUTPUTS); // canProcessReplacing(); isSynth(); //programsAreChunks(true); setUniqueID(CCONST ('C', '7', '0', '0')); } //l̐ݒ for ( int i=0; i<kNumberOfParameters; i++ ) { setParameter(i, shrinkParam(i, C700Kernel::GetParameterDefault(i)) ); } suspend(); // pChunk= new unsigned char[32*1024]; mEditor = new C700Edit(this); editor = mEditor; efxAcc = new EfxAccess(this); mEditor->SetEfxAccess(efxAcc); // if(!editor){ // oome = true; // } } //----------------------------------------------------------------------------------------- C700VST::~C700VST() { delete efxAcc; delete mEfx; } //----------------------------------------------------------------------------- float C700VST::expandParam( int index, float value ) { return (value * (C700Kernel::GetParameterMax(index) - C700Kernel::GetParameterMin(index)) + C700Kernel::GetParameterMin(index)); } //----------------------------------------------------------------------------- float C700VST::shrinkParam( int index, float value ) { return (value - C700Kernel::GetParameterMin(index)) / (C700Kernel::GetParameterMax(index) - C700Kernel::GetParameterMin(index)); } //----------------------------------------------------------------------------- void C700VST::PropertyNotifyFunc(int propID, void* userData) { C700VST *This = reinterpret_cast<C700VST*> (userData); if ( propID == kAudioUnitCustomProperty_ProgramName ) { const char *pgname; pgname = This->mEfx->GetProgramName(); if ( pgname ) { This->mEditor->SetProgramName(pgname); } } else if ( propID == kAudioUnitCustomProperty_BRRData ) { const BRRData *brr; brr = This->mEfx->GetBRRData(); if ( brr ) { This->mEditor->SetBRRData(brr); } } else { float value = This->mEfx->GetPropertyValue(propID); This->mEditor->setParameter(propID, value); } } //----------------------------------------------------------------------------- void C700VST::ParameterSetFunc(int paramID, float value, void* userData) { C700VST *This = reinterpret_cast<C700VST*> (userData); This->setParameter(paramID, This->shrinkParam(paramID, value)); } //----------------------------------------------------------------------------------------- void C700VST::open() { AudioEffectX::open(); } //----------------------------------------------------------------------------------------- void C700VST::close() { AudioEffectX::close(); } //----------------------------------------------------------------------------------------- void C700VST::suspend() { AudioEffectX::suspend(); } //----------------------------------------------------------------------------------------- void C700VST::resume() { AudioEffectX::resume(); } //------------------------------------------------------------------------ VstIntPtr C700VST::vendorSpecific(VstInt32 lArg1, VstIntPtr lArg2, void* ptrArg, float floatArg) { //MouseWhell Enable if (editor && lArg1 == CCONST('s','t','C','A') && lArg2 == CCONST('W','h','e','e')) { return editor->onWheel (floatArg) == true ? 1 : 0; } else { return AudioEffectX::vendorSpecific (lArg1, lArg2, ptrArg, floatArg); } } //----------------------------------------------------------------------------------------- void C700VST::setProgram(VstInt32 program) { #ifdef DEBUG DebugPrint("C700VST::setProgram %d",program); #endif mEfx->SelectPreset(program); mCurrentPreset = program; } //----------------------------------------------------------------------------------------- void C700VST::setProgramName(char *name) { } //----------------------------------------------------------------------------------------- void C700VST::getProgramName(char *name) { strncpy(name, mEfx->GetPresetName(mCurrentPreset), kVstMaxProgNameLen-1); } //----------------------------------------------------------------------------------------- void C700VST::getParameterLabel(VstInt32 index, char *label) { #if DEBUG DebugPrint("exec C700VST::getParamaeterLabel"); #endif strncpy(label, mEfx->GetParameterName(index), kVstMaxParamStrLen-1); } //----------------------------------------------------------------------------------------- void C700VST::getParameterDisplay(VstInt32 index, char *text) { #if DEBUG DebugPrint("exec C700VST::getParamaeterDisplay"); #endif snprintf(text, kVstMaxParamStrLen-1, "%f", mEfx->GetParameter(index) ); } //----------------------------------------------------------------------------------------- void C700VST::getParameterName(VstInt32 index, char *label) { #if DEBUG DebugPrint("exec C700VST::getParamaeterName TblLabel[%d]=%s",index,label); #endif strncpy(label, mEfx->GetParameterName(index), kVstMaxParamStrLen-1); } //----------------------------------------------------------------------------------------- void C700VST::setParameter(VstInt32 index, float value) { #if DEBUG DebugPrint("exec C700VST::setParamaeter index=%d value=%f",index,value); #endif float realValue = expandParam(index, value); mEfx->SetParameter(index, realValue); if (editor) { ((AEffGUIEditor*)editor)->setParameter(index, realValue); } } //----------------------------------------------------------------------------------------- float C700VST::getParameter(VstInt32 index) { #if DEBUG DebugPrint("exec C700VST::getParamaeter"); #endif return shrinkParam(index, mEfx->GetParameter(index)); } //----------------------------------------------------------------------------------------- bool C700VST::getOutputProperties(VstInt32 index, VstPinProperties* properties) { #if DEBUG DebugPrint("exec C700VST::getOutputProperties %d ",index); #endif if (index < NUM_OUTPUTS) { sprintf (properties->label, "C700 %1d", index + 1); properties->flags = kVstPinIsActive; if (index < 2) properties->flags |= kVstPinIsStereo; // test, make channel 1+2 stereo return true; } return false; } //----------------------------------------------------------------------------------------- bool C700VST::copyProgram(long destination) { return false; } //----------------------------------------------------------------------------------------- bool C700VST::getEffectName(char* name) { strcpy (name, "C700VST"); return true; } //----------------------------------------------------------------------------------------- bool C700VST::getVendorString(char* text) { strcpy (text, "osoumen"); return true; } //----------------------------------------------------------------------------------------- bool C700VST::getProductString(char* text) { strcpy (text, "C700"); return true; } //----------------------------------------------------------------------------------------- VstInt32 C700VST::canDo(char* text) { #if DEBUG DebugPrint("exec VOPM::canDo [%s] ",text); #endif if (!strcmp (text, "receiveVstEvents")) { return 1; } if (!strcmp (text, "receiveVstMidiEvent")) { return 1; } //if(!strcmp(text, "midiProgramNames")) // return 1; return -1; // explicitly can't do; 0 => don't know } //----------------------------------------------------------------------------------------- VstInt32 C700VST::getChunk(void** data, bool isPreset) { return 0; } //----------------------------------------------------------------------------------------- VstInt32 C700VST::setChunk(void* data, VstInt32 byteSize, bool isPreset) { return 0; } //----------------------------------------------------------------------------------------- void C700VST::setSampleRate(float sampleRate) { AudioEffectX::setSampleRate(sampleRate); mEfx->SetSampleRate(sampleRate); } //----------------------------------------------------------------------------------------- void C700VST::setBlockSize(long blockSize) { AudioEffectX::setBlockSize(blockSize); // you may need to have to do something here... } //----------------------------------------------------------------------------------------- void C700VST::processReplacing(float **inputs, float **outputs, int sampleFrames) { mEfx->Render(sampleFrames, outputs); } //----------------------------------------------------------------------------------------- VstInt32 C700VST::processEvents(VstEvents* ev) { for (long i = 0; i < ev->numEvents; i++) { if ((ev->events[i])->type != kVstMidiType) continue; VstMidiEvent* event = (VstMidiEvent*)ev->events[i]; char* midiData = event->midiData; int inFrames = event->deltaFrames; unsigned char status = midiData[0] & 0xf0; // ignoring channel char MidiCh = midiData[0] & 0x0f; char note = midiData[1] & 0x7f; char velocity = midiData[2] & 0x7f; /* #if DEBUG DebugPrint("VOPMproc::ProcessEvents Message[%02x %02x %02x]", midiData[0],midiData[1],midiData[2]); #endif */ switch (status) { case 0x80: mEfx->HandleNoteOff(MidiCh, note, note+MidiCh*256, inFrames); break; case 0x90: if (velocity==0) { mEfx->HandleNoteOff(MidiCh, note, note+MidiCh*256, inFrames); } else { mEfx->HandleNoteOn(MidiCh, note, velocity, note+MidiCh*256, inFrames); } break; case 0xb0: switch (note) { case 0x01://Modulation Wheel mEfx->HandleControlChange(MidiCh, note, velocity, inFrames); break; case 0x78://Force off mEfx->HandleAllSoundOff(MidiCh, inFrames); break; case 0x7B://All Note Off mEfx->HandleAllNotesOff(MidiCh, inFrames); break; case 0x7E://Mono case 0x7F://Poly default: ; } break; case 0xc0: mEfx->HandleProgramChange(MidiCh, note, inFrames); break; case 0xe0: mEfx->HandlePitchBend(MidiCh, note, velocity, inFrames); break; } } return 1; } <commit_msg>XMSNESテキスト、totalramが反映されないのを修正<commit_after>/* * C700VST.cpp * Chip700 * * Created by osoumen on 12/10/13. * Copyright 2012 __MyCompanyName__. All rights reserved. * */ #include "C700VST.h" #include <stdio.h> AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { return new C700VST(audioMaster); } //----------------------------------------------------------------------------------------- C700VST::C700VST(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, NUM_PRESETS, kNumberOfParameters) { mEfx = new C700Kernel(); mEfx->SetPropertyNotifyFunc(PropertyNotifyFunc, this); mEfx->SetParameterSetFunc(ParameterSetFunc, this); //setProgram(0); mCurrentPreset = 0; if (audioMaster) { setNumInputs(0); // no inputs setNumOutputs(NUM_OUTPUTS); // canProcessReplacing(); isSynth(); //programsAreChunks(true); setUniqueID(CCONST ('C', '7', '0', '0')); } suspend(); // pChunk= new unsigned char[32*1024]; mEditor = new C700Edit(this); editor = mEditor; efxAcc = new EfxAccess(this); mEditor->SetEfxAccess(efxAcc); //l̐ݒ for ( int i=0; i<kNumberOfParameters; i++ ) { setParameter(i, shrinkParam(i, C700Kernel::GetParameterDefault(i)) ); } // if(!editor){ // oome = true; // } } //----------------------------------------------------------------------------------------- C700VST::~C700VST() { delete efxAcc; delete mEfx; } //----------------------------------------------------------------------------- float C700VST::expandParam( int index, float value ) { return (value * (C700Kernel::GetParameterMax(index) - C700Kernel::GetParameterMin(index)) + C700Kernel::GetParameterMin(index)); } //----------------------------------------------------------------------------- float C700VST::shrinkParam( int index, float value ) { return (value - C700Kernel::GetParameterMin(index)) / (C700Kernel::GetParameterMax(index) - C700Kernel::GetParameterMin(index)); } //----------------------------------------------------------------------------- void C700VST::PropertyNotifyFunc(int propID, void* userData) { C700VST *This = reinterpret_cast<C700VST*> (userData); if ( propID == kAudioUnitCustomProperty_ProgramName ) { const char *pgname; pgname = This->mEfx->GetProgramName(); if ( pgname ) { This->mEditor->SetProgramName(pgname); } } else if ( propID == kAudioUnitCustomProperty_BRRData ) { const BRRData *brr; brr = This->mEfx->GetBRRData(); if ( brr ) { This->mEditor->SetBRRData(brr); } } else { float value = This->mEfx->GetPropertyValue(propID); This->mEditor->setParameter(propID, value); } } //----------------------------------------------------------------------------- void C700VST::ParameterSetFunc(int paramID, float value, void* userData) { C700VST *This = reinterpret_cast<C700VST*> (userData); This->setParameter(paramID, This->shrinkParam(paramID, value)); } //----------------------------------------------------------------------------------------- void C700VST::open() { AudioEffectX::open(); } //----------------------------------------------------------------------------------------- void C700VST::close() { AudioEffectX::close(); } //----------------------------------------------------------------------------------------- void C700VST::suspend() { AudioEffectX::suspend(); } //----------------------------------------------------------------------------------------- void C700VST::resume() { AudioEffectX::resume(); } //------------------------------------------------------------------------ VstIntPtr C700VST::vendorSpecific(VstInt32 lArg1, VstIntPtr lArg2, void* ptrArg, float floatArg) { //MouseWhell Enable if (editor && lArg1 == CCONST('s','t','C','A') && lArg2 == CCONST('W','h','e','e')) { return editor->onWheel (floatArg) == true ? 1 : 0; } else { return AudioEffectX::vendorSpecific (lArg1, lArg2, ptrArg, floatArg); } } //----------------------------------------------------------------------------------------- void C700VST::setProgram(VstInt32 program) { #ifdef DEBUG DebugPrint("C700VST::setProgram %d",program); #endif mEfx->SelectPreset(program); mCurrentPreset = program; } //----------------------------------------------------------------------------------------- void C700VST::setProgramName(char *name) { } //----------------------------------------------------------------------------------------- void C700VST::getProgramName(char *name) { strncpy(name, mEfx->GetPresetName(mCurrentPreset), kVstMaxProgNameLen-1); } //----------------------------------------------------------------------------------------- void C700VST::getParameterLabel(VstInt32 index, char *label) { #if DEBUG DebugPrint("exec C700VST::getParamaeterLabel"); #endif strncpy(label, mEfx->GetParameterName(index), kVstMaxParamStrLen-1); } //----------------------------------------------------------------------------------------- void C700VST::getParameterDisplay(VstInt32 index, char *text) { #if DEBUG DebugPrint("exec C700VST::getParamaeterDisplay"); #endif snprintf(text, kVstMaxParamStrLen-1, "%f", mEfx->GetParameter(index) ); } //----------------------------------------------------------------------------------------- void C700VST::getParameterName(VstInt32 index, char *label) { #if DEBUG DebugPrint("exec C700VST::getParamaeterName TblLabel[%d]=%s",index,label); #endif strncpy(label, mEfx->GetParameterName(index), kVstMaxParamStrLen-1); } //----------------------------------------------------------------------------------------- void C700VST::setParameter(VstInt32 index, float value) { #if DEBUG DebugPrint("exec C700VST::setParamaeter index=%d value=%f",index,value); #endif float realValue = expandParam(index, value); mEfx->SetParameter(index, realValue); switch ( index ) { case kParam_echodelay: PropertyNotifyFunc(kAudioUnitCustomProperty_TotalRAM, this); case kParam_echovol_L: case kParam_echovol_R: case kParam_echoFB: case kParam_fir0: case kParam_fir1: case kParam_fir2: case kParam_fir3: case kParam_fir4: case kParam_fir5: case kParam_fir6: case kParam_fir7: PropertyNotifyFunc(kAudioUnitCustomProperty_Band1, this); break; } if (editor) { ((AEffGUIEditor*)editor)->setParameter(index, realValue); } } //----------------------------------------------------------------------------------------- float C700VST::getParameter(VstInt32 index) { #if DEBUG DebugPrint("exec C700VST::getParamaeter"); #endif return shrinkParam(index, mEfx->GetParameter(index)); } //----------------------------------------------------------------------------------------- bool C700VST::getOutputProperties(VstInt32 index, VstPinProperties* properties) { #if DEBUG DebugPrint("exec C700VST::getOutputProperties %d ",index); #endif if (index < NUM_OUTPUTS) { sprintf (properties->label, "C700 %1d", index + 1); properties->flags = kVstPinIsActive; if (index < 2) properties->flags |= kVstPinIsStereo; // test, make channel 1+2 stereo return true; } return false; } //----------------------------------------------------------------------------------------- bool C700VST::copyProgram(long destination) { return false; } //----------------------------------------------------------------------------------------- bool C700VST::getEffectName(char* name) { strcpy (name, "C700VST"); return true; } //----------------------------------------------------------------------------------------- bool C700VST::getVendorString(char* text) { strcpy (text, "osoumen"); return true; } //----------------------------------------------------------------------------------------- bool C700VST::getProductString(char* text) { strcpy (text, "C700"); return true; } //----------------------------------------------------------------------------------------- VstInt32 C700VST::canDo(char* text) { #if DEBUG DebugPrint("exec VOPM::canDo [%s] ",text); #endif if (!strcmp (text, "receiveVstEvents")) { return 1; } if (!strcmp (text, "receiveVstMidiEvent")) { return 1; } //if(!strcmp(text, "midiProgramNames")) // return 1; return -1; // explicitly can't do; 0 => don't know } //----------------------------------------------------------------------------------------- VstInt32 C700VST::getChunk(void** data, bool isPreset) { return 0; } //----------------------------------------------------------------------------------------- VstInt32 C700VST::setChunk(void* data, VstInt32 byteSize, bool isPreset) { return 0; } //----------------------------------------------------------------------------------------- void C700VST::setSampleRate(float sampleRate) { AudioEffectX::setSampleRate(sampleRate); mEfx->SetSampleRate(sampleRate); } //----------------------------------------------------------------------------------------- void C700VST::setBlockSize(long blockSize) { AudioEffectX::setBlockSize(blockSize); // you may need to have to do something here... } //----------------------------------------------------------------------------------------- void C700VST::processReplacing(float **inputs, float **outputs, int sampleFrames) { mEfx->Render(sampleFrames, outputs); } //----------------------------------------------------------------------------------------- VstInt32 C700VST::processEvents(VstEvents* ev) { for (long i = 0; i < ev->numEvents; i++) { if ((ev->events[i])->type != kVstMidiType) continue; VstMidiEvent* event = (VstMidiEvent*)ev->events[i]; char* midiData = event->midiData; int inFrames = event->deltaFrames; unsigned char status = midiData[0] & 0xf0; // ignoring channel char MidiCh = midiData[0] & 0x0f; char note = midiData[1] & 0x7f; char velocity = midiData[2] & 0x7f; /* #if DEBUG DebugPrint("VOPMproc::ProcessEvents Message[%02x %02x %02x]", midiData[0],midiData[1],midiData[2]); #endif */ switch (status) { case 0x80: mEfx->HandleNoteOff(MidiCh, note, note+MidiCh*256, inFrames); break; case 0x90: if (velocity==0) { mEfx->HandleNoteOff(MidiCh, note, note+MidiCh*256, inFrames); } else { mEfx->HandleNoteOn(MidiCh, note, velocity, note+MidiCh*256, inFrames); } break; case 0xb0: switch (note) { case 0x01://Modulation Wheel mEfx->HandleControlChange(MidiCh, note, velocity, inFrames); break; case 0x78://Force off mEfx->HandleAllSoundOff(MidiCh, inFrames); break; case 0x7B://All Note Off mEfx->HandleAllNotesOff(MidiCh, inFrames); break; case 0x7E://Mono case 0x7F://Poly default: ; } break; case 0xc0: mEfx->HandleProgramChange(MidiCh, note, inFrames); break; case 0xe0: mEfx->HandlePitchBend(MidiCh, note, velocity, inFrames); break; } } return 1; } <|endoftext|>
<commit_before>// CA4.cpp : Defines the entry point for the console application. // #include "stdafx.h" const int cbCodeId = 0x3EB; const int btnDecompId = 0x3EC; const int btnCancelId = 2; const SIZE_T fbRecordSize = 0xB4; const LPVOID fileObjectAddr = (LPVOID)0x4101d8; const SIZE_T fileObjectSize = 0x3A4; const bool g_dumpRecords = false; const bool g_doPackage = true; const bool g_use7z = true; struct FileObject { LPVOID vtable; DWORD d2; char error[0x100]; char scode[0x20]; //0x108 DWORD type; //0x128 DWORD d3; DWORD d4; DWORD maskmode; DWORD markettype; // 0x138 char filename[0x100]; HANDLE dataheap; // 0x23c LPVOID filedata; DWORD totalsize; DWORD datasize; HANDLE codeheap; LPVOID codetable; //0x250 DWORD tablesize; DWORD codesize; DWORD d10; HANDLE decodeheap; //0x260 LPVOID decodedata; DWORD decodesize; DWORD decodebufsize; BYTE b270_256[0xb4]; // 0x270 BYTE b324_40[0x28]; // 0x324 BYTE b34c_80[0x50]; // 0x34c DWORD d12; DWORD d13; // 0x3a0 }; struct RecordObject { DWORD dt; DWORD time; DWORD close; DWORD volumeLow; DWORD volumeHigh; DWORD amountLow; DWORD amountHigh; DWORD transactions; DWORD accVolumeLow; DWORD accVolumeHigh; DWORD accAmountLow; DWORD accAmountHigh; DWORD flag; DWORD prices[10]; DWORD volumes[20]; DWORD reservedLow; DWORD reservedHigh; }; const char *_7zExe = "\"c:\\Program Files\\7-Zip\\7z.exe\" a -sdel output.7z @listfile"; const char *_7zipExe = "\"c:\\Program Files\\7-Zip\\7z.exe\" a -sdel output.zip @listfile"; void Start7z() { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessA(NULL, g_use7z ? (LPSTR)_7zExe : (LPSTR)_7zipExe, NULL, NULL, FALSE, 0, NULL, NULL, // current directory &si, &pi)) { printf("CreateProcess failed (%d)\n", GetLastError()); } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } #define MAKELONGLONG(l, h) ((LONGLONG)(l & 0xffffffff) | (LONGLONG)h << 32) void DumpRecords(BYTE *pData, int records) { RecordObject* pRec = (RecordObject *)pData; DWORD accTxn = 0; LONGLONG llReserved = MAKELONGLONG(pRec[0].reservedLow, pRec[0].reservedHigh); for (int i = 0; i < records; i++) { DWORD txn = pRec[i].transactions; if (MAKELONGLONG(pRec[i].reservedLow, pRec[i].reservedHigh) != llReserved) { txn = pRec[i].transactions - accTxn; llReserved = MAKELONGLONG(pRec[i].reservedLow, pRec[i].reservedHigh); accTxn = pRec[i].transactions; } else { accTxn += pRec[i].transactions; } printf("%u %06u %u %u %I64u %I64u\n", pRec[i].dt, pRec[i].time, pRec[i].close, txn, MAKELONGLONG(pRec[i].amountLow, pRec[i].amountHigh), MAKELONGLONG(pRec[i].volumeLow, pRec[i].volumeHigh)); } } bool IsValidCode(char *code, size_t len) { if (len != 6) { return false; } for (size_t i = 0; i < len; i++) { if (code[i] > '9' || code[i] < '0') { return false; } } return true; } int _tmain_message(int argc, _TCHAR* argv[]) { if (argc != 3) { printf("specify a file name.\n"); return 0; } if (!argv[2][0] || argv[2][1]) { printf("specify a market marker (h/s).\n"); return 0; } char fn[0x100]; ZeroMemory(fn, sizeof(fn)); strcpy_s(fn, sizeof(fn), argv[1]); FILE *paramfp = NULL; int err = fopen_s(&paramfp, "dzhtest.exe.param", "rb+"); if (!err) { fseek(paramfp, 0, FILE_BEGIN); fwrite(fn, sizeof(char), sizeof(fn), paramfp); fseek(paramfp, 0x110, FILE_BEGIN); if (argv[2][0] == 'h') { // sh 0x1e fwrite("\x1e", sizeof(char), 1, paramfp); } else if (argv[2][0] == 's') { // sz 0x25 fwrite("\x25", sizeof(char), 1, paramfp); } fclose(paramfp); } else { printf("failed to open param file.\n"); return -1; } GetCurrentDirectoryA(sizeof(fn), fn); strcat_s(fn, sizeof(fn), "\\dzhtest.exe"); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessA(NULL, fn, NULL, NULL, FALSE, 0, NULL, NULL, // current directory &si, &pi)) { printf("CreateProcess failed (%d)\n", GetLastError()); return -2; } // wait for dzhtest bootstrap WaitForSingleObject(pi.hProcess, 1500); HWND target = FindWindowA(NULL, "dzhtest"); if (!target) { // if it's still not running, give up printf("target window not found!\n"); return -3; } HWND btnWnd = GetDlgItem(target, btnDecompId); HWND cbWnd = GetDlgItem(target, cbCodeId); LRESULT r = SendMessage(cbWnd, CB_GETCOUNT, 0, 0); char scodesel[32]; char *fl = new char[r * (sizeof(scodesel) + 1)]; char *flpointer = fl; LPVOID fp; FileObject fo; SIZE_T bytesRead; ReadProcessMemory(pi.hProcess, (LPCVOID)fileObjectAddr, (LPVOID)&fp, sizeof(fp), &bytesRead); ReadProcessMemory(pi.hProcess, fp, &fo, fileObjectSize, &bytesRead); LPVOID initial = fo.decodedata; for (int i = 0; i < r; i++) { LRESULT re = SendMessage(cbWnd, CB_SETCURSEL, (WPARAM)i, 0); re = SendMessage(cbWnd, WM_GETTEXT, (WPARAM)sizeof(scodesel), (LPARAM)scodesel); if (!IsValidCode(scodesel, re)) { printf("invalid code %s\n", scodesel); continue; } re = SendMessage(target, WM_COMMAND, MAKEWPARAM(btnDecompId, BN_CLICKED), (LPARAM)btnWnd); ReadProcessMemory(pi.hProcess, fp, &fo, fileObjectSize, &bytesRead); if (initial && fo.decodedata != initial) { printf("decoded data buffer changed! %p %p", initial, fo.decodedata); } if (!fo.decodesize) { continue; } BYTE *pData = new BYTE[fo.decodesize]; ReadProcessMemory(pi.hProcess, fo.decodedata, pData, fo.decodesize, &bytesRead); size_t cnt = sprintf_s(fn, sizeof(scodesel), "%d%s", *(DWORD *)pData, scodesel); FILE *outfp = NULL; err = fopen_s(&outfp, fn, "wb"); if (!err) { fwrite(pData, 1, bytesRead, outfp); fclose(outfp); strncpy_s(flpointer, cnt + 1, fn, cnt); flpointer[cnt] = '\r'; flpointer = flpointer + cnt + 1; } else { printf("failed to open [%s].\n", fn); } if (bytesRead % fbRecordSize == 0) { if (g_dumpRecords) { DumpRecords(pData, bytesRead / fbRecordSize); } } else { printf("probably wrong buffer length!\n"); } delete pData; } FILE *outflist = NULL; err = fopen_s(&outflist, "listfile", "wb"); if (!err) { fwrite(fl, sizeof(char), flpointer - fl, outflist); fclose(outflist); } else { printf("failed to open [listfile].\n"); } delete fl; SendMessage(target, WM_COMMAND, MAKEWPARAM(btnCancelId, BN_CLICKED), (LPARAM)GetDlgItem(target, btnCancelId)); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if (g_doPackage) { Start7z(); } return 0; } int _tmain_inject(int argc, _TCHAR* argv[]) { if (argc != 3) { return -1; } HANDLE processHandle; HANDLE threadHandle; HMODULE dllHandle; DWORD processID; FARPROC loadLibraryAddress; LPVOID baseAddress; processID = (DWORD)_ttol(argv[1]); processHandle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,processID); if(processHandle == NULL) { printf("Error unable to open process. Error code: %d", GetLastError()); return -2; } printf("Process handle %d is ready",processID); dllHandle = GetModuleHandle("Kernel32"); if(dllHandle == NULL) { printf("Error unable to allocate kernel32 handle..Error code: %d. Press any key to exit...",GetLastError()); } printf("kernel32 handle is ready\n"); loadLibraryAddress = GetProcAddress(dllHandle,"LoadLibraryA"); if(loadLibraryAddress == NULL) { printf("Cannot get LoadLibraryA() address. Error code: %d. Press any key to exit",GetLastError()); return -2; } printf("LoadLibrary() address is ready\n"); baseAddress = VirtualAllocEx( processHandle, NULL, 2048, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE); if(baseAddress == NULL) { printf("Error unable to alocate memmory in remote process. Error code: %d. Press any key to exit", GetLastError()); return 0; } printf("Memory allocation succeeded\n"); BOOL isSucceeded = WriteProcessMemory( processHandle, baseAddress, argv[2], strlen(argv[2])+1, NULL); if(isSucceeded == 0) { printf("Error unable to write memory . Error code: %d Press any key to exit...",GetLastError()); return 0; } printf("Argument has been written\n"); threadHandle = CreateRemoteThread( processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, baseAddress, NULL, 0); if(threadHandle != NULL) { printf("Remote thread has been created\n"); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { // return _tmain_inject(argc, argv); return _tmain_message(argc, argv); } <commit_msg>output decode error<commit_after>// CA4.cpp : Defines the entry point for the console application. // #include "stdafx.h" const int cbCodeId = 0x3EB; const int btnDecompId = 0x3EC; const int btnCancelId = 2; const SIZE_T fbRecordSize = 0xB4; const LPVOID fileObjectAddr = (LPVOID)0x4101d8; const SIZE_T fileObjectSize = 0x3A4; const bool g_dumpRecords = false; const bool g_doPackage = true; const bool g_use7z = true; struct FileObject { LPVOID vtable; DWORD d2; char error[0x100]; char scode[0x20]; //0x108 DWORD type; //0x128 DWORD d3; DWORD d4; DWORD maskmode; DWORD markettype; // 0x138 char filename[0x100]; HANDLE dataheap; // 0x23c LPVOID filedata; DWORD totalsize; DWORD datasize; HANDLE codeheap; LPVOID codetable; //0x250 DWORD tablesize; DWORD codesize; DWORD d10; HANDLE decodeheap; //0x260 LPVOID decodedata; DWORD decodesize; DWORD decodebufsize; BYTE b270_256[0xb4]; // 0x270 BYTE b324_40[0x28]; // 0x324 BYTE b34c_80[0x50]; // 0x34c DWORD d12; DWORD d13; // 0x3a0 }; struct RecordObject { DWORD dt; DWORD time; DWORD close; DWORD volumeLow; DWORD volumeHigh; DWORD amountLow; DWORD amountHigh; DWORD transactions; DWORD accVolumeLow; DWORD accVolumeHigh; DWORD accAmountLow; DWORD accAmountHigh; DWORD flag; DWORD prices[10]; DWORD volumes[20]; DWORD reservedLow; DWORD reservedHigh; }; const char *_7zExe = "\"c:\\Program Files\\7-Zip\\7z.exe\" a -sdel output.7z @listfile"; const char *_7zipExe = "\"c:\\Program Files\\7-Zip\\7z.exe\" a -sdel output.zip @listfile"; void Start7z() { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessA(NULL, g_use7z ? (LPSTR)_7zExe : (LPSTR)_7zipExe, NULL, NULL, FALSE, 0, NULL, NULL, // current directory &si, &pi)) { printf("CreateProcess failed (%d)\n", GetLastError()); } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } #define MAKELONGLONG(l, h) ((LONGLONG)(l & 0xffffffff) | (LONGLONG)h << 32) void DumpRecords(BYTE *pData, int records) { RecordObject* pRec = (RecordObject *)pData; DWORD accTxn = 0; LONGLONG llReserved = MAKELONGLONG(pRec[0].reservedLow, pRec[0].reservedHigh); for (int i = 0; i < records; i++) { DWORD txn = pRec[i].transactions; if (MAKELONGLONG(pRec[i].reservedLow, pRec[i].reservedHigh) != llReserved) { txn = pRec[i].transactions - accTxn; llReserved = MAKELONGLONG(pRec[i].reservedLow, pRec[i].reservedHigh); accTxn = pRec[i].transactions; } else { accTxn += pRec[i].transactions; } printf("%u %06u %u %u %I64u %I64u\n", pRec[i].dt, pRec[i].time, pRec[i].close, txn, MAKELONGLONG(pRec[i].amountLow, pRec[i].amountHigh), MAKELONGLONG(pRec[i].volumeLow, pRec[i].volumeHigh)); } } bool IsValidCode(char *code, size_t len) { if (len != 6) { return false; } for (size_t i = 0; i < len; i++) { if (code[i] > '9' || code[i] < '0') { return false; } } return true; } int _tmain_message(int argc, _TCHAR* argv[]) { if (argc != 3) { printf("specify a file name.\n"); return 0; } if (!argv[2][0] || argv[2][1]) { printf("specify a market marker (h/s).\n"); return 0; } char fn[0x100]; ZeroMemory(fn, sizeof(fn)); strcpy_s(fn, sizeof(fn), argv[1]); FILE *paramfp = NULL; int err = fopen_s(&paramfp, "dzhtest.exe.param", "rb+"); if (!err) { fseek(paramfp, 0, FILE_BEGIN); fwrite(fn, sizeof(char), sizeof(fn), paramfp); fseek(paramfp, 0x110, FILE_BEGIN); if (argv[2][0] == 'h') { // sh 0x1e fwrite("\x1e", sizeof(char), 1, paramfp); } else if (argv[2][0] == 's') { // sz 0x25 fwrite("\x25", sizeof(char), 1, paramfp); } fclose(paramfp); } else { printf("failed to open param file.\n"); return -1; } GetCurrentDirectoryA(sizeof(fn), fn); strcat_s(fn, sizeof(fn), "\\dzhtest.exe"); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); if (!CreateProcessA(NULL, fn, NULL, NULL, FALSE, 0, NULL, NULL, // current directory &si, &pi)) { printf("CreateProcess failed (%d)\n", GetLastError()); return -2; } // wait for dzhtest bootstrap WaitForSingleObject(pi.hProcess, 1500); HWND target = FindWindowA(NULL, "dzhtest"); if (!target) { // if it's still not running, give up printf("target window not found!\n"); return -3; } HWND btnWnd = GetDlgItem(target, btnDecompId); HWND cbWnd = GetDlgItem(target, cbCodeId); LRESULT r = SendMessage(cbWnd, CB_GETCOUNT, 0, 0); char scodesel[32]; char *fl = new char[r * (sizeof(scodesel) + 1)]; char *flpointer = fl; LPVOID fp; FileObject fo; SIZE_T bytesRead; ReadProcessMemory(pi.hProcess, (LPCVOID)fileObjectAddr, (LPVOID)&fp, sizeof(fp), &bytesRead); ReadProcessMemory(pi.hProcess, fp, &fo, fileObjectSize, &bytesRead); LPVOID initial = fo.decodedata; for (int i = 0; i < r; i++) { LRESULT re = SendMessage(cbWnd, CB_SETCURSEL, (WPARAM)i, 0); re = SendMessage(cbWnd, WM_GETTEXT, (WPARAM)sizeof(scodesel), (LPARAM)scodesel); if (!IsValidCode(scodesel, re)) { printf("invalid code %s\n", scodesel); continue; } re = SendMessage(target, WM_COMMAND, MAKEWPARAM(btnDecompId, BN_CLICKED), (LPARAM)btnWnd); ReadProcessMemory(pi.hProcess, fp, &fo, fileObjectSize, &bytesRead); if (initial && fo.decodedata != initial) { printf("decoded data buffer changed! %p %p\n", initial, fo.decodedata); } if (!fo.decodesize) { if (fo.error[0]) { printf("decode [%s] error: %s\n", scodesel, fo.error); } continue; } BYTE *pData = new BYTE[fo.decodesize]; ReadProcessMemory(pi.hProcess, fo.decodedata, pData, fo.decodesize, &bytesRead); size_t cnt = sprintf_s(fn, sizeof(scodesel), "%d%s", *(DWORD *)pData, scodesel); FILE *outfp = NULL; err = fopen_s(&outfp, fn, "wb"); if (!err) { fwrite(pData, 1, bytesRead, outfp); fclose(outfp); strncpy_s(flpointer, cnt + 1, fn, cnt); flpointer[cnt] = '\r'; flpointer = flpointer + cnt + 1; } else { printf("failed to open [%s].\n", fn); } if (bytesRead % fbRecordSize == 0) { if (g_dumpRecords) { DumpRecords(pData, bytesRead / fbRecordSize); } } else { printf("probably wrong buffer length!\n"); } delete pData; } FILE *outflist = NULL; err = fopen_s(&outflist, "listfile", "wb"); if (!err) { fwrite(fl, sizeof(char), flpointer - fl, outflist); fclose(outflist); } else { printf("failed to open [listfile].\n"); } delete fl; SendMessage(target, WM_COMMAND, MAKEWPARAM(btnCancelId, BN_CLICKED), (LPARAM)GetDlgItem(target, btnCancelId)); WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if (g_doPackage) { Start7z(); } return 0; } int _tmain_inject(int argc, _TCHAR* argv[]) { if (argc != 3) { return -1; } HANDLE processHandle; HANDLE threadHandle; HMODULE dllHandle; DWORD processID; FARPROC loadLibraryAddress; LPVOID baseAddress; processID = (DWORD)_ttol(argv[1]); processHandle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,processID); if(processHandle == NULL) { printf("Error unable to open process. Error code: %d", GetLastError()); return -2; } printf("Process handle %d is ready",processID); dllHandle = GetModuleHandle("Kernel32"); if(dllHandle == NULL) { printf("Error unable to allocate kernel32 handle..Error code: %d. Press any key to exit...",GetLastError()); } printf("kernel32 handle is ready\n"); loadLibraryAddress = GetProcAddress(dllHandle,"LoadLibraryA"); if(loadLibraryAddress == NULL) { printf("Cannot get LoadLibraryA() address. Error code: %d. Press any key to exit",GetLastError()); return -2; } printf("LoadLibrary() address is ready\n"); baseAddress = VirtualAllocEx( processHandle, NULL, 2048, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE); if(baseAddress == NULL) { printf("Error unable to alocate memmory in remote process. Error code: %d. Press any key to exit", GetLastError()); return 0; } printf("Memory allocation succeeded\n"); BOOL isSucceeded = WriteProcessMemory( processHandle, baseAddress, argv[2], strlen(argv[2])+1, NULL); if(isSucceeded == 0) { printf("Error unable to write memory . Error code: %d Press any key to exit...",GetLastError()); return 0; } printf("Argument has been written\n"); threadHandle = CreateRemoteThread( processHandle, NULL, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddress, baseAddress, NULL, 0); if(threadHandle != NULL) { printf("Remote thread has been created\n"); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { // return _tmain_inject(argc, argv); return _tmain_message(argc, argv); } <|endoftext|>
<commit_before>/* This file is part of Android File Transfer For Linux. Copyright (C) 2015 Vladimir Menshakov Android File Transfer For Linux is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Android File Transfer For Linux is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Android File Transfer For Linux. If not, see <http://www.gnu.org/licenses/>. */ #include <mtp/ptp/Device.h> #include <mtp/ptp/Response.h> #include <mtp/ptp/Container.h> #include <mtp/ptp/Messages.h> #include <mtp/log.h> #include <usb/Context.h> #include <usb/Device.h> #include <usb/Interface.h> #include <mtp/ptp/OperationRequest.h> #include <mtp/usb/Request.h> #include <stdexcept> namespace mtp { Device::Device(usb::BulkPipePtr pipe): _packeter(pipe) { } SessionPtr Device::OpenSession(u32 sessionId, int timeout) { OperationRequest req(OperationCode::OpenSession, 0, sessionId); Container container(req); _packeter.Write(container.Data, timeout); ByteArray data, response; ResponseType code; _packeter.Read(0, data, code, response, timeout); //HexDump("payload", data); return std::make_shared<Session>(_packeter.GetPipe(), sessionId); } int Device::GetInterfaceStringIndex(usb::DeviceDescriptorPtr desc, u8 number) { static const u16 DT_INTERFACE = 4; ByteArray descData = desc->GetDescriptor(); HexDump("descriptor", descData); size_t offset = 0; while(offset < descData.size()) { u8 len = descData.at(offset + 0); u8 type = descData.at(offset + 1); if (len < 2) throw std::runtime_error("invalid descriptor length"); if (type == DT_INTERFACE && len >= 9 && descData.at(offset + 2) == number) return descData.at(offset + 8); offset += len; } throw std::runtime_error("no interface descriptor found"); } DevicePtr Device::Find() { using namespace mtp; usb::ContextPtr ctx(new usb::Context); for (usb::DeviceDescriptorPtr desc : ctx->GetDevices()) try { usb::DevicePtr device = desc->TryOpen(ctx); if (!device) continue; int confs = desc->GetConfigurationsCount(); //debug("configurations: ", confs); for(int i = 0; i < confs; ++i) { usb::ConfigurationPtr conf = desc->GetConfiguration(i); int interfaces = conf->GetInterfaceCount(); //debug("interfaces: ", interfaces); for(int j = 0; j < interfaces; ++j) { usb::InterfacePtr iface = conf->GetInterface(device, conf, j, 0); usb::InterfaceTokenPtr token = device->ClaimInterface(iface); debug(i, ':', j, "index ", iface->GetIndex(), ", eps ", iface->GetEndpointsCount()); ByteArray data = usb::DeviceRequest(device).GetDescriptor(usb::DescriptorType::String, 0, 0); HexDump("languages", data); if (data.size() < 4 || data[1] != (u8)usb::DescriptorType::String) continue; int interfaceStringIndex = GetInterfaceStringIndex(desc, j); u16 langId = data[2] | ((u16)data[3] << 8); data = usb::DeviceRequest(device).GetDescriptor(usb::DescriptorType::String, interfaceStringIndex, langId); HexDump("interface name", data); if (data.size() < 4 || data[1] != (u8)usb::DescriptorType::String) continue; u8 len = data[0]; InputStream stream(data, 2); std::string name = stream.ReadString((len - 2) / 2); if (name == "MTP") { //device->SetConfiguration(configuration->GetIndex()); usb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface, token); return std::make_shared<Device>(pipe); } if (iface->GetClass() == 6 && iface->GetSubclass() == 1) { usb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface, token); return std::make_shared<Device>(pipe); } } } } catch(const std::exception &ex) { error(stderr, "%s\n", ex.what()); } return nullptr; } } <commit_msg>removed printf remains<commit_after>/* This file is part of Android File Transfer For Linux. Copyright (C) 2015 Vladimir Menshakov Android File Transfer For Linux is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Android File Transfer For Linux is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Android File Transfer For Linux. If not, see <http://www.gnu.org/licenses/>. */ #include <mtp/ptp/Device.h> #include <mtp/ptp/Response.h> #include <mtp/ptp/Container.h> #include <mtp/ptp/Messages.h> #include <mtp/log.h> #include <usb/Context.h> #include <usb/Device.h> #include <usb/Interface.h> #include <mtp/ptp/OperationRequest.h> #include <mtp/usb/Request.h> #include <stdexcept> namespace mtp { Device::Device(usb::BulkPipePtr pipe): _packeter(pipe) { } SessionPtr Device::OpenSession(u32 sessionId, int timeout) { OperationRequest req(OperationCode::OpenSession, 0, sessionId); Container container(req); _packeter.Write(container.Data, timeout); ByteArray data, response; ResponseType code; _packeter.Read(0, data, code, response, timeout); //HexDump("payload", data); return std::make_shared<Session>(_packeter.GetPipe(), sessionId); } int Device::GetInterfaceStringIndex(usb::DeviceDescriptorPtr desc, u8 number) { static const u16 DT_INTERFACE = 4; ByteArray descData = desc->GetDescriptor(); HexDump("descriptor", descData); size_t offset = 0; while(offset < descData.size()) { u8 len = descData.at(offset + 0); u8 type = descData.at(offset + 1); if (len < 2) throw std::runtime_error("invalid descriptor length"); if (type == DT_INTERFACE && len >= 9 && descData.at(offset + 2) == number) return descData.at(offset + 8); offset += len; } throw std::runtime_error("no interface descriptor found"); } DevicePtr Device::Find() { using namespace mtp; usb::ContextPtr ctx(new usb::Context); for (usb::DeviceDescriptorPtr desc : ctx->GetDevices()) try { usb::DevicePtr device = desc->TryOpen(ctx); if (!device) continue; int confs = desc->GetConfigurationsCount(); //debug("configurations: ", confs); for(int i = 0; i < confs; ++i) { usb::ConfigurationPtr conf = desc->GetConfiguration(i); int interfaces = conf->GetInterfaceCount(); //debug("interfaces: ", interfaces); for(int j = 0; j < interfaces; ++j) { usb::InterfacePtr iface = conf->GetInterface(device, conf, j, 0); usb::InterfaceTokenPtr token = device->ClaimInterface(iface); debug(i, ':', j, "index ", iface->GetIndex(), ", eps ", iface->GetEndpointsCount()); ByteArray data = usb::DeviceRequest(device).GetDescriptor(usb::DescriptorType::String, 0, 0); HexDump("languages", data); if (data.size() < 4 || data[1] != (u8)usb::DescriptorType::String) continue; int interfaceStringIndex = GetInterfaceStringIndex(desc, j); u16 langId = data[2] | ((u16)data[3] << 8); data = usb::DeviceRequest(device).GetDescriptor(usb::DescriptorType::String, interfaceStringIndex, langId); HexDump("interface name", data); if (data.size() < 4 || data[1] != (u8)usb::DescriptorType::String) continue; u8 len = data[0]; InputStream stream(data, 2); std::string name = stream.ReadString((len - 2) / 2); if (name == "MTP") { //device->SetConfiguration(configuration->GetIndex()); usb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface, token); return std::make_shared<Device>(pipe); } if (iface->GetClass() == 6 && iface->GetSubclass() == 1) { usb::BulkPipePtr pipe = usb::BulkPipe::Create(device, conf, iface, token); return std::make_shared<Device>(pipe); } } } } catch(const std::exception &ex) { error("Device::Find", ex.what()); } return nullptr; } } <|endoftext|>
<commit_before> // Includes: // Standard libpng functionality. #include <png.h> // C standard library functionality: #include <cstdlib> #include <cstdint> // Namespaces: namespace imageEncoder { // Structures: typedef struct pixel_ARGB { // Colors: uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; } pixel; } <commit_msg>Fixed a small oversight with the C++ includes.<commit_after> // Includes: // C standard library functionality: #include <cstdlib> #include <cstdint> // Namespaces: namespace imageEncoder { // Structures: typedef struct pixel_ARGB { // Colors: uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; } pixel; } <|endoftext|>
<commit_before>// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP_LIFECYCLE__NODE_INTERFACES__LIFECYCLE_NODE_INTERFACE_HPP_ #define RCLCPP_LIFECYCLE__NODE_INTERFACES__LIFECYCLE_NODE_INTERFACE_HPP_ #include "lifecycle_msgs/msg/transition.hpp" #include "rclcpp_lifecycle/state.hpp" #include "rclcpp_lifecycle/visibility_control.h" namespace rclcpp_lifecycle { namespace node_interfaces { /// Interface class for a managed node. /** Virtual functions as defined in * http://design.ros2.org/articles/node_lifecycle.html * * If the callback function returns successfully, * the specified transition is completed. * If the callback function fails or throws an * uncaught exception, the on_error function is * called. * By default, all functions remain optional to overwrite * and return true. Except the on_error function, which * returns false and thus goes to shutdown/finalize state. */ class LifecycleNodeInterface { protected: RCLCPP_LIFECYCLE_PUBLIC LifecycleNodeInterface() {} public: enum class CallbackReturn : uint8_t { SUCCESS = lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS, FAILURE = lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_FAILURE, ERROR = lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_ERROR }; /// Callback function for configure transition /* * \return true by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_configure(const State & previous_state); /// Callback function for cleanup transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_cleanup(const State & previous_state); /// Callback function for shutdown transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_shutdown(const State & previous_state); /// Callback function for activate transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_activate(const State & previous_state); /// Callback function for deactivate transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_deactivate(const State & previous_state); /// Callback function for errorneous transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_error(const State & previous_state); RCLCPP_LIFECYCLE_PUBLIC virtual ~LifecycleNodeInterface() {} }; } // namespace node_interfaces } // namespace rclcpp_lifecycle #endif // RCLCPP_LIFECYCLE__NODE_INTERFACES__LIFECYCLE_NODE_INTERFACE_HPP_ <commit_msg>LifecycleNode on_configure doc fix. (#2034)<commit_after>// Copyright 2016 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLCPP_LIFECYCLE__NODE_INTERFACES__LIFECYCLE_NODE_INTERFACE_HPP_ #define RCLCPP_LIFECYCLE__NODE_INTERFACES__LIFECYCLE_NODE_INTERFACE_HPP_ #include "lifecycle_msgs/msg/transition.hpp" #include "rclcpp_lifecycle/state.hpp" #include "rclcpp_lifecycle/visibility_control.h" namespace rclcpp_lifecycle { namespace node_interfaces { /// Interface class for a managed node. /** Virtual functions as defined in * http://design.ros2.org/articles/node_lifecycle.html * * If the callback function returns successfully, * the specified transition is completed. * If the callback function fails or throws an * uncaught exception, the on_error function is * called. * By default, all functions remain optional to overwrite * and return true. Except the on_error function, which * returns false and thus goes to shutdown/finalize state. */ class LifecycleNodeInterface { protected: RCLCPP_LIFECYCLE_PUBLIC LifecycleNodeInterface() {} public: enum class CallbackReturn : uint8_t { SUCCESS = lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_SUCCESS, FAILURE = lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_FAILURE, ERROR = lifecycle_msgs::msg::Transition::TRANSITION_CALLBACK_ERROR }; /// Callback function for configure transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_configure(const State & previous_state); /// Callback function for cleanup transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_cleanup(const State & previous_state); /// Callback function for shutdown transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_shutdown(const State & previous_state); /// Callback function for activate transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_activate(const State & previous_state); /// Callback function for deactivate transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_deactivate(const State & previous_state); /// Callback function for errorneous transition /* * \return SUCCESS by default */ RCLCPP_LIFECYCLE_PUBLIC virtual CallbackReturn on_error(const State & previous_state); RCLCPP_LIFECYCLE_PUBLIC virtual ~LifecycleNodeInterface() {} }; } // namespace node_interfaces } // namespace rclcpp_lifecycle #endif // RCLCPP_LIFECYCLE__NODE_INTERFACES__LIFECYCLE_NODE_INTERFACE_HPP_ <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2016 Sergio Martins <smartins@kde.org> Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "AccessSpecifierManager.h" #if !defined(IS_OLD_CLANG) #include "StringUtils.h" #include "HierarchyUtils.h" #include "QtUtils.h" #include <clang/Basic/SourceManager.h> #include <clang/Parse/Parser.h> #include <clang/AST/DeclCXX.h> using namespace clang; using namespace std; static bool accessSpecifierCompare(const ClazyAccessSpecifier &lhs, const ClazyAccessSpecifier &rhs, const SourceManager &sm) { if (lhs.loc.isMacroID() || rhs.loc.isMacroID()) { // Q_SIGNALS is special because it hides a "public", which is expanded by this macro. // That means that both the Q_SIGNALS macro and the "public" will have the same source location. // We do want the "public" to appear before, so check if one has a macro id on it. SourceLocation realLHSLoc = sm.getFileLoc(lhs.loc); SourceLocation realRHSLoc = sm.getFileLoc(rhs.loc); if (realLHSLoc == realRHSLoc) { return lhs.loc.isMacroID(); } else { return realLHSLoc < realRHSLoc; } } return lhs.loc < rhs.loc; } static void sorted_insert(ClazySpecifierList &v, const ClazyAccessSpecifier &item, const clang::SourceManager &sm) { auto pred = [&sm] (const ClazyAccessSpecifier &lhs, const ClazyAccessSpecifier &rhs) { return accessSpecifierCompare(lhs, rhs, sm); }; v.insert(std::upper_bound(v.begin(), v.end(), item, pred), item); } class AccessSpecifierPreprocessorCallbacks : public clang::PPCallbacks { AccessSpecifierPreprocessorCallbacks(const AccessSpecifierPreprocessorCallbacks &) = delete; public: AccessSpecifierPreprocessorCallbacks(const clang::CompilerInstance &ci) : clang::PPCallbacks() , m_ci(ci) { m_qtAccessSpecifiers.reserve(30); // bootstrap it } void MacroExpands(const Token &MacroNameTok, const MacroDefinition &, SourceRange range, const MacroArgs *) override { IdentifierInfo *ii = MacroNameTok.getIdentifierInfo(); if (!ii) return; auto name = ii->getName(); const bool isSlots = name == "slots" || name == "Q_SLOTS"; const bool isSignals = isSlots ? false : (name == "signals" || name == "Q_SIGNALS"); const bool isSlot = (isSlots || isSignals) ? false : name == "Q_SLOT"; const bool isSignal = (isSlots || isSignals || isSlot) ? false : name == "Q_SIGNAL"; if (!isSlots && !isSignals && !isSlot && !isSignal) return; SourceLocation loc = range.getBegin(); if (loc.isMacroID()) return; if (isSignals || isSlots) { QtAccessSpecifierType qtAccessSpecifier = (isSlots || isSlot) ? QtAccessSpecifier_Slot : QtAccessSpecifier_Signal; m_qtAccessSpecifiers.push_back( { loc, clang::AS_none, qtAccessSpecifier } ); } else { // Get the location of the method declaration, so we can compare directly when we visit methods loc = Utils::locForNextToken(loc, m_ci.getSourceManager(), m_ci.getLangOpts()); if (loc.isInvalid()) return; if (isSignal) { m_individualSignals.push_back(loc.getRawEncoding()); } else { m_individualSlots.push_back(loc.getRawEncoding()); } } } vector<unsigned> m_individualSignals; // Q_SIGNAL vector<unsigned> m_individualSlots; // Q_SLOT const CompilerInstance &m_ci; ClazySpecifierList m_qtAccessSpecifiers; }; AccessSpecifierManager::AccessSpecifierManager(const clang::CompilerInstance &ci) : m_ci(ci) , m_preprocessorCallbacks(new AccessSpecifierPreprocessorCallbacks(ci)) { Preprocessor &pi = m_ci.getPreprocessor(); pi.addPPCallbacks(unique_ptr<PPCallbacks>(m_preprocessorCallbacks)); } ClazySpecifierList& AccessSpecifierManager::entryForClassDefinition(CXXRecordDecl *classDecl) { ClazySpecifierList &specifiers = m_specifiersMap[classDecl]; return specifiers; } CXXRecordDecl *AccessSpecifierManager::classDefinitionForLoc(SourceLocation loc) const { for (const auto &it : m_specifiersMap) { CXXRecordDecl *record = it.first; if (record->getLocStart() < loc && loc < record->getLocEnd()) return record; } return nullptr; } void AccessSpecifierManager::VisitDeclaration(Decl *decl) { auto record = dyn_cast<CXXRecordDecl>(decl); if (!QtUtils::isQObject(record)) return; const auto &sm = m_ci.getSourceManager(); // We got a new record, lets fetch signals and slots that the pre-processor gathered ClazySpecifierList &specifiers = entryForClassDefinition(record); auto it = m_preprocessorCallbacks->m_qtAccessSpecifiers.begin(); while (it != m_preprocessorCallbacks->m_qtAccessSpecifiers.end()) { if (classDefinitionForLoc((*it).loc) == record) { sorted_insert(specifiers, *it, sm); it = m_preprocessorCallbacks->m_qtAccessSpecifiers.erase(it); } else { ++it; } } // Now lets add the normal C++ access specifiers (public, private etc.) for (auto d : record->decls()) { auto accessSpec = dyn_cast<AccessSpecDecl>(d); if (!accessSpec || accessSpec->getDeclContext() != record) continue; ClazySpecifierList &specifiers = entryForClassDefinition(record); sorted_insert(specifiers, {accessSpec->getLocStart(), accessSpec->getAccess(), QtAccessSpecifier_None }, sm); } } QtAccessSpecifierType AccessSpecifierManager::qtAccessSpecifierType(CXXMethodDecl *method) const { if (!method || method->getLocStart().isMacroID()) return QtAccessSpecifier_Unknown; SourceLocation loc = method->getLocStart(); // Process Q_SIGNAL: for (auto signalLoc : m_preprocessorCallbacks->m_individualSignals) { if (signalLoc == loc.getRawEncoding()) return QtAccessSpecifier_Signal; } // Process Q_SLOT: for (auto slotLoc : m_preprocessorCallbacks->m_individualSlots) { if (slotLoc == loc.getRawEncoding()) return QtAccessSpecifier_Slot; } // Process Q_SLOTS and Q_SIGNALS: CXXRecordDecl *record = method->getParent(); if (!record || isa<clang::ClassTemplateSpecializationDecl>(record)) return QtAccessSpecifier_None; auto it = m_specifiersMap.find(record); if (it == m_specifiersMap.cend()) return QtAccessSpecifier_None; const ClazySpecifierList &accessSpecifiers = it->second; auto pred = [this] (const ClazyAccessSpecifier &lhs, const ClazyAccessSpecifier &rhs) { return accessSpecifierCompare(lhs, rhs, m_ci.getSourceManager()); }; const ClazyAccessSpecifier dummy = { method->getLocStart(), // we're only interested in the location /*dummy*/ clang::AS_none, /*dummy*/ QtAccessSpecifier_None }; auto i = std::upper_bound(accessSpecifiers.cbegin(), accessSpecifiers.cend(), dummy, pred); if (i == accessSpecifiers.cbegin()) return QtAccessSpecifier_None; --i; // One before the upper bound is the last access specifier before our method return (*i).qtAccessSpecifier; } #endif <commit_msg>minor cleanup<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2016 Sergio Martins <smartins@kde.org> Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "AccessSpecifierManager.h" #if !defined(IS_OLD_CLANG) #include "StringUtils.h" #include "HierarchyUtils.h" #include "QtUtils.h" #include <clang/Basic/SourceManager.h> #include <clang/Parse/Parser.h> #include <clang/AST/DeclCXX.h> using namespace clang; using namespace std; static bool accessSpecifierCompare(const ClazyAccessSpecifier &lhs, const ClazyAccessSpecifier &rhs, const SourceManager &sm) { if (lhs.loc.isMacroID() || rhs.loc.isMacroID()) { // Q_SIGNALS is special because it hides a "public", which is expanded by this macro. // That means that both the Q_SIGNALS macro and the "public" will have the same source location. // We do want the "public" to appear before, so check if one has a macro id on it. SourceLocation realLHSLoc = sm.getFileLoc(lhs.loc); SourceLocation realRHSLoc = sm.getFileLoc(rhs.loc); if (realLHSLoc == realRHSLoc) { return lhs.loc.isMacroID(); } else { return realLHSLoc < realRHSLoc; } } return lhs.loc < rhs.loc; } static void sorted_insert(ClazySpecifierList &v, const ClazyAccessSpecifier &item, const clang::SourceManager &sm) { auto pred = [&sm] (const ClazyAccessSpecifier &lhs, const ClazyAccessSpecifier &rhs) { return accessSpecifierCompare(lhs, rhs, sm); }; v.insert(std::upper_bound(v.begin(), v.end(), item, pred), item); } class AccessSpecifierPreprocessorCallbacks : public clang::PPCallbacks { AccessSpecifierPreprocessorCallbacks(const AccessSpecifierPreprocessorCallbacks &) = delete; public: AccessSpecifierPreprocessorCallbacks(const clang::CompilerInstance &ci) : clang::PPCallbacks() , m_ci(ci) { m_qtAccessSpecifiers.reserve(30); // bootstrap it } void MacroExpands(const Token &MacroNameTok, const MacroDefinition &, SourceRange range, const MacroArgs *) override { IdentifierInfo *ii = MacroNameTok.getIdentifierInfo(); if (!ii) return; auto name = ii->getName(); const bool isSlots = name == "slots" || name == "Q_SLOTS"; const bool isSignals = isSlots ? false : (name == "signals" || name == "Q_SIGNALS"); const bool isSlot = (isSlots || isSignals) ? false : name == "Q_SLOT"; const bool isSignal = (isSlots || isSignals || isSlot) ? false : name == "Q_SIGNAL"; if (!isSlots && !isSignals && !isSlot && !isSignal) return; SourceLocation loc = range.getBegin(); if (loc.isMacroID()) return; if (isSignals || isSlots) { QtAccessSpecifierType qtAccessSpecifier = isSlots ? QtAccessSpecifier_Slot : QtAccessSpecifier_Signal; m_qtAccessSpecifiers.push_back( { loc, clang::AS_none, qtAccessSpecifier } ); } else { // Get the location of the method declaration, so we can compare directly when we visit methods loc = Utils::locForNextToken(loc, m_ci.getSourceManager(), m_ci.getLangOpts()); if (loc.isInvalid()) return; if (isSignal) { m_individualSignals.push_back(loc.getRawEncoding()); } else { m_individualSlots.push_back(loc.getRawEncoding()); } } } vector<unsigned> m_individualSignals; // Q_SIGNAL vector<unsigned> m_individualSlots; // Q_SLOT const CompilerInstance &m_ci; ClazySpecifierList m_qtAccessSpecifiers; }; AccessSpecifierManager::AccessSpecifierManager(const clang::CompilerInstance &ci) : m_ci(ci) , m_preprocessorCallbacks(new AccessSpecifierPreprocessorCallbacks(ci)) { Preprocessor &pi = m_ci.getPreprocessor(); pi.addPPCallbacks(unique_ptr<PPCallbacks>(m_preprocessorCallbacks)); } ClazySpecifierList& AccessSpecifierManager::entryForClassDefinition(CXXRecordDecl *classDecl) { ClazySpecifierList &specifiers = m_specifiersMap[classDecl]; return specifiers; } CXXRecordDecl *AccessSpecifierManager::classDefinitionForLoc(SourceLocation loc) const { for (const auto &it : m_specifiersMap) { CXXRecordDecl *record = it.first; if (record->getLocStart() < loc && loc < record->getLocEnd()) return record; } return nullptr; } void AccessSpecifierManager::VisitDeclaration(Decl *decl) { auto record = dyn_cast<CXXRecordDecl>(decl); if (!QtUtils::isQObject(record)) return; const auto &sm = m_ci.getSourceManager(); // We got a new record, lets fetch signals and slots that the pre-processor gathered ClazySpecifierList &specifiers = entryForClassDefinition(record); auto it = m_preprocessorCallbacks->m_qtAccessSpecifiers.begin(); while (it != m_preprocessorCallbacks->m_qtAccessSpecifiers.end()) { if (classDefinitionForLoc((*it).loc) == record) { sorted_insert(specifiers, *it, sm); it = m_preprocessorCallbacks->m_qtAccessSpecifiers.erase(it); } else { ++it; } } // Now lets add the normal C++ access specifiers (public, private etc.) for (auto d : record->decls()) { auto accessSpec = dyn_cast<AccessSpecDecl>(d); if (!accessSpec || accessSpec->getDeclContext() != record) continue; ClazySpecifierList &specifiers = entryForClassDefinition(record); sorted_insert(specifiers, {accessSpec->getLocStart(), accessSpec->getAccess(), QtAccessSpecifier_None }, sm); } } QtAccessSpecifierType AccessSpecifierManager::qtAccessSpecifierType(CXXMethodDecl *method) const { if (!method || method->getLocStart().isMacroID()) return QtAccessSpecifier_Unknown; const SourceLocation methodLoc = method->getLocStart(); // Process Q_SIGNAL: for (auto signalLoc : m_preprocessorCallbacks->m_individualSignals) { if (signalLoc == methodLoc.getRawEncoding()) return QtAccessSpecifier_Signal; } // Process Q_SLOT: for (auto slotLoc : m_preprocessorCallbacks->m_individualSlots) { if (slotLoc == methodLoc.getRawEncoding()) return QtAccessSpecifier_Slot; } // Process Q_SLOTS and Q_SIGNALS: CXXRecordDecl *record = method->getParent(); if (!record || isa<clang::ClassTemplateSpecializationDecl>(record)) return QtAccessSpecifier_None; auto it = m_specifiersMap.find(record); if (it == m_specifiersMap.cend()) return QtAccessSpecifier_None; const ClazySpecifierList &accessSpecifiers = it->second; auto pred = [this] (const ClazyAccessSpecifier &lhs, const ClazyAccessSpecifier &rhs) { return accessSpecifierCompare(lhs, rhs, m_ci.getSourceManager()); }; const ClazyAccessSpecifier dummy = { methodLoc, // we're only interested in the location /*dummy*/ clang::AS_none, /*dummy*/ QtAccessSpecifier_None }; auto i = std::upper_bound(accessSpecifiers.cbegin(), accessSpecifiers.cend(), dummy, pred); if (i == accessSpecifiers.cbegin()) return QtAccessSpecifier_None; --i; // One before the upper bound is the last access specifier before our method return (*i).qtAccessSpecifier; } #endif <|endoftext|>
<commit_before>#include "Clipper.h" #include <algorithm> #include <functional> // Calculates the intersection point of a line segment lb->la which crosses the // plane with normal 'n'. static bool RayPlaneIntersection(const FLOATVECTOR3 &la, const FLOATVECTOR3 &lb, const FLOATVECTOR3 &n, const float D, FLOATVECTOR3 &hit) { const float denom = n ^ (la - lb); if(EpsilonEqual(denom, 0.0f)) { return false; } const float t = ((n ^ la) + D) / denom; hit = la + (t*(lb - la)); return true; } // Splits a triangle along a plane with the given normal. // Assumes: plane's D == 0. // triangle does span the plane. void SplitTriangle(FLOATVECTOR3 a, FLOATVECTOR3 b, FLOATVECTOR3 c, float fa, float fb, float fc, const FLOATVECTOR3 &normal, const float D, std::vector<FLOATVECTOR3>& out, std::vector<FLOATVECTOR3>& newVerts) { // rotation / mirroring. // c // o Push `c' to be alone on one side of the plane, making // / \ `a' and `b' on the other. Later we'll be able to // plane --------- assume that there will be an intersection with the // / \ clip plane along the lines `ac' and `bc'. This // o-------o reduces the number of cases below. // a b // if fa*fc is non-negative, both have the same sign -- and thus are on the // same side of the plane. if(fa*fc >= 0) { std::swap(fb, fc); std::swap(b, c); std::swap(fa, fb); std::swap(a, b); } else if(fb*fc >= 0) { std::swap(fa, fc); std::swap(a, c); std::swap(fa, fb); std::swap(a, b); } // Find the intersection points. FLOATVECTOR3 A, B; RayPlaneIntersection(a,c, normal,D, A); RayPlaneIntersection(b,c, normal,D, B); if(fc >= 0) { out.push_back(a); out.push_back(b); out.push_back(A); out.push_back(b); out.push_back(B); out.push_back(A); } else { out.push_back(A); out.push_back(B); out.push_back(c); } newVerts.push_back(A); newVerts.push_back(B); } std::vector<FLOATVECTOR3> Clipper::TriPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) { std::vector<FLOATVECTOR3> newVertices; std::vector<FLOATVECTOR3> out; if (posData.size() % 3 != 0) return newVertices; for(auto iter = posData.begin(); iter < (posData.end()-2); iter += 3) { const FLOATVECTOR3 &a = (*iter); const FLOATVECTOR3 &b = (*(iter+1)); const FLOATVECTOR3 &c = (*(iter+2)); float fa = (normal ^ a) + D; float fb = (normal ^ b) + D; float fc = (normal ^ c) + D; if(fabs(fa) < (2 * std::numeric_limits<float>::epsilon())) { fa = 0; } if(fabs(fb) < (2 * std::numeric_limits<float>::epsilon())) { fb = 0; } if(fabs(fc) < (2 * std::numeric_limits<float>::epsilon())) { fc = 0; } if(fa >= 0 && fb >= 0 && fc >= 0) { // trivial reject // discard -- i.e. do nothing / ignore tri. continue; } else if(fa <= 0 && fb <= 0 && fc <= 0) { // trivial accept out.push_back(a); out.push_back(b); out.push_back(c); } else { // triangle spans plane -- must be split. std::vector<FLOATVECTOR3> tris, newVerts; SplitTriangle(a,b,c, fa,fb,fc,normal,D, tris, newVerts); // append triangles and vertices to lists out.insert(out.end(), tris.begin(), tris. end()); newVertices.insert(newVertices.end(), newVerts.begin(), newVerts. end()); } } posData = out; return newVertices; } struct { bool operator() (const FLOATVECTOR3& i, const FLOATVECTOR3& j) { return i.x < j.x || (i.x == j.x && i.y < j.y) || (i.x == j.x && i.y == j.y && i.z < j.z); } } CompSorter; static bool AngleSorter(const FLOATVECTOR3& i, const FLOATVECTOR3& j, const FLOATVECTOR3& center, const FLOATVECTOR3& refVec, const FLOATVECTOR3& normal) { FLOATVECTOR3 vecI = (i-center).normalized(); float cosI = refVec ^ vecI; float sinI = (vecI % refVec)^ normal; FLOATVECTOR3 vecJ = (j-center).normalized(); float cosJ = refVec ^ vecJ; float sinJ = (vecJ % refVec) ^ normal; float acI = atan2(sinI, cosI); float acJ = atan2(sinJ, cosJ); return acI > acJ; } void Clipper::BoxPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) { std::vector<FLOATVECTOR3> newVertices = Clipper::TriPlane(posData, normal, D); if (newVertices.size() < 3) return; // remove duplicate vertices std::sort(newVertices.begin(), newVertices.end(), CompSorter); newVertices.erase(std::unique(newVertices.begin(), newVertices.end()), newVertices.end()); // sort counter clockwise using namespace std::placeholders; FLOATVECTOR3 center; for (auto vertex = newVertices.begin();vertex<newVertices.end();++vertex) { center += *vertex; } center /= float(newVertices.size()); std::sort(newVertices.begin(), newVertices.end(), std::bind(AngleSorter, _1, _2, center, (newVertices[0]-center).normalized(), normal )); // create a triangle fan with the newly created vertices to close the polytope for (auto vertex = newVertices.begin()+2;vertex<newVertices.end();++vertex) { posData.push_back(newVertices[0]); posData.push_back(*(vertex-1)); posData.push_back(*(vertex)); } } /* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Interactive Visualization and Data Analysis Group. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ <commit_msg>beautified the code<commit_after>#include "Clipper.h" #include <algorithm> #include <functional> // Calculates the intersection point of a line segment lb->la which crosses the // plane with normal 'n'. static bool RayPlaneIntersection(const FLOATVECTOR3 &la, const FLOATVECTOR3 &lb, const FLOATVECTOR3 &n, const float D, FLOATVECTOR3 &hit) { const float denom = n ^ (la - lb); if(EpsilonEqual(denom, 0.0f)) { return false; } const float t = ((n ^ la) + D) / denom; hit = la + (t*(lb - la)); return true; } // Splits a triangle along a plane with the given normal. // Assumes: plane's D == 0. // triangle does span the plane. void SplitTriangle(FLOATVECTOR3 a, FLOATVECTOR3 b, FLOATVECTOR3 c, float fa, float fb, float fc, const FLOATVECTOR3 &normal, const float D, std::vector<FLOATVECTOR3>& out, std::vector<FLOATVECTOR3>& newVerts) { // rotation / mirroring. // c // o Push `c' to be alone on one side of the plane, making // / \ `a' and `b' on the other. Later we'll be able to // plane --------- assume that there will be an intersection with the // / \ clip plane along the lines `ac' and `bc'. This // o-------o reduces the number of cases below. // a b // if fa*fc is non-negative, both have the same sign -- and thus are on the // same side of the plane. if(fa*fc >= 0) { std::swap(fb, fc); std::swap(b, c); std::swap(fa, fb); std::swap(a, b); } else if(fb*fc >= 0) { std::swap(fa, fc); std::swap(a, c); std::swap(fa, fb); std::swap(a, b); } // Find the intersection points. FLOATVECTOR3 A, B; RayPlaneIntersection(a,c, normal,D, A); RayPlaneIntersection(b,c, normal,D, B); if(fc >= 0) { out.push_back(a); out.push_back(b); out.push_back(A); out.push_back(b); out.push_back(B); out.push_back(A); } else { out.push_back(A); out.push_back(B); out.push_back(c); } newVerts.push_back(A); newVerts.push_back(B); } std::vector<FLOATVECTOR3> Clipper::TriPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) { std::vector<FLOATVECTOR3> newVertices; std::vector<FLOATVECTOR3> out; if (posData.size() % 3 != 0) return newVertices; for(auto iter = posData.begin(); iter < (posData.end()-2); iter += 3) { const FLOATVECTOR3 &a = (*iter); const FLOATVECTOR3 &b = (*(iter+1)); const FLOATVECTOR3 &c = (*(iter+2)); float fa = (normal ^ a) + D; float fb = (normal ^ b) + D; float fc = (normal ^ c) + D; if(fabs(fa) < (2 * std::numeric_limits<float>::epsilon())) { fa = 0; } if(fabs(fb) < (2 * std::numeric_limits<float>::epsilon())) { fb = 0; } if(fabs(fc) < (2 * std::numeric_limits<float>::epsilon())) { fc = 0; } if(fa >= 0 && fb >= 0 && fc >= 0) { // trivial reject // discard -- i.e. do nothing / ignore tri. continue; } else if(fa <= 0 && fb <= 0 && fc <= 0) { // trivial accept out.push_back(a); out.push_back(b); out.push_back(c); } else { // triangle spans plane -- must be split. std::vector<FLOATVECTOR3> tris, newVerts; SplitTriangle(a,b,c, fa,fb,fc,normal,D, tris, newVerts); // append triangles and vertices to lists out.insert(out.end(), tris.begin(), tris. end()); newVertices.insert(newVertices.end(), newVerts.begin(), newVerts. end()); } } posData = out; return newVertices; } struct { bool operator() (const FLOATVECTOR3& i, const FLOATVECTOR3& j) { return i.x < j.x || (i.x == j.x && i.y < j.y) || (i.x == j.x && i.y == j.y && i.z < j.z); } } CompSorter; static bool AngleSorter(const FLOATVECTOR3& i, const FLOATVECTOR3& j, const FLOATVECTOR3& center, const FLOATVECTOR3& refVec, const FLOATVECTOR3& normal) { FLOATVECTOR3 vecI = (i-center).normalized(); float cosI = refVec ^ vecI; float sinI = (vecI % refVec)^ normal; FLOATVECTOR3 vecJ = (j-center).normalized(); float cosJ = refVec ^ vecJ; float sinJ = (vecJ % refVec) ^ normal; float acI = atan2(sinI, cosI); float acJ = atan2(sinJ, cosJ); return acI > acJ; } void Clipper::BoxPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) { std::vector<FLOATVECTOR3> newVertices = Clipper::TriPlane(posData, normal, D); if (newVertices.size() < 3) return; // remove duplicate vertices std::sort(newVertices.begin(), newVertices.end(), CompSorter); newVertices.erase(std::unique(newVertices.begin(), newVertices.end()), newVertices.end()); // sort counter clockwise using namespace std::placeholders; FLOATVECTOR3 center; for (auto vertex = newVertices.begin();vertex<newVertices.end();++vertex) { center += *vertex; } center /= float(newVertices.size()); std::sort(newVertices.begin(), newVertices.end(), std::bind(AngleSorter, _1, _2, center, (newVertices[0]-center).normalized(), normal )); // create a triangle fan with the newly created vertices to close the polytope for (auto vertex = newVertices.begin()+2;vertex<newVertices.end();++vertex) { posData.push_back(newVertices[0]); posData.push_back(*(vertex-1)); posData.push_back(*(vertex)); } } /* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Interactive Visualization and Data Analysis Group. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ <|endoftext|>
<commit_before>#include "wrestd.h" #ifdef _WIN32 #include <Windows.h> #endif #include <iostream> #include <fstream> #include <cstdio> // this is here because on VS2010 I have to change how this works to make it work properly #define TO_STRING(i) (to_string(i)) // windows defined max, and I want to use a different one later on, meaning I have to undef this one #ifdef _WIN32 #undef max #endif using namespace std; using namespace wrestd::io; // the following color code arrays are in the order of color_t color codes for reasy switching: color_t::black = 0, so nixcolorcodes[0] = 30, aka black // foreground color codes for ANSI escapes const char* nixcolorcodes[16] = { "30", "34", "32", "36", "31", "35", "33", "37", "30;1", "34;1", "32;1", "36;1", "31;1", "35;1", "33;1", "37;1" }; // background color codes for ANSI escapes const char* nixbgcolorcodes[16] = { "40", "44", "42", "46", "41", "45", "43", "47", "40;1", "44;1", "42;1", "46;1", "41;1", "45;1", "43;1", "47;1" }; // return the ANSI color code corresponding to the color_t specified char* nixcolor(color_t color) { char *ncolor = (char *)malloc(15); // 15 is a wee bit large but it should be enough for all colors required if (color != DEFAULT) sprintf(ncolor, "\033[%sm", nixcolorcodes[color]); else // the person wants to set it to DEFAULT, which should be ESC[m sprintf(ncolor, "\033[m"); return ncolor; } // return the ANSI code for the background color_t specified char* nixbgcolor(color_t color) { char *ncolor = (char *)malloc(15); if (color != DEFAULT) sprintf(ncolor, "\033[%sm", nixbgcolorcodes[color]); else sprintf(ncolor, "\033[m"); return ncolor; } #ifdef _WIN32 // this will let me access the console HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); #endif /* Set color of console text. Can specify background color if the system supports it. */ void wrestd::io::setColor(color_t colorCode, color_t bgColorCode = NULL) { #ifdef _WIN32 // this will only work on windows SetConsoleTextAttribute(console, colorCode); #else // here I will use the nixcolors above cout << nixcolor(colorCode); // if bgColorCode is specified, change the background to that too if (bgColorCode != NULL) cout << nixbgcolor(bgColorCode); #endif } /* Clear the console. */ void wrestd::io::clear() { #ifdef _WIN32 COORD topLeft = { 0, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA(console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written); FillConsoleOutputAttribute(console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &written); SetConsoleCursorPosition(console, topLeft); #else // this is the non-windows way of doing this // J clears the display, 2 means to clear the whole thing, and then cursor gets put at the top left cout << "\033[2J"; #endif } /* Print a line in a certain color. * Optionally, specify a background color for systems that support it. */ void wrestd::io::printlc(string line, color_t color, color_t bgColorCode = NULL) { setColor(color, bgColorCode); cout << line << endl; setColor(DEFAULT, DEFAULT); } /* Print in a certain color, but no newline. * Optionally, specify a background color for systems that support it. */ void wrestd::io::printc(string text, color_t color, color_t bgColorCode = NULL) { setColor(color, bgColorCode); cout << text; setColor(DEFAULT, DEFAULT); } /* Wait for user to press enter, optionally printing it in a specific color. * Also optionally add a background color shown on systems which support it. */ void wrestd::io::wait(color_t messagecolor = DEFAULT, color_t bgColor = NULL) { setColor(messagecolor, bgColor); cout << "\nPress ENTER to continue..."; // this is why i had to undef max, because windows defines it in some header file somewhere cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); setColor(DEFAULT, DEFAULT); } /* Wait for user to press enter, display custom message, optionally specifying a color for the message. * Optionally specify background color for supported systems. */ void wrestd::io::wait(string message, color_t messagecolor = DEFAULT, color_t bgColorCode = NULL) { setColor(messagecolor, bgColorCode); cout << "\n" << message; // this is why i had to undef max, because windows defines it in some header file somewhere cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); setColor(DEFAULT, DEFAULT); } /* Return true or false based on the existance of a file. */ bool wrestd::io::fileExists(char filename[]) { if (ifstream(filename)) return true; ofstream file(filename); if (!file) { file.close(); return false; } return false; // just in case both of the above fail to work. assume no file. } <commit_msg>Added background color support for Windows.<commit_after>#include "wrestd.h" #ifdef _WIN32 #include <Windows.h> #endif #include <iostream> #include <fstream> #include <cstdio> // this is here because on VS2010 I have to change how this works to make it work properly #define TO_STRING(i) (to_string(i)) // windows defined max, and I want to use a different one later on, meaning I have to undef this one #ifdef _WIN32 #undef max #endif using namespace std; using namespace wrestd::io; // the following color code arrays are in the order of color_t color codes for reasy switching: color_t::black = 0, so nixcolorcodes[0] = 30, aka black // foreground color codes for ANSI escapes const char* nixcolorcodes[16] = { "30", "34", "32", "36", "31", "35", "33", "37", "30;1", "34;1", "32;1", "36;1", "31;1", "35;1", "33;1", "37;1" }; // background color codes for ANSI escapes const char* nixbgcolorcodes[16] = { "40", "44", "42", "46", "41", "45", "43", "47", "40;1", "44;1", "42;1", "46;1", "41;1", "45;1", "43;1", "47;1" }; // return the ANSI color code corresponding to the color_t specified char* nixcolor(color_t color) { char *ncolor = (char *)malloc(15); // 15 is a wee bit large but it should be enough for all colors required if (color != DEFAULT) sprintf(ncolor, "\033[%sm", nixcolorcodes[color]); else // the person wants to set it to DEFAULT, which should be ESC[m sprintf(ncolor, "\033[m"); return ncolor; } // return the ANSI code for the background color_t specified char* nixbgcolor(color_t color) { char *ncolor = (char *)malloc(15); if (color != DEFAULT) sprintf(ncolor, "\033[%sm", nixbgcolorcodes[color]); else sprintf(ncolor, "\033[m"); return ncolor; } #ifdef _WIN32 // this will let me access the console HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); #endif /* Set color of console text. Can specify background color if the system supports it. */ void wrestd::io::setColor(color_t colorCode, color_t bgColorCode = NULL) { #ifdef _WIN32 // this will only work on windows // if there is no bgColorCode specified, just do this if (bgColorCode == NULL) SetConsoleTextAttribute(console, colorCode); else { WORD color = ((bgColorCode & 0x0F) << 4) + (colorCode & 0x0F); SetConsoleTextAttribute(console, color); } #else // here I will use the nixcolors above cout << nixcolor(colorCode); // if bgColorCode is specified, change the background to that too if (bgColorCode != NULL) cout << nixbgcolor(bgColorCode); #endif } /* Clear the console. */ void wrestd::io::clear() { #ifdef _WIN32 COORD topLeft = { 0, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA(console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written); FillConsoleOutputAttribute(console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &written); SetConsoleCursorPosition(console, topLeft); #else // this is the non-windows way of doing this // J clears the display, 2 means to clear the whole thing, and then cursor gets put at the top left cout << "\033[2J"; #endif } /* Print a line in a certain color. * Optionally, specify a background color for systems that support it. */ void wrestd::io::printlc(string line, color_t color, color_t bgColorCode = NULL) { setColor(color, bgColorCode); cout << line << endl; setColor(DEFAULT, DEFAULT); } /* Print in a certain color, but no newline. * Optionally, specify a background color for systems that support it. */ void wrestd::io::printc(string text, color_t color, color_t bgColorCode = NULL) { setColor(color, bgColorCode); cout << text; setColor(DEFAULT, DEFAULT); } /* Wait for user to press enter, optionally printing it in a specific color. * Also optionally add a background color shown on systems which support it. */ void wrestd::io::wait(color_t messagecolor = DEFAULT, color_t bgColor = NULL) { setColor(messagecolor, bgColor); cout << "\nPress ENTER to continue..."; // this is why i had to undef max, because windows defines it in some header file somewhere cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); setColor(DEFAULT, DEFAULT); } /* Wait for user to press enter, display custom message, optionally specifying a color for the message. * Optionally specify background color for supported systems. */ void wrestd::io::wait(string message, color_t messagecolor = DEFAULT, color_t bgColorCode = NULL) { setColor(messagecolor, bgColorCode); cout << "\n" << message; // this is why i had to undef max, because windows defines it in some header file somewhere cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); setColor(DEFAULT, DEFAULT); } /* Return true or false based on the existance of a file. */ bool wrestd::io::fileExists(char filename[]) { if (ifstream(filename)) return true; ofstream file(filename); if (!file) { file.close(); return false; } return false; // just in case both of the above fail to work. assume no file. } <|endoftext|>
<commit_before> /* * Copyright (c) 2014, Dinamica Srl * Copyright (c) 2014, K. Kumar (kumar@dinamicatech.com) * All rights reserved. * See COPYING for license details. */ #include <iomanip> #include <limits> #include <cmath> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <boost/format.hpp> #include <boost/timer/timer.hpp> #include <Eigen/Core> #include <nlopt.hpp> #include <libsgp4/Eci.h> #include <libsgp4/DateTime.h> #include <libsgp4/Globals.h> #include <libsgp4/SGP4.h> #include <libsgp4/Tle.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/physicalConstants.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h> #include <TudatCore/Mathematics/BasicMathematics/basicMathematicsFunctions.h> #include <TudatCore/Mathematics/BasicMathematics/mathematicalConstants.h> #include <Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.h> #include <D2D/cartesianToTwoLineElementsObjectiveFunction.h> //! Execute D2D test app. int main( const int numberOfInputs, const char* inputArguments[ ] ) { /////////////////////////////////////////////////////////////////////////// // Start timer. Timer automatically ends when this object goes out of scope. boost::timer::auto_cpu_timer timer; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Declare using-statements. using std::cout; using std::endl; using std::string; using std::vector; using namespace tudat::basic_astrodynamics::orbital_element_conversions; using namespace tudat::basic_astrodynamics::unit_conversions; using namespace tudat::basic_astrodynamics::physical_constants; using namespace tudat::basic_mathematics; using namespace tudat::basic_mathematics::mathematical_constants; using namespace tudat::mission_segments; using namespace d2d; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Input deck. // Set depature epoch. const DateTime departureEpoch( 2014, 5, 23, 16, 0, 0 ); // Set time-of-flight [s]. // const double timeOfFlight = 1325.0; // Set TLE strings for 1st debris object. const string nameObject1 = "0 VANGUARD 1"; const string line1Object1 = "1 00005U 58002B 14143.59770889 -.00000036 00000-0 -22819-4 0 2222"; const string line2Object1 = "2 00005 034.2431 215.7533 1849786 098.8024 282.5368 10.84391811964621"; // Set TLE strings for 2nd debris object. // const string nameObject2 = "0 SCOUT D-1 R/B"; // const string line1Object2 // = "1 06800U 72091 B 79098.71793498 .00418782 +00000-0 +00000-0 0 03921"; // const string line2Object2 // = "2 06800 001.9047 136.0594 0024458 068.9289 290.1247 15.83301112263179"; // Set minimization tolerance. // const double minimizationTolerance = 1.0e-3; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Compute derived parameters. // Set Earth gravitational parameter [m^3 s^-2]. const double earthGravitationalParameter = kMU * 1.0e9; // Compute arrival epoch. const DateTime arrivalEpoch( departureEpoch ); // arrivalEpoch.AddSeconds( timeOfFlight ); // Create TLE objects from strings. const Tle tleObject1( nameObject1, line1Object1, line2Object1 ); // const Tle tleObject2( nameObject2, line1Object2, line2Object2 ); // Set up SGP4 propagator objects. const SGP4 sgp4Object1( tleObject1 ); // const SGP4 sgp4Object2( tleObject2 ); // Compute Cartesian states of objects at departure and arrival epochs. const Eci departureState = sgp4Object1.FindPosition( departureEpoch ); // const Eci arrivalState = sgp4Object2.FindPosition( arrivalEpoch ); // Compute departure position [m] and velocity [ms^-1]. const Eigen::Vector3d depaturePosition( convertKilometersToMeters( departureState.Position( ).x ), convertKilometersToMeters( departureState.Position( ).y ), convertKilometersToMeters( departureState.Position( ).z ) ); const Eigen::Vector3d departureVelocity( convertKilometersToMeters( departureState.Velocity( ).x ), convertKilometersToMeters( departureState.Velocity( ).y ), convertKilometersToMeters( departureState.Velocity( ).z ) ); // Compute arrival position [m] and velocity [ms^-1]. // const Eigen::Vector3d arrivalPosition( // convertKilometersToMeters( arrivalState.Position( ).x ), // convertKilometersToMeters( arrivalState.Position( ).y ), // convertKilometersToMeters( arrivalState.Position( ).z ) ); // const Eigen::Vector3d arrivalVelocity( // convertKilometersToMeters( arrivalState.Velocity( ).x ), // convertKilometersToMeters( arrivalState.Velocity( ).y ), // convertKilometersToMeters( arrivalState.Velocity( ).z ) ); // Set up Lambert targeter. This automatically triggers the solver to execute. // LambertTargeterIzzo lambertTargeter( // depaturePosition, arrivalPosition, timeOfFlight, earthGravitationalParameter ); // // Compute Delta V at departure position [ms^-1]. // cout << "Delta V_dep: " // << std::fabs( // lambertTargeter.getInertialVelocityAtDeparture( ).norm( ) // - departureVelocity.norm( ) ) // << " m/s" << endl; // Set Cartesian state at departure after executing maneuver. const Eigen::VectorXd departureStateAfterManeuver = ( Eigen::VectorXd( 6 ) << depaturePosition, // lambertTargeter.getInertialVelocityAtDeparture( ) ).finished( ); departureVelocity // + Eigen::Vector3d( 50.0, 25.0, -10.0 ) ).finished( ); // Set initial guess for TLE mean elements. const Eigen::VectorXd newTleMeanElementsGuess = ( Eigen::VectorXd( 6 ) << tleObject1.Inclination( true ), tleObject1.RightAscendingNode( true ), tleObject1.Eccentricity( ), tleObject1.ArgumentPerigee( true ), tleObject1.MeanAnomaly( true ), tleObject1.MeanMotion( ) ).finished( ); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Compute TLE for object 1 at departure epoch. // Set up derivative-free optimizer. nlopt::opt optimizer( nlopt::LN_BOBYQA, 6 ); // Set up parameters for objective function. ObjectiveFunctionParameters parameters( earthGravitationalParameter, tleObject1, departureStateAfterManeuver, departureEpoch ); // Set objective function. optimizer.set_min_objective( cartesianToTwoLineElementsObjectiveFunction, &parameters ); // Set tolerance. // optimizer.set_xtol_rel( minimizationTolerance ); // Set lower bounds. // std::vector< double > lowerBounds( 6, -HUGE_VAL ); // // lowerBounds.at( semiMajorAxisIndex ) = 6.0e6; // lowerBounds.at( eccentricityIndex ) = 0.0; // // lowerBounds.at( inclinationIndex ) = 0.0; // // lowerBounds.at( argumentOfPeriapsisIndex ) = 0.0; // // lowerBounds.at( longitudeOfAscendingNodeIndex ) = 0.0; // // lowerBounds.at( trueAnomalyIndex ) = 0.0; // optimizer.set_lower_bounds( lowerBounds ); // Set upper bounds. // std::vector< double > upperBounds( 6, HUGE_VAL ); // // lowerBounds.at( semiMajorAxisIndex ) = 5.0e7; // upperBounds.at( eccentricityIndex ) = 1.0; // // upperBounds.at( inclinationIndex ) = PI; // // upperBounds.at( argumentOfPeriapsisIndex ) = 2.0 * PI; // // upperBounds.at( longitudeOfAscendingNodeIndex ) = 2.0 * PI; // // upperBounds.at( trueAnomalyIndex ) = 2.0 * PI; // optimizer.set_upper_bounds( upperBounds ); // Set initial guess for decision vector to the TLE mean elements at departure. vector< double > decisionVector( 6 ); Eigen::Map< Eigen::VectorXd >( decisionVector.data( ), 6, 1 ) = newTleMeanElementsGuess; // Set initial step size. // optimizer.set_initial_step( 0.1 ); // Execute optimizer. double minimumFunctionValue; nlopt::result result = optimizer.optimize( decisionVector, minimumFunctionValue ); // Print output statements. if ( result < 0 ) { cout << "NLOPT failed!" << endl; } else { cout << "found minimum = " << minimumFunctionValue << endl; } // Print number of iterations taken by optimizer. cout << endl; cout << "# of iterations: " << optimizerIterations << endl; cout << endl; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// cout << "Timing information: "; // If program is successfully completed, return 0. return EXIT_SUCCESS; ///////////////////////////////////////////////////////////////////////// }<commit_msg>Reduce solver tolerance (converging for 0-maneuver case.<commit_after> /* * Copyright (c) 2014, Dinamica Srl * Copyright (c) 2014, K. Kumar (kumar@dinamicatech.com) * All rights reserved. * See COPYING for license details. */ #include <iomanip> #include <limits> #include <cmath> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <boost/format.hpp> #include <boost/timer/timer.hpp> #include <Eigen/Core> #include <nlopt.hpp> #include <libsgp4/Eci.h> #include <libsgp4/DateTime.h> #include <libsgp4/Globals.h> #include <libsgp4/SGP4.h> #include <libsgp4/Tle.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/physicalConstants.h> #include <TudatCore/Astrodynamics/BasicAstrodynamics/unitConversions.h> #include <TudatCore/Mathematics/BasicMathematics/basicMathematicsFunctions.h> #include <TudatCore/Mathematics/BasicMathematics/mathematicalConstants.h> #include <Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.h> #include <D2D/cartesianToTwoLineElementsObjectiveFunction.h> //! Execute D2D test app. int main( const int numberOfInputs, const char* inputArguments[ ] ) { /////////////////////////////////////////////////////////////////////////// // Start timer. Timer automatically ends when this object goes out of scope. boost::timer::auto_cpu_timer timer; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Declare using-statements. using std::cout; using std::endl; using std::string; using std::vector; using namespace tudat::basic_astrodynamics::orbital_element_conversions; using namespace tudat::basic_astrodynamics::unit_conversions; using namespace tudat::basic_astrodynamics::physical_constants; using namespace tudat::basic_mathematics; using namespace tudat::basic_mathematics::mathematical_constants; using namespace tudat::mission_segments; using namespace d2d; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Input deck. // Set depature epoch. const DateTime departureEpoch( 2014, 5, 23, 16, 0, 0 ); // Set time-of-flight [s]. // const double timeOfFlight = 1325.0; // Set TLE strings for 1st debris object. const string nameObject1 = "0 VANGUARD 1"; const string line1Object1 = "1 00005U 58002B 14143.59770889 -.00000036 00000-0 -22819-4 0 2222"; const string line2Object1 = "2 00005 034.2431 215.7533 1849786 098.8024 282.5368 10.84391811964621"; // Set TLE strings for 2nd debris object. // const string nameObject2 = "0 SCOUT D-1 R/B"; // const string line1Object2 // = "1 06800U 72091 B 79098.71793498 .00418782 +00000-0 +00000-0 0 03921"; // const string line2Object2 // = "2 06800 001.9047 136.0594 0024458 068.9289 290.1247 15.83301112263179"; // Set minimization tolerance. const double minimizationTolerance = 1.0e-3; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Compute derived parameters. // Set Earth gravitational parameter [m^3 s^-2]. const double earthGravitationalParameter = kMU * 1.0e9; // Compute arrival epoch. const DateTime arrivalEpoch( departureEpoch ); // arrivalEpoch.AddSeconds( timeOfFlight ); // Create TLE objects from strings. const Tle tleObject1( nameObject1, line1Object1, line2Object1 ); // const Tle tleObject2( nameObject2, line1Object2, line2Object2 ); // Set up SGP4 propagator objects. const SGP4 sgp4Object1( tleObject1 ); // const SGP4 sgp4Object2( tleObject2 ); // Compute Cartesian states of objects at departure and arrival epochs. const Eci departureState = sgp4Object1.FindPosition( departureEpoch ); // const Eci arrivalState = sgp4Object2.FindPosition( arrivalEpoch ); // Compute departure position [m] and velocity [ms^-1]. const Eigen::Vector3d depaturePosition( convertKilometersToMeters( departureState.Position( ).x ), convertKilometersToMeters( departureState.Position( ).y ), convertKilometersToMeters( departureState.Position( ).z ) ); const Eigen::Vector3d departureVelocity( convertKilometersToMeters( departureState.Velocity( ).x ), convertKilometersToMeters( departureState.Velocity( ).y ), convertKilometersToMeters( departureState.Velocity( ).z ) ); // Compute arrival position [m] and velocity [ms^-1]. // const Eigen::Vector3d arrivalPosition( // convertKilometersToMeters( arrivalState.Position( ).x ), // convertKilometersToMeters( arrivalState.Position( ).y ), // convertKilometersToMeters( arrivalState.Position( ).z ) ); // const Eigen::Vector3d arrivalVelocity( // convertKilometersToMeters( arrivalState.Velocity( ).x ), // convertKilometersToMeters( arrivalState.Velocity( ).y ), // convertKilometersToMeters( arrivalState.Velocity( ).z ) ); // Set up Lambert targeter. This automatically triggers the solver to execute. // LambertTargeterIzzo lambertTargeter( // depaturePosition, arrivalPosition, timeOfFlight, earthGravitationalParameter ); // // Compute Delta V at departure position [ms^-1]. // cout << "Delta V_dep: " // << std::fabs( // lambertTargeter.getInertialVelocityAtDeparture( ).norm( ) // - departureVelocity.norm( ) ) // << " m/s" << endl; // Set Cartesian state at departure after executing maneuver. const Eigen::VectorXd departureStateAfterManeuver = ( Eigen::VectorXd( 6 ) << depaturePosition, // lambertTargeter.getInertialVelocityAtDeparture( ) ).finished( ); departureVelocity // + Eigen::Vector3d( 50.0, 25.0, -10.0 ) ).finished( ); // Set initial guess for TLE mean elements. const Eigen::VectorXd newTleMeanElementsGuess = ( Eigen::VectorXd( 6 ) << tleObject1.Inclination( true ), tleObject1.RightAscendingNode( true ), tleObject1.Eccentricity( ), tleObject1.ArgumentPerigee( true ), tleObject1.MeanAnomaly( true ), tleObject1.MeanMotion( ) ).finished( ); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Compute TLE for object 1 at departure epoch. // Set up derivative-free optimizer. nlopt::opt optimizer( nlopt::LN_BOBYQA, 6 ); // Set up parameters for objective function. ObjectiveFunctionParameters parameters( earthGravitationalParameter, tleObject1, departureStateAfterManeuver, departureEpoch ); // Set objective function. optimizer.set_min_objective( cartesianToTwoLineElementsObjectiveFunction, &parameters ); // Set tolerance. optimizer.set_xtol_rel( minimizationTolerance ); // Set lower bounds. // std::vector< double > lowerBounds( 6, -HUGE_VAL ); // // lowerBounds.at( semiMajorAxisIndex ) = 6.0e6; // lowerBounds.at( eccentricityIndex ) = 0.0; // // lowerBounds.at( inclinationIndex ) = 0.0; // // lowerBounds.at( argumentOfPeriapsisIndex ) = 0.0; // // lowerBounds.at( longitudeOfAscendingNodeIndex ) = 0.0; // // lowerBounds.at( trueAnomalyIndex ) = 0.0; // optimizer.set_lower_bounds( lowerBounds ); // Set upper bounds. // std::vector< double > upperBounds( 6, HUGE_VAL ); // // lowerBounds.at( semiMajorAxisIndex ) = 5.0e7; // upperBounds.at( eccentricityIndex ) = 1.0; // // upperBounds.at( inclinationIndex ) = PI; // // upperBounds.at( argumentOfPeriapsisIndex ) = 2.0 * PI; // // upperBounds.at( longitudeOfAscendingNodeIndex ) = 2.0 * PI; // // upperBounds.at( trueAnomalyIndex ) = 2.0 * PI; // optimizer.set_upper_bounds( upperBounds ); // Set initial guess for decision vector to the TLE mean elements at departure. vector< double > decisionVector( 6 ); Eigen::Map< Eigen::VectorXd >( decisionVector.data( ), 6, 1 ) = newTleMeanElementsGuess; // Set initial step size. optimizer.set_initial_step( 1.0e-6 ); // Execute optimizer. double minimumFunctionValue; nlopt::result result = optimizer.optimize( decisionVector, minimumFunctionValue ); // Print output statements. if ( result < 0 ) { cout << "NLOPT failed!" << endl; } else { cout << "found minimum = " << minimumFunctionValue << endl; } // Print number of iterations taken by optimizer. cout << endl; cout << "# of iterations: " << optimizerIterations << endl; cout << endl; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// cout << "Timing information: "; // If program is successfully completed, return 0. return EXIT_SUCCESS; ///////////////////////////////////////////////////////////////////////// }<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskManualPositionSmoothVel.hpp * * Flight task for smooth manual controlled position. */ #pragma once #include "FlightTaskManualPosition.hpp" #include "VelocitySmoothing.hpp" class FlightTaskManualPositionSmoothVel : public FlightTaskManualPosition { public: FlightTaskManualPositionSmoothVel() = default; virtual ~FlightTaskManualPositionSmoothVel() = default; bool activate() override; void reActivate() override; protected: virtual void _updateSetpoints() override; DEFINE_PARAMETERS_CUSTOM_PARENT(FlightTaskManualPosition, (ParamFloat<px4::params::MPC_JERK_MIN>) _param_mpc_jerk_min, /**< Minimum jerk (velocity-based if > 0) */ (ParamFloat<px4::params::MPC_JERK_MAX>) _param_mpc_jerk_max, (ParamFloat<px4::params::MPC_ACC_UP_MAX>) _param_mpc_acc_up_max, (ParamFloat<px4::params::MPC_ACC_DOWN_MAX>) _param_mpc_acc_down_max ) private: enum class Axes {XY, XYZ}; /** * Reset the required axes. when force_z_zero is set to true, the z derivatives are set to sero and not to the estimated states */ void reset(Axes axes, bool force_z_zero = false); void _checkEkfResetCounters(); /**< Reset the trajectories when the ekf resets velocity or position */ VelocitySmoothing _smoothing[3]; ///< Smoothing in x, y and z directions matrix::Vector3f _vel_sp_smooth; bool _position_lock_xy_active{false}; bool _position_lock_z_active{false}; matrix::Vector2f _position_setpoint_xy_locked; float _position_setpoint_z_locked{NAN}; /* counters for estimator local position resets */ struct { uint8_t xy; uint8_t vxy; uint8_t z; uint8_t vz; } _reset_counters{0, 0, 0, 0}; }; <commit_msg>ManualSmoothVel - Remove unused _param_mpc_jerk_min declaration<commit_after>/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskManualPositionSmoothVel.hpp * * Flight task for smooth manual controlled position. */ #pragma once #include "FlightTaskManualPosition.hpp" #include "VelocitySmoothing.hpp" class FlightTaskManualPositionSmoothVel : public FlightTaskManualPosition { public: FlightTaskManualPositionSmoothVel() = default; virtual ~FlightTaskManualPositionSmoothVel() = default; bool activate() override; void reActivate() override; protected: virtual void _updateSetpoints() override; DEFINE_PARAMETERS_CUSTOM_PARENT(FlightTaskManualPosition, (ParamFloat<px4::params::MPC_JERK_MAX>) _param_mpc_jerk_max, (ParamFloat<px4::params::MPC_ACC_UP_MAX>) _param_mpc_acc_up_max, (ParamFloat<px4::params::MPC_ACC_DOWN_MAX>) _param_mpc_acc_down_max ) private: enum class Axes {XY, XYZ}; /** * Reset the required axes. when force_z_zero is set to true, the z derivatives are set to sero and not to the estimated states */ void reset(Axes axes, bool force_z_zero = false); void _checkEkfResetCounters(); /**< Reset the trajectories when the ekf resets velocity or position */ VelocitySmoothing _smoothing[3]; ///< Smoothing in x, y and z directions matrix::Vector3f _vel_sp_smooth; bool _position_lock_xy_active{false}; bool _position_lock_z_active{false}; matrix::Vector2f _position_setpoint_xy_locked; float _position_setpoint_z_locked{NAN}; /* counters for estimator local position resets */ struct { uint8_t xy; uint8_t vxy; uint8_t z; uint8_t vz; } _reset_counters{0, 0, 0, 0}; }; <|endoftext|>
<commit_before>/*- * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <thread> #include <chrono> #include <sstream> #include <vector> #include <set> #include <curses.h> #include "popupwindow.h" #include "inputwindow.h" #include "gfx.h" #include "ui.h" namespace portal { const std::string markerCategory("---"); const std::string markerFolded("-"); const std::string markerUnfolded("\\"); Ui::Ui() { filters_.set(); gfx::Gfx::instance().init(); createInterface(); updatePanes(); } Ui::~Ui() { gfx::Gfx::instance().terminate(); } void Ui::display() { for (const auto& pane : pane_) { pane->draw(); } tray_->display(); gfx::Gfx::instance().update(); } void Ui::handleEvent(const Event& event) { switch (event.type()) { case Event::Type::nextMode: selectNextMode(); pane_[pkgList]->clearStatus(); switch (currentMode_) { case Mode::browse: Pkg::instance().resetFilter(); break; case Mode::search: applySearch(); break; case Mode::filter: applyFilter(); break; } updatePanes(); updateTray(); break; case Event::Type::select: { if (!Pkg::instance().isRepositoryEmpty()) { if (gotCategorySelected()) { std::string category = getSelectedItemName(); toggleCategoryFolding(category); updatePanes(); } else { registerPkgChange(event.type()); updatePkgListPane(); } } break; } case Event::Type::deselect: if (!Pkg::instance().isRepositoryEmpty()) { registerPkgChange(event.type()); updatePkgListPane(); } break; case Event::Type::keyUp: case Event::Type::keyDown: if (!Pkg::instance().isRepositoryEmpty()) { if (event.type() == Event::Type::keyUp) { pane_[pkgList]->moveCursorUp(); } else if (event.type() == Event::Type::keyDown) { pane_[pkgList]->moveCursorDown(); } updatePkgDescrPane(); } break; case Event::Type::pageUp: case Event::Type::pageDown: if (!Pkg::instance().isRepositoryEmpty()) { if (event.type() == Event::Type::pageUp) { pane_[pkgDescr]->scrollUp(); } else if (event.type() == Event::Type::pageDown) { pane_[pkgDescr]->scrollDown(); } updatePkgDescrPane(); } break; case Event::Type::character: switch (currentMode_) { case Mode::browse: // DO NOTHING break; case Mode::search: pane_[pkgList]->resetCursorPosition(); promptSearch(event.character()); applySearch(); updatePanes(); break; case Mode::filter: pane_[pkgList]->resetCursorPosition(); promptFilter(event.character()); applyFilter(); updatePanes(); break; } break; case Event::Type::go: if (!Pkg::instance().gotRootPrivileges()) { gfx::PopupWindow("Insufficient privileges, please retry as root", gfx::PopupWindow::Type::warning); } else { performPending(); closeAllFolds(); updatePanes(); } break; case Event::Type::redraw: display(); break; default: break; } } /* +------------------------------+ | | \ | | | | | | pane_[pkgList] | | | | | / +------------------------------+ | | \ <-- comment | | | | | / pane_[pkgDescr] +------------------------------+ */ void Ui::createInterface() { int pkgPaneHeight = LINES * .6; int descrPaneHeight = LINES - pkgPaneHeight - 1; gfx::Size listSize, descrSize; listSize.setWidth(COLS); listSize.setHeight(pkgPaneHeight); descrSize.setWidth(COLS); descrSize.setHeight(descrPaneHeight); gfx::Point listPos, descrPos; descrPos.setY(pkgPaneHeight); pane_[pkgList] = std::unique_ptr<gfx::Pane>(new gfx::Pane(listSize, listPos)); pane_[pkgDescr] = std::unique_ptr<gfx::Pane>(new gfx::Pane(descrSize, descrPos)); pane_[pkgDescr]->borders(false); pane_[pkgDescr]->cursorLineHighlight(false); gfx::Point trayPos; trayPos.setY(pkgPaneHeight); trayPos.setX(COLS / 2); tray_ = std::unique_ptr<gfx::Tray>(new gfx::Tray(trayPos, Mode::nbModes)); } void Ui::updatePanes() { if (Pkg::instance().isRepositoryEmpty()) { for (auto& pane : pane_) { pane->clear(); pane->resetCursorPosition(); } } else { updatePkgListPane(); updatePkgDescrPane(); } } void Ui::buildPkgList() { pkgList_.clear(); std::vector<std::string> categories = Pkg::instance().getPkgCategories(); for (const auto& category : categories) { pkgList_.push_back({pkgListItemType::category, category}); if (!isCategoryFolded(category)) { std::vector<std::string> origins = Pkg::instance().getPkgOrigins(category); for (const auto& origin : origins) { pkgList_.push_back({pkgListItemType::pkg, origin}); } } } } // Build a hierarchy of categories and ports: // // ---- category1 // ---\ category2 // - port1 // + port2 // ---- category3 void Ui::updatePkgListPane() { buildPkgList(); pane_[pkgList]->clear(); for (const auto& item : pkgList_) { switch (item.type) { case pkgListItemType::category: { std::string categoryString = getStringForCategory(item.name); pane_[pkgList]->print(categoryString); } break; case pkgListItemType::pkg: { std::string pkgString = getStringForPkg(item.name); pane_[pkgList]->print(pkgString); std::string pkgVersions = getVersionsForPkg(item.name); pane_[pkgList]->print(pkgVersions, gfx::Pane::Align::right); //if (Pkg::instance().hasPendingActions(item.name)) { // XXX change attributes // XXX Need to add a setRowStyle(const Style&, const Point& = current) method to Pane class //pane_[pkgList].addRowAttributes(dataGrid.height() - 1, gfx::ATTR_BOLD); //} } break; default: break; } pane_[pkgList]->newline(); } } void Ui::updatePkgDescrPane() { pane_[pkgDescr]->clear(); if (!gotCategorySelected()) { std::string origin = getSelectedItemName(); std::string comment = Pkg::instance().getPkgAttr(origin, Pkg::Attr::comment); pane_[pkgDescr]->print(comment); pane_[pkgDescr]->colorizeCurrentLine(gfx::Style::Color::cyan); std::string desc = Pkg::instance().getPkgAttr(origin, Pkg::Attr::description); std::stringstream commentStream(desc); std::string descLine; while (std::getline(commentStream, descLine, '\n')) { pane_[pkgDescr]->newline(); pane_[pkgDescr]->print(descLine); } } //pane_[pkgDescr].requestRefresh(); } const Ui::pkgListItem& Ui::getCurrentPkgListItem() const { int index = pane_[pkgList]->getCursorRowNum(); return pkgList_[index]; } std::string Ui::getSelectedItemName() const { const pkgListItem& item = getCurrentPkgListItem(); return item.name; } bool Ui::gotCategorySelected() { const pkgListItem& item = getCurrentPkgListItem(); return isCategory(item); } bool Ui::isCategory(const pkgListItem& item) const { return item.type == pkgListItemType::category; } void Ui::toggleCategoryFolding(const std::string& category) { if (unfolded_.find(category) != unfolded_.end()) { unfolded_[category] = unfolded_[category] == true ? false : true; } else { unfolded_[category] = true; } } void Ui::closeAllFolds() { unfolded_.clear(); pane_[pkgList]->resetCursorPosition(); } void Ui::registerPkgChange(Event::Type event) { if (!gotCategorySelected()) { std::string origin = getSelectedItemName(); switch (event) { case Event::Type::select: Pkg::instance().registerInstall(origin); break; case Event::Type::deselect: Pkg::instance().registerRemoval(origin); break; default: break; } } } void Ui::performPending() { busy_ = true; std::thread uiHint([this]() {busyStatus(*pane_[pkgList]);}); uiHint.detach(); std::thread pendingActions(&Pkg::performPending, &Pkg::instance()); pendingActions.join(); busy_ = false; } void Ui::promptFilter(int character) { switch (character) { case 'a': filters_.flip(Pkg::Statuses::available); break; case 'i': filters_.flip(Pkg::Statuses::installed); break; case 'p': filters_.flip(Pkg::Statuses::pendingInstall); break; case 'u': filters_.flip(Pkg::Statuses::upgradable); break; default: // DO NOTHING break; } } void Ui::applyFilter() const { static const std::string availableStatus = "(A)vailable"; static const std::string installedStatus = "(I)nstalled"; static const std::string pendingStatus = "(P)ending"; static const std::string upgradableStatus = "(U)pgradable"; static const std::string statusString = availableStatus + " / " + installedStatus + " / " + pendingStatus + " / " + upgradableStatus; Pkg::instance().applyFilter(filters_); pane_[pkgList]->clearStatus(); pane_[pkgList]->printStatus(statusString); gfx::Style unselectedStyle; unselectedStyle.color = gfx::Style::Color::black; unselectedStyle.bold = true; pane_[pkgList]->setStatusStyle(0, statusString.length(), unselectedStyle); gfx::Style selectedStyle; selectedStyle.color = gfx::Style::Color::magenta; int pos = 0; if (filters_[Pkg::Statuses::available]) { pane_[pkgList]->setStatusStyle(0, availableStatus.length(), selectedStyle); } pos += availableStatus.length() + 3; if (filters_[Pkg::Statuses::installed]) { pane_[pkgList]->setStatusStyle(pos, installedStatus.length(), selectedStyle); } pos += installedStatus.length() + 3; if (filters_[Pkg::Statuses::pendingInstall]) { pane_[pkgList]->setStatusStyle(pos, pendingStatus.length(), selectedStyle); } pos += pendingStatus.length() + 3; if (filters_[Pkg::Statuses::upgradable]) { pane_[pkgList]->setStatusStyle(pos, upgradableStatus.length(), selectedStyle); } } void Ui::promptSearch(int character) { gfx::Point pos = gfx::Point::Label::center; gfx::InputWindow inputWindow(pos, 40); inputWindow.setContent(std::string(1, static_cast<char>(character))); searchString_ = inputWindow.getInput(); } void Ui::applySearch() const { if (!searchString_.empty()) { Pkg::instance().search(searchString_); pane_[pkgList]->clearStatus(); gfx::Style promptStyle; promptStyle.color = gfx::Style::Color::magenta; pane_[pkgList]->printStatus(searchString_, promptStyle); } } void Ui::busyStatus(gfx::Pane& pane) { pane.clearStatus(); gfx::Style busyStyle; busyStyle.color = gfx::Style::Color::magenta; busyStyle.reverse = true; std::string busyString(" "); int busyStringLen = busyString.length(); pane.printStatus(busyString); for (;;) { for (int x = 0; x < busyStringLen; ++x) { if (!busy_) { pane.clearStatus(); pane.draw(); gfx::Gfx::instance().update(); return; } else { pane.setStatusStyle(0, busyStringLen, {}); pane.setStatusStyle(x, 1, busyStyle); pane.draw(); gfx::Gfx::instance().update(); std::this_thread::sleep_for(std::chrono::milliseconds(150)); } } } } bool Ui::isCategoryFolded(const std::string& category) const { return unfolded_.find(category) == unfolded_.end() || unfolded_.at(category) == false; } std::string Ui::getStringForCategory(const std::string& category) const { std::string categoryString(markerCategory); if (isCategoryFolded(category)) { categoryString.append(markerFolded); } else { categoryString.append(markerUnfolded); } categoryString.append(" "); categoryString.append(category); categoryString.append(" ("); categoryString.append(std::to_string(Pkg::instance().getCategorySize(category))); categoryString.append(")"); return categoryString; } std::string Ui::getStringForPkg(const std::string& origin) const { std::string pkgString = Pkg::instance().getCurrentStatusAsString(origin); if (Pkg::instance().hasPendingActions(origin)) { pkgString.append("["); pkgString.append(Pkg::instance().getPendingStatusAsString(origin)); pkgString.append("] "); } else if (Pkg::instance().isUpgradable(origin)) { pkgString.append("[^] "); } else { pkgString.append(" "); } pkgString.append(Pkg::instance().getNameFromOrigin(origin)); return pkgString; } std::string Ui::getVersionsForPkg(const std::string& origin) const { std::string pkgVersions = Pkg::instance().getLocalVersion(origin); if (!pkgVersions.empty()) { pkgVersions.append(" "); } pkgVersions.append(Pkg::instance().getRemoteVersion(origin)); return pkgVersions; } void Ui::selectNextMode() { ++currentMode_; if (currentMode_ == Mode::nbModes) { currentMode_ = 0; } } void Ui::updateTray() { tray_->selectSlot(currentMode_); std::thread popupModeName([this](){showCurrentModeName();}); popupModeName.detach(); } void Ui::showCurrentModeName() { gfx::Point center; center.setX(COLS / 2); center.setY(pane_[pkgList]->size().height() - 3); gfx::PopupWindow(modeName_[currentMode_], gfx::PopupWindow::Type::brief, center); } } <commit_msg>Use the new print method signature<commit_after>/*- * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <thread> #include <chrono> #include <sstream> #include <vector> #include <set> #include <curses.h> #include "popupwindow.h" #include "inputwindow.h" #include "gfx.h" #include "ui.h" namespace portal { const std::string markerCategory("---"); const std::string markerFolded("-"); const std::string markerUnfolded("\\"); Ui::Ui() { filters_.set(); gfx::Gfx::instance().init(); createInterface(); updatePanes(); } Ui::~Ui() { gfx::Gfx::instance().terminate(); } void Ui::display() { for (const auto& pane : pane_) { pane->draw(); } tray_->display(); gfx::Gfx::instance().update(); } void Ui::handleEvent(const Event& event) { switch (event.type()) { case Event::Type::nextMode: selectNextMode(); pane_[pkgList]->clearStatus(); switch (currentMode_) { case Mode::browse: Pkg::instance().resetFilter(); break; case Mode::search: applySearch(); break; case Mode::filter: applyFilter(); break; } updatePanes(); updateTray(); break; case Event::Type::select: { if (!Pkg::instance().isRepositoryEmpty()) { if (gotCategorySelected()) { std::string category = getSelectedItemName(); toggleCategoryFolding(category); updatePanes(); } else { registerPkgChange(event.type()); updatePkgListPane(); } } break; } case Event::Type::deselect: if (!Pkg::instance().isRepositoryEmpty()) { registerPkgChange(event.type()); updatePkgListPane(); } break; case Event::Type::keyUp: case Event::Type::keyDown: if (!Pkg::instance().isRepositoryEmpty()) { if (event.type() == Event::Type::keyUp) { pane_[pkgList]->moveCursorUp(); } else if (event.type() == Event::Type::keyDown) { pane_[pkgList]->moveCursorDown(); } updatePkgDescrPane(); } break; case Event::Type::pageUp: case Event::Type::pageDown: if (!Pkg::instance().isRepositoryEmpty()) { if (event.type() == Event::Type::pageUp) { pane_[pkgDescr]->scrollUp(); } else if (event.type() == Event::Type::pageDown) { pane_[pkgDescr]->scrollDown(); } updatePkgDescrPane(); } break; case Event::Type::character: switch (currentMode_) { case Mode::browse: // DO NOTHING break; case Mode::search: pane_[pkgList]->resetCursorPosition(); promptSearch(event.character()); applySearch(); updatePanes(); break; case Mode::filter: pane_[pkgList]->resetCursorPosition(); promptFilter(event.character()); applyFilter(); updatePanes(); break; } break; case Event::Type::go: if (!Pkg::instance().gotRootPrivileges()) { gfx::PopupWindow("Insufficient privileges, please retry as root", gfx::PopupWindow::Type::warning); } else { performPending(); closeAllFolds(); updatePanes(); } break; case Event::Type::redraw: display(); break; default: break; } } /* +------------------------------+ | | \ | | | | | | pane_[pkgList] | | | | | / +------------------------------+ | | \ <-- comment | | | | | / pane_[pkgDescr] +------------------------------+ */ void Ui::createInterface() { int pkgPaneHeight = LINES * .6; int descrPaneHeight = LINES - pkgPaneHeight - 1; gfx::Size listSize, descrSize; listSize.setWidth(COLS); listSize.setHeight(pkgPaneHeight); descrSize.setWidth(COLS); descrSize.setHeight(descrPaneHeight); gfx::Point listPos, descrPos; descrPos.setY(pkgPaneHeight); pane_[pkgList] = std::unique_ptr<gfx::Pane>(new gfx::Pane(listSize, listPos)); pane_[pkgDescr] = std::unique_ptr<gfx::Pane>(new gfx::Pane(descrSize, descrPos)); pane_[pkgDescr]->borders(false); pane_[pkgDescr]->cursorLineHighlight(false); gfx::Point trayPos; trayPos.setY(pkgPaneHeight); trayPos.setX(COLS / 2); tray_ = std::unique_ptr<gfx::Tray>(new gfx::Tray(trayPos, Mode::nbModes)); } void Ui::updatePanes() { if (Pkg::instance().isRepositoryEmpty()) { for (auto& pane : pane_) { pane->clear(); pane->resetCursorPosition(); } } else { updatePkgListPane(); updatePkgDescrPane(); } } void Ui::buildPkgList() { pkgList_.clear(); std::vector<std::string> categories = Pkg::instance().getPkgCategories(); for (const auto& category : categories) { pkgList_.push_back({pkgListItemType::category, category}); if (!isCategoryFolded(category)) { std::vector<std::string> origins = Pkg::instance().getPkgOrigins(category); for (const auto& origin : origins) { pkgList_.push_back({pkgListItemType::pkg, origin}); } } } } // Build a hierarchy of categories and ports: // // ---- category1 // ---\ category2 // - port1 // + port2 // ---- category3 void Ui::updatePkgListPane() { buildPkgList(); pane_[pkgList]->clear(); gfx::Style rightAligned; rightAligned.align = gfx::Style::Alignment::right; for (const auto& item : pkgList_) { switch (item.type) { case pkgListItemType::category: { std::string categoryString = getStringForCategory(item.name); pane_[pkgList]->print(categoryString); } break; case pkgListItemType::pkg: { std::string pkgString = getStringForPkg(item.name); pane_[pkgList]->print(pkgString); std::string pkgVersions = getVersionsForPkg(item.name); pane_[pkgList]->print(pkgVersions, rightAligned); } break; default: break; } pane_[pkgList]->newline(); } } void Ui::updatePkgDescrPane() { pane_[pkgDescr]->clear(); if (!gotCategorySelected()) { std::string origin = getSelectedItemName(); std::string comment = Pkg::instance().getPkgAttr(origin, Pkg::Attr::comment); pane_[pkgDescr]->print(comment); pane_[pkgDescr]->colorizeCurrentLine(gfx::Style::Color::cyan); std::string desc = Pkg::instance().getPkgAttr(origin, Pkg::Attr::description); std::stringstream commentStream(desc); std::string descLine; while (std::getline(commentStream, descLine, '\n')) { pane_[pkgDescr]->newline(); pane_[pkgDescr]->print(descLine); } } } const Ui::pkgListItem& Ui::getCurrentPkgListItem() const { int index = pane_[pkgList]->getCursorRowNum(); return pkgList_[index]; } std::string Ui::getSelectedItemName() const { const pkgListItem& item = getCurrentPkgListItem(); return item.name; } bool Ui::gotCategorySelected() { const pkgListItem& item = getCurrentPkgListItem(); return isCategory(item); } bool Ui::isCategory(const pkgListItem& item) const { return item.type == pkgListItemType::category; } void Ui::toggleCategoryFolding(const std::string& category) { if (unfolded_.find(category) != unfolded_.end()) { unfolded_[category] = unfolded_[category] == true ? false : true; } else { unfolded_[category] = true; } } void Ui::closeAllFolds() { unfolded_.clear(); pane_[pkgList]->resetCursorPosition(); } void Ui::registerPkgChange(Event::Type event) { if (!gotCategorySelected()) { std::string origin = getSelectedItemName(); switch (event) { case Event::Type::select: Pkg::instance().registerInstall(origin); break; case Event::Type::deselect: Pkg::instance().registerRemoval(origin); break; default: break; } } } void Ui::performPending() { busy_ = true; std::thread uiHint([this]() {busyStatus(*pane_[pkgList]);}); uiHint.detach(); std::thread pendingActions(&Pkg::performPending, &Pkg::instance()); pendingActions.join(); busy_ = false; } void Ui::promptFilter(int character) { switch (character) { case 'a': filters_.flip(Pkg::Statuses::available); break; case 'i': filters_.flip(Pkg::Statuses::installed); break; case 'p': filters_.flip(Pkg::Statuses::pendingInstall); break; case 'u': filters_.flip(Pkg::Statuses::upgradable); break; default: // DO NOTHING break; } } void Ui::applyFilter() const { static const std::string availableStatus = "(A)vailable"; static const std::string installedStatus = "(I)nstalled"; static const std::string pendingStatus = "(P)ending"; static const std::string upgradableStatus = "(U)pgradable"; static const std::string statusString = availableStatus + " / " + installedStatus + " / " + pendingStatus + " / " + upgradableStatus; Pkg::instance().applyFilter(filters_); pane_[pkgList]->clearStatus(); pane_[pkgList]->printStatus(statusString); gfx::Style unselectedStyle; unselectedStyle.color = gfx::Style::Color::black; unselectedStyle.bold = true; pane_[pkgList]->setStatusStyle(0, statusString.length(), unselectedStyle); gfx::Style selectedStyle; selectedStyle.color = gfx::Style::Color::magenta; int pos = 0; if (filters_[Pkg::Statuses::available]) { pane_[pkgList]->setStatusStyle(0, availableStatus.length(), selectedStyle); } pos += availableStatus.length() + 3; if (filters_[Pkg::Statuses::installed]) { pane_[pkgList]->setStatusStyle(pos, installedStatus.length(), selectedStyle); } pos += installedStatus.length() + 3; if (filters_[Pkg::Statuses::pendingInstall]) { pane_[pkgList]->setStatusStyle(pos, pendingStatus.length(), selectedStyle); } pos += pendingStatus.length() + 3; if (filters_[Pkg::Statuses::upgradable]) { pane_[pkgList]->setStatusStyle(pos, upgradableStatus.length(), selectedStyle); } } void Ui::promptSearch(int character) { gfx::Point pos = gfx::Point::Label::center; gfx::InputWindow inputWindow(pos, 40); inputWindow.setContent(std::string(1, static_cast<char>(character))); searchString_ = inputWindow.getInput(); } void Ui::applySearch() const { if (!searchString_.empty()) { Pkg::instance().search(searchString_); pane_[pkgList]->clearStatus(); gfx::Style promptStyle; promptStyle.color = gfx::Style::Color::magenta; pane_[pkgList]->printStatus(searchString_, promptStyle); } } void Ui::busyStatus(gfx::Pane& pane) { pane.clearStatus(); gfx::Style busyStyle; busyStyle.color = gfx::Style::Color::magenta; busyStyle.reverse = true; std::string busyString(" "); int busyStringLen = busyString.length(); pane.printStatus(busyString); for (;;) { for (int x = 0; x < busyStringLen; ++x) { if (!busy_) { pane.clearStatus(); pane.draw(); gfx::Gfx::instance().update(); return; } else { pane.setStatusStyle(0, busyStringLen, {}); pane.setStatusStyle(x, 1, busyStyle); pane.draw(); gfx::Gfx::instance().update(); std::this_thread::sleep_for(std::chrono::milliseconds(150)); } } } } bool Ui::isCategoryFolded(const std::string& category) const { return unfolded_.find(category) == unfolded_.end() || unfolded_.at(category) == false; } std::string Ui::getStringForCategory(const std::string& category) const { std::string categoryString(markerCategory); if (isCategoryFolded(category)) { categoryString.append(markerFolded); } else { categoryString.append(markerUnfolded); } categoryString.append(" "); categoryString.append(category); categoryString.append(" ("); categoryString.append(std::to_string(Pkg::instance().getCategorySize(category))); categoryString.append(")"); return categoryString; } std::string Ui::getStringForPkg(const std::string& origin) const { std::string pkgString = Pkg::instance().getCurrentStatusAsString(origin); if (Pkg::instance().hasPendingActions(origin)) { pkgString.append("["); pkgString.append(Pkg::instance().getPendingStatusAsString(origin)); pkgString.append("] "); } else if (Pkg::instance().isUpgradable(origin)) { pkgString.append("[^] "); } else { pkgString.append(" "); } pkgString.append(Pkg::instance().getNameFromOrigin(origin)); return pkgString; } std::string Ui::getVersionsForPkg(const std::string& origin) const { std::string pkgVersions = Pkg::instance().getLocalVersion(origin); if (!pkgVersions.empty()) { pkgVersions.append(" "); } pkgVersions.append(Pkg::instance().getRemoteVersion(origin)); return pkgVersions; } void Ui::selectNextMode() { ++currentMode_; if (currentMode_ == Mode::nbModes) { currentMode_ = 0; } } void Ui::updateTray() { tray_->selectSlot(currentMode_); std::thread popupModeName([this](){showCurrentModeName();}); popupModeName.detach(); } void Ui::showCurrentModeName() { gfx::Point center; center.setX(COLS / 2); center.setY(pane_[pkgList]->size().height() - 3); gfx::PopupWindow(modeName_[currentMode_], gfx::PopupWindow::Type::brief, center); } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2016-2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file input_mavlink.cpp * @author Leon Müller (thedevleon) * @author Beat Küng <beat-kueng@gmx.net> * */ #include "input_mavlink.h" #include <uORB/uORB.h> #include <uORB/topics/vehicle_roi.h> #include <uORB/topics/vehicle_command_ack.h> #include <uORB/topics/position_setpoint_triplet.h> #include <drivers/drv_hrt.h> #include <px4_defines.h> #include <px4_posix.h> #include <errno.h> namespace vmount { InputMavlinkROI::~InputMavlinkROI() { if (_vehicle_roi_sub >= 0) { orb_unsubscribe(_vehicle_roi_sub); } if (_position_setpoint_triplet_sub >= 0) { orb_unsubscribe(_position_setpoint_triplet_sub); } } int InputMavlinkROI::initialize() { _vehicle_roi_sub = orb_subscribe(ORB_ID(vehicle_roi)); if (_vehicle_roi_sub < 0) { return -errno; } _position_setpoint_triplet_sub = orb_subscribe(ORB_ID(position_setpoint_triplet)); if (_position_setpoint_triplet_sub < 0) { return -errno; } return 0; } int InputMavlinkROI::update_impl(unsigned int timeout_ms, ControlData **control_data, bool already_active) { // already_active is unused, we don't care what happened previously. // Default to no change, set if we receive anything. *control_data = nullptr; const int num_poll = 2; px4_pollfd_struct_t polls[num_poll]; polls[0].fd = _vehicle_roi_sub; polls[0].events = POLLIN; polls[1].fd = _position_setpoint_triplet_sub; polls[1].events = POLLIN; int ret = px4_poll(polls, num_poll, timeout_ms); if (ret < 0) { return -errno; } if (ret == 0) { // Timeout, _control_data is already null } else { if (polls[0].revents & POLLIN) { vehicle_roi_s vehicle_roi; orb_copy(ORB_ID(vehicle_roi), _vehicle_roi_sub, &vehicle_roi); _control_data.gimbal_shutter_retract = false; if (vehicle_roi.mode == vehicle_roi_s::ROI_NONE) { _control_data.type = ControlData::Type::Neutral; *control_data = &_control_data; } else if (vehicle_roi.mode == vehicle_roi_s::ROI_WPNEXT) { _control_data.type = ControlData::Type::LonLat; _read_control_data_from_position_setpoint_sub(); _control_data.type_data.lonlat.pitch_fixed_angle = -10.f; _control_data.type_data.lonlat.roll_angle = vehicle_roi.roll_offset; _control_data.type_data.lonlat.pitch_angle_offset = vehicle_roi.pitch_offset; _control_data.type_data.lonlat.yaw_angle_offset = vehicle_roi.yaw_offset; *control_data = &_control_data; } else if (vehicle_roi.mode == vehicle_roi_s::ROI_LOCATION) { control_data_set_lon_lat(vehicle_roi.lon, vehicle_roi.lat, vehicle_roi.alt); *control_data = &_control_data; } else if (vehicle_roi.mode == vehicle_roi_s::ROI_TARGET) { //TODO is this even suported? } _cur_roi_mode = vehicle_roi.mode; //set all other control data fields to defaults for (int i = 0; i < 3; ++i) { _control_data.stabilize_axis[i] = false; } } // check whether the position setpoint got updated if (polls[1].revents & POLLIN) { if (_cur_roi_mode == vehicle_roi_s::ROI_WPNEXT) { _read_control_data_from_position_setpoint_sub(); *control_data = &_control_data; } else { // must do an orb_copy() in *every* case position_setpoint_triplet_s position_setpoint_triplet; orb_copy(ORB_ID(position_setpoint_triplet), _position_setpoint_triplet_sub, &position_setpoint_triplet); } } } return 0; } void InputMavlinkROI::_read_control_data_from_position_setpoint_sub() { position_setpoint_triplet_s position_setpoint_triplet; orb_copy(ORB_ID(position_setpoint_triplet), _position_setpoint_triplet_sub, &position_setpoint_triplet); _control_data.type_data.lonlat.lon = position_setpoint_triplet.next.lon; _control_data.type_data.lonlat.lat = position_setpoint_triplet.next.lat; _control_data.type_data.lonlat.altitude = position_setpoint_triplet.next.alt; } void InputMavlinkROI::print_status() { PX4_INFO("Input: Mavlink (ROI)"); } InputMavlinkCmdMount::InputMavlinkCmdMount(bool stabilize) : _stabilize {stabilize, stabilize, stabilize} { param_t handle = param_find("MAV_SYS_ID"); if (handle != PARAM_INVALID) { param_get(handle, &_mav_sys_id); } handle = param_find("MAV_COMP_ID"); if (handle != PARAM_INVALID) { param_get(handle, &_mav_comp_id); } } InputMavlinkCmdMount::~InputMavlinkCmdMount() { if (_vehicle_command_sub >= 0) { orb_unsubscribe(_vehicle_command_sub); } } int InputMavlinkCmdMount::initialize() { if ((_vehicle_command_sub = orb_subscribe(ORB_ID(vehicle_command))) < 0) { return -errno; } // rate-limit inputs to 100Hz. If we don't do this and the output is configured to mavlink mode, // it will publish vehicle_command's as well, causing the input poll() in here to return // immediately, which in turn will cause an output update and thus a busy loop. orb_set_interval(_vehicle_command_sub, 10); return 0; } int InputMavlinkCmdMount::update_impl(unsigned int timeout_ms, ControlData **control_data, bool already_active) { // Default to notify that there was no change. *control_data = nullptr; const int num_poll = 1; px4_pollfd_struct_t polls[num_poll]; polls[0].fd = _vehicle_command_sub; polls[0].events = POLLIN; int poll_timeout = (int)timeout_ms; bool exit_loop = false; while (!exit_loop && poll_timeout >= 0) { hrt_abstime poll_start = hrt_absolute_time(); int ret = px4_poll(polls, num_poll, poll_timeout); if (ret < 0) { return -errno; } poll_timeout -= (hrt_absolute_time() - poll_start) / 1000; // if we get a command that we need to handle, we exit the loop, otherwise we poll until we reach the timeout exit_loop = true; if (ret == 0) { // Timeout control_data already null. } else { if (polls[0].revents & POLLIN) { vehicle_command_s vehicle_command; orb_copy(ORB_ID(vehicle_command), _vehicle_command_sub, &vehicle_command); // Process only if the command is for us or for anyone (component id 0). const bool sysid_correct = (vehicle_command.target_system == _mav_sys_id); const bool compid_correct = ((vehicle_command.target_component == _mav_comp_id) || (vehicle_command.target_component == 0)); if (!sysid_correct || !compid_correct) { exit_loop = false; continue; } for (int i = 0; i < 3; ++i) { _control_data.stabilize_axis[i] = _stabilize[i]; } _control_data.gimbal_shutter_retract = false; if (vehicle_command.command == vehicle_command_s::VEHICLE_CMD_DO_MOUNT_CONTROL) { switch ((int)vehicle_command.param7) { case vehicle_command_s::VEHICLE_MOUNT_MODE_RETRACT: _control_data.gimbal_shutter_retract = true; /* FALLTHROUGH */ case vehicle_command_s::VEHICLE_MOUNT_MODE_NEUTRAL: _control_data.type = ControlData::Type::Neutral; *control_data = &_control_data; break; case vehicle_command_s::VEHICLE_MOUNT_MODE_MAVLINK_TARGETING: _control_data.type = ControlData::Type::Angle; _control_data.type_data.angle.is_speed[0] = false; _control_data.type_data.angle.is_speed[1] = false; _control_data.type_data.angle.is_speed[2] = false; // vmount spec has roll on channel 0, MAVLink spec has pitch on channel 0 _control_data.type_data.angle.angles[0] = vehicle_command.param2 * M_DEG_TO_RAD_F; // vmount spec has pitch on channel 1, MAVLink spec has roll on channel 1 _control_data.type_data.angle.angles[1] = vehicle_command.param1 * M_DEG_TO_RAD_F; // both specs have yaw on channel 2 _control_data.type_data.angle.angles[2] = vehicle_command.param3 * M_DEG_TO_RAD_F; // We expect angle of [-pi..+pi]. If the input range is [0..2pi] we can fix that. if (_control_data.type_data.angle.angles[2] > M_PI_F) { _control_data.type_data.angle.angles[2] -= 2 * M_PI_F; } *control_data = &_control_data; break; case vehicle_command_s::VEHICLE_MOUNT_MODE_RC_TARGETING: break; case vehicle_command_s::VEHICLE_MOUNT_MODE_GPS_POINT: control_data_set_lon_lat((double)vehicle_command.param2, (double)vehicle_command.param1, vehicle_command.param3); *control_data = &_control_data; break; } _ack_vehicle_command(&vehicle_command); } else if (vehicle_command.command == vehicle_command_s::VEHICLE_CMD_DO_MOUNT_CONFIGURE) { _stabilize[0] = (uint8_t) vehicle_command.param2 == 1; _stabilize[1] = (uint8_t) vehicle_command.param3 == 1; _stabilize[2] = (uint8_t) vehicle_command.param4 == 1; _control_data.type = ControlData::Type::Neutral; //always switch to neutral position *control_data = &_control_data; _ack_vehicle_command(&vehicle_command); } else { exit_loop = false; } } } } return 0; } void InputMavlinkCmdMount::_ack_vehicle_command(vehicle_command_s *cmd) { vehicle_command_ack_s vehicle_command_ack = { .timestamp = hrt_absolute_time(), .result_param2 = 0, .command = cmd->command, .result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED, .from_external = false, .result_param1 = 0, .target_system = cmd->source_system, .target_component = cmd->source_component }; if (_vehicle_command_ack_pub == nullptr) { _vehicle_command_ack_pub = orb_advertise_queue(ORB_ID(vehicle_command_ack), &vehicle_command_ack, vehicle_command_ack_s::ORB_QUEUE_LENGTH); } else { orb_publish(ORB_ID(vehicle_command_ack), _vehicle_command_ack_pub, &vehicle_command_ack); } } void InputMavlinkCmdMount::print_status() { PX4_INFO("Input: Mavlink (CMD_MOUNT)"); } } /* namespace vmount */ <commit_msg>vmount: input_mavlink point gimbal towards current triplet instead of next (#9405)<commit_after>/**************************************************************************** * * Copyright (c) 2016-2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file input_mavlink.cpp * @author Leon Müller (thedevleon) * @author Beat Küng <beat-kueng@gmx.net> * */ #include "input_mavlink.h" #include <uORB/uORB.h> #include <uORB/topics/vehicle_roi.h> #include <uORB/topics/vehicle_command_ack.h> #include <uORB/topics/position_setpoint_triplet.h> #include <drivers/drv_hrt.h> #include <px4_defines.h> #include <px4_posix.h> #include <errno.h> namespace vmount { InputMavlinkROI::~InputMavlinkROI() { if (_vehicle_roi_sub >= 0) { orb_unsubscribe(_vehicle_roi_sub); } if (_position_setpoint_triplet_sub >= 0) { orb_unsubscribe(_position_setpoint_triplet_sub); } } int InputMavlinkROI::initialize() { _vehicle_roi_sub = orb_subscribe(ORB_ID(vehicle_roi)); if (_vehicle_roi_sub < 0) { return -errno; } _position_setpoint_triplet_sub = orb_subscribe(ORB_ID(position_setpoint_triplet)); if (_position_setpoint_triplet_sub < 0) { return -errno; } return 0; } int InputMavlinkROI::update_impl(unsigned int timeout_ms, ControlData **control_data, bool already_active) { // already_active is unused, we don't care what happened previously. // Default to no change, set if we receive anything. *control_data = nullptr; const int num_poll = 2; px4_pollfd_struct_t polls[num_poll]; polls[0].fd = _vehicle_roi_sub; polls[0].events = POLLIN; polls[1].fd = _position_setpoint_triplet_sub; polls[1].events = POLLIN; int ret = px4_poll(polls, num_poll, timeout_ms); if (ret < 0) { return -errno; } if (ret == 0) { // Timeout, _control_data is already null } else { if (polls[0].revents & POLLIN) { vehicle_roi_s vehicle_roi; orb_copy(ORB_ID(vehicle_roi), _vehicle_roi_sub, &vehicle_roi); _control_data.gimbal_shutter_retract = false; if (vehicle_roi.mode == vehicle_roi_s::ROI_NONE) { _control_data.type = ControlData::Type::Neutral; *control_data = &_control_data; } else if (vehicle_roi.mode == vehicle_roi_s::ROI_WPNEXT) { _control_data.type = ControlData::Type::LonLat; _read_control_data_from_position_setpoint_sub(); _control_data.type_data.lonlat.pitch_fixed_angle = -10.f; _control_data.type_data.lonlat.roll_angle = vehicle_roi.roll_offset; _control_data.type_data.lonlat.pitch_angle_offset = vehicle_roi.pitch_offset; _control_data.type_data.lonlat.yaw_angle_offset = vehicle_roi.yaw_offset; *control_data = &_control_data; } else if (vehicle_roi.mode == vehicle_roi_s::ROI_LOCATION) { control_data_set_lon_lat(vehicle_roi.lon, vehicle_roi.lat, vehicle_roi.alt); *control_data = &_control_data; } else if (vehicle_roi.mode == vehicle_roi_s::ROI_TARGET) { //TODO is this even suported? } _cur_roi_mode = vehicle_roi.mode; //set all other control data fields to defaults for (int i = 0; i < 3; ++i) { _control_data.stabilize_axis[i] = false; } } // check whether the position setpoint got updated if (polls[1].revents & POLLIN) { if (_cur_roi_mode == vehicle_roi_s::ROI_WPNEXT) { _read_control_data_from_position_setpoint_sub(); *control_data = &_control_data; } else { // must do an orb_copy() in *every* case position_setpoint_triplet_s position_setpoint_triplet; orb_copy(ORB_ID(position_setpoint_triplet), _position_setpoint_triplet_sub, &position_setpoint_triplet); } } } return 0; } void InputMavlinkROI::_read_control_data_from_position_setpoint_sub() { position_setpoint_triplet_s position_setpoint_triplet; orb_copy(ORB_ID(position_setpoint_triplet), _position_setpoint_triplet_sub, &position_setpoint_triplet); _control_data.type_data.lonlat.lon = position_setpoint_triplet.current.lon; _control_data.type_data.lonlat.lat = position_setpoint_triplet.current.lat; _control_data.type_data.lonlat.altitude = position_setpoint_triplet.current.alt; } void InputMavlinkROI::print_status() { PX4_INFO("Input: Mavlink (ROI)"); } InputMavlinkCmdMount::InputMavlinkCmdMount(bool stabilize) : _stabilize {stabilize, stabilize, stabilize} { param_t handle = param_find("MAV_SYS_ID"); if (handle != PARAM_INVALID) { param_get(handle, &_mav_sys_id); } handle = param_find("MAV_COMP_ID"); if (handle != PARAM_INVALID) { param_get(handle, &_mav_comp_id); } } InputMavlinkCmdMount::~InputMavlinkCmdMount() { if (_vehicle_command_sub >= 0) { orb_unsubscribe(_vehicle_command_sub); } } int InputMavlinkCmdMount::initialize() { if ((_vehicle_command_sub = orb_subscribe(ORB_ID(vehicle_command))) < 0) { return -errno; } // rate-limit inputs to 100Hz. If we don't do this and the output is configured to mavlink mode, // it will publish vehicle_command's as well, causing the input poll() in here to return // immediately, which in turn will cause an output update and thus a busy loop. orb_set_interval(_vehicle_command_sub, 10); return 0; } int InputMavlinkCmdMount::update_impl(unsigned int timeout_ms, ControlData **control_data, bool already_active) { // Default to notify that there was no change. *control_data = nullptr; const int num_poll = 1; px4_pollfd_struct_t polls[num_poll]; polls[0].fd = _vehicle_command_sub; polls[0].events = POLLIN; int poll_timeout = (int)timeout_ms; bool exit_loop = false; while (!exit_loop && poll_timeout >= 0) { hrt_abstime poll_start = hrt_absolute_time(); int ret = px4_poll(polls, num_poll, poll_timeout); if (ret < 0) { return -errno; } poll_timeout -= (hrt_absolute_time() - poll_start) / 1000; // if we get a command that we need to handle, we exit the loop, otherwise we poll until we reach the timeout exit_loop = true; if (ret == 0) { // Timeout control_data already null. } else { if (polls[0].revents & POLLIN) { vehicle_command_s vehicle_command; orb_copy(ORB_ID(vehicle_command), _vehicle_command_sub, &vehicle_command); // Process only if the command is for us or for anyone (component id 0). const bool sysid_correct = (vehicle_command.target_system == _mav_sys_id); const bool compid_correct = ((vehicle_command.target_component == _mav_comp_id) || (vehicle_command.target_component == 0)); if (!sysid_correct || !compid_correct) { exit_loop = false; continue; } for (int i = 0; i < 3; ++i) { _control_data.stabilize_axis[i] = _stabilize[i]; } _control_data.gimbal_shutter_retract = false; if (vehicle_command.command == vehicle_command_s::VEHICLE_CMD_DO_MOUNT_CONTROL) { switch ((int)vehicle_command.param7) { case vehicle_command_s::VEHICLE_MOUNT_MODE_RETRACT: _control_data.gimbal_shutter_retract = true; /* FALLTHROUGH */ case vehicle_command_s::VEHICLE_MOUNT_MODE_NEUTRAL: _control_data.type = ControlData::Type::Neutral; *control_data = &_control_data; break; case vehicle_command_s::VEHICLE_MOUNT_MODE_MAVLINK_TARGETING: _control_data.type = ControlData::Type::Angle; _control_data.type_data.angle.is_speed[0] = false; _control_data.type_data.angle.is_speed[1] = false; _control_data.type_data.angle.is_speed[2] = false; // vmount spec has roll on channel 0, MAVLink spec has pitch on channel 0 _control_data.type_data.angle.angles[0] = vehicle_command.param2 * M_DEG_TO_RAD_F; // vmount spec has pitch on channel 1, MAVLink spec has roll on channel 1 _control_data.type_data.angle.angles[1] = vehicle_command.param1 * M_DEG_TO_RAD_F; // both specs have yaw on channel 2 _control_data.type_data.angle.angles[2] = vehicle_command.param3 * M_DEG_TO_RAD_F; // We expect angle of [-pi..+pi]. If the input range is [0..2pi] we can fix that. if (_control_data.type_data.angle.angles[2] > M_PI_F) { _control_data.type_data.angle.angles[2] -= 2 * M_PI_F; } *control_data = &_control_data; break; case vehicle_command_s::VEHICLE_MOUNT_MODE_RC_TARGETING: break; case vehicle_command_s::VEHICLE_MOUNT_MODE_GPS_POINT: control_data_set_lon_lat((double)vehicle_command.param2, (double)vehicle_command.param1, vehicle_command.param3); *control_data = &_control_data; break; } _ack_vehicle_command(&vehicle_command); } else if (vehicle_command.command == vehicle_command_s::VEHICLE_CMD_DO_MOUNT_CONFIGURE) { _stabilize[0] = (uint8_t) vehicle_command.param2 == 1; _stabilize[1] = (uint8_t) vehicle_command.param3 == 1; _stabilize[2] = (uint8_t) vehicle_command.param4 == 1; _control_data.type = ControlData::Type::Neutral; //always switch to neutral position *control_data = &_control_data; _ack_vehicle_command(&vehicle_command); } else { exit_loop = false; } } } } return 0; } void InputMavlinkCmdMount::_ack_vehicle_command(vehicle_command_s *cmd) { vehicle_command_ack_s vehicle_command_ack = { .timestamp = hrt_absolute_time(), .result_param2 = 0, .command = cmd->command, .result = vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED, .from_external = false, .result_param1 = 0, .target_system = cmd->source_system, .target_component = cmd->source_component }; if (_vehicle_command_ack_pub == nullptr) { _vehicle_command_ack_pub = orb_advertise_queue(ORB_ID(vehicle_command_ack), &vehicle_command_ack, vehicle_command_ack_s::ORB_QUEUE_LENGTH); } else { orb_publish(ORB_ID(vehicle_command_ack), _vehicle_command_ack_pub, &vehicle_command_ack); } } void InputMavlinkCmdMount::print_status() { PX4_INFO("Input: Mavlink (CMD_MOUNT)"); } } /* namespace vmount */ <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2020, The Regents of the University of California // All rights reserved. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "browserWidget.h" #include <QHeaderView> #include "utl/Logger.h" Q_DECLARE_METATYPE(odb::dbInst*); Q_DECLARE_METATYPE(odb::dbModule*); namespace gui { /////// BrowserWidget::BrowserWidget(QWidget* parent) : QDockWidget("Hierarchy Browser", parent), block_(nullptr), view_(new QTreeView(this)), model_(new QStandardItemModel(this)) { setObjectName("hierarchy_viewer"); // for settings model_->setHorizontalHeaderLabels({"Instance", "Master", "Area"}); view_->setModel(model_); QHeaderView* header = view_->header(); header->setStretchLastSection(false); header->setSectionResizeMode(0, QHeaderView::Stretch); header->setSectionResizeMode(1, QHeaderView::ResizeToContents); header->setSectionResizeMode(2, QHeaderView::ResizeToContents); setWidget(view_); connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clicked(const QModelIndex&))); connect(view_->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(selectionChanged(const QItemSelection&, const QItemSelection&))); } void BrowserWidget::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { auto indexes = selected.indexes(); if (indexes.isEmpty()) { return; } emit clicked(indexes.first()); } void BrowserWidget::clicked(const QModelIndex& index) { QStandardItem* item = model_->itemFromIndex(index); QVariant data = item->data(); if (data.isValid()) { auto* gui = Gui::get(); auto* inst = data.value<odb::dbInst*>(); if (inst != nullptr) { emit select(gui->makeSelected(inst)); } else { auto* module = data.value<odb::dbModule*>(); if (module != nullptr) { emit select(gui->makeSelected(module)); } } } } void BrowserWidget::setBlock(odb::dbBlock* block) { block_ = block; addOwner(block_); updateModel(); } void BrowserWidget::showEvent(QShowEvent* event) { addOwner(block_); updateModel(); } void BrowserWidget::hideEvent(QHideEvent* event) { removeOwner(); clearModel(); } void BrowserWidget::updateModel() { clearModel(); if (block_ == nullptr) { return; } auto* root = model_->invisibleRootItem(); populateModule(block_->getTopModule(), root); QStandardItem* orphans = new QStandardItem("Physical only"); orphans->setEditable(false); orphans->setSelectable(false); double area = 0; for (auto* inst : block_->getInsts()) { if (inst->getModule() != nullptr) { continue; } area += addInstanceItem(inst, orphans); } root->appendRow({orphans, new QStandardItem, makeSizeItem(area)}); } void BrowserWidget::clearModel() { model_->removeRows(0, model_->rowCount()); } int64_t BrowserWidget::populateModule(odb::dbModule* module, QStandardItem* parent) { int64_t leaf_area = 0; auto* leafs = new QStandardItem("Leaf instances"); leafs->setEditable(false); leafs->setSelectable(false); for (auto* inst : module->getInsts()) { leaf_area += addInstanceItem(inst, leafs); } int64_t area = 0; for (auto* child : module->getChildren()) { area += addModuleItem(child->getMaster(), parent); } parent->appendRow({leafs, new QStandardItem, makeSizeItem(leaf_area)}); return leaf_area + area; } int64_t BrowserWidget::addInstanceItem(odb::dbInst* inst, QStandardItem* parent) { QStandardItem* item = new QStandardItem(inst->getConstName()); item->setEditable(false); item->setSelectable(true); item->setData(QVariant::fromValue(inst)); auto* box = inst->getBBox(); int64_t area = box->getDX() * box->getDY(); parent->appendRow({item, makeMasterItem(inst->getMaster()->getConstName()), makeSizeItem(area)}); return area; } int64_t BrowserWidget::addModuleItem(odb::dbModule* module, QStandardItem* parent) { QStandardItem* item = new QStandardItem(QString::fromStdString(module->getHierarchicalName())); item->setEditable(false); item->setSelectable(true); item->setData(QVariant::fromValue(module)); int64_t area = populateModule(module, item); parent->appendRow({item, makeMasterItem(module->getName()), makeSizeItem(area)}); return area; } QStandardItem* BrowserWidget::makeSizeItem(int64_t area) const { double scale_to_um = block_->getDbUnitsPerMicron() * block_->getDbUnitsPerMicron(); std::string units = "\u03BC"; // mu double disp_area = area / scale_to_um; if (disp_area > 10e6) { disp_area /= (1e3 * 1e3); units = "m"; } auto text = fmt::format("{:.3f}", disp_area) + " " + units + "m\u00B2"; // m2 QStandardItem* size = new QStandardItem(QString::fromStdString(text)); size->setEditable(false); size->setData(Qt::AlignRight, Qt::TextAlignmentRole); return size; } QStandardItem* BrowserWidget::makeMasterItem(const std::string& name) const { QStandardItem* master = new QStandardItem(QString::fromStdString(name)); master->setEditable(false); return master; } void BrowserWidget::inDbInstCreate(odb::dbInst*) { updateModel(); } void BrowserWidget::inDbInstCreate(odb::dbInst*, odb::dbRegion*) { updateModel(); } void BrowserWidget::inDbInstDestroy(odb::dbInst*) { updateModel(); } void BrowserWidget::inDbInstSwapMasterAfter(odb::dbInst*) { updateModel(); } } // namespace gui <commit_msg>gui: add top as root module in browser<commit_after>///////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2020, The Regents of the University of California // All rights reserved. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #include "browserWidget.h" #include <QHeaderView> #include "utl/Logger.h" Q_DECLARE_METATYPE(odb::dbInst*); Q_DECLARE_METATYPE(odb::dbModule*); namespace gui { /////// BrowserWidget::BrowserWidget(QWidget* parent) : QDockWidget("Hierarchy Browser", parent), block_(nullptr), view_(new QTreeView(this)), model_(new QStandardItemModel(this)) { setObjectName("hierarchy_viewer"); // for settings model_->setHorizontalHeaderLabels({"Instance", "Master", "Area"}); view_->setModel(model_); QHeaderView* header = view_->header(); header->setStretchLastSection(false); header->setSectionResizeMode(0, QHeaderView::Stretch); header->setSectionResizeMode(1, QHeaderView::ResizeToContents); header->setSectionResizeMode(2, QHeaderView::ResizeToContents); setWidget(view_); connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clicked(const QModelIndex&))); connect(view_->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(selectionChanged(const QItemSelection&, const QItemSelection&))); } void BrowserWidget::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { auto indexes = selected.indexes(); if (indexes.isEmpty()) { return; } emit clicked(indexes.first()); } void BrowserWidget::clicked(const QModelIndex& index) { QStandardItem* item = model_->itemFromIndex(index); QVariant data = item->data(); if (data.isValid()) { auto* gui = Gui::get(); auto* inst = data.value<odb::dbInst*>(); if (inst != nullptr) { emit select(gui->makeSelected(inst)); } else { auto* module = data.value<odb::dbModule*>(); if (module != nullptr) { emit select(gui->makeSelected(module)); } } } } void BrowserWidget::setBlock(odb::dbBlock* block) { block_ = block; addOwner(block_); updateModel(); } void BrowserWidget::showEvent(QShowEvent* event) { addOwner(block_); updateModel(); } void BrowserWidget::hideEvent(QHideEvent* event) { removeOwner(); clearModel(); } void BrowserWidget::updateModel() { clearModel(); if (block_ == nullptr) { return; } auto* root = model_->invisibleRootItem(); addModuleItem(block_->getTopModule(), root); QStandardItem* physical = new QStandardItem("Physical only"); physical->setEditable(false); physical->setSelectable(false); double area = 0; for (auto* inst : block_->getInsts()) { if (inst->getModule() != nullptr) { continue; } area += addInstanceItem(inst, physical); } root->appendRow({physical, new QStandardItem, makeSizeItem(area)}); } void BrowserWidget::clearModel() { model_->removeRows(0, model_->rowCount()); } int64_t BrowserWidget::populateModule(odb::dbModule* module, QStandardItem* parent) { int64_t leaf_area = 0; auto* leafs = new QStandardItem("Leaf instances"); leafs->setEditable(false); leafs->setSelectable(false); for (auto* inst : module->getInsts()) { leaf_area += addInstanceItem(inst, leafs); } int64_t area = 0; for (auto* child : module->getChildren()) { area += addModuleItem(child->getMaster(), parent); } parent->appendRow({leafs, new QStandardItem, makeSizeItem(leaf_area)}); return leaf_area + area; } int64_t BrowserWidget::addInstanceItem(odb::dbInst* inst, QStandardItem* parent) { QStandardItem* item = new QStandardItem(inst->getConstName()); item->setEditable(false); item->setSelectable(true); item->setData(QVariant::fromValue(inst)); auto* box = inst->getBBox(); int64_t area = box->getDX() * box->getDY(); parent->appendRow({item, makeMasterItem(inst->getMaster()->getConstName()), makeSizeItem(area)}); return area; } int64_t BrowserWidget::addModuleItem(odb::dbModule* module, QStandardItem* parent) { QStandardItem* item = new QStandardItem(QString::fromStdString(module->getHierarchicalName())); item->setEditable(false); item->setSelectable(true); item->setData(QVariant::fromValue(module)); int64_t area = populateModule(module, item); parent->appendRow({item, makeMasterItem(module->getName()), makeSizeItem(area)}); return area; } QStandardItem* BrowserWidget::makeSizeItem(int64_t area) const { double scale_to_um = block_->getDbUnitsPerMicron() * block_->getDbUnitsPerMicron(); std::string units = "\u03BC"; // mu double disp_area = area / scale_to_um; if (disp_area > 10e6) { disp_area /= (1e3 * 1e3); units = "m"; } auto text = fmt::format("{:.3f}", disp_area) + " " + units + "m\u00B2"; // m2 QStandardItem* size = new QStandardItem(QString::fromStdString(text)); size->setEditable(false); size->setData(Qt::AlignRight, Qt::TextAlignmentRole); return size; } QStandardItem* BrowserWidget::makeMasterItem(const std::string& name) const { QStandardItem* master = new QStandardItem(QString::fromStdString(name)); master->setEditable(false); return master; } void BrowserWidget::inDbInstCreate(odb::dbInst*) { updateModel(); } void BrowserWidget::inDbInstCreate(odb::dbInst*, odb::dbRegion*) { updateModel(); } void BrowserWidget::inDbInstDestroy(odb::dbInst*) { updateModel(); } void BrowserWidget::inDbInstSwapMasterAfter(odb::dbInst*) { updateModel(); } } // namespace gui <|endoftext|>
<commit_before>#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <cmath> #include <sstream> #include <string> #include <vector> #include "factorencoder.hh" int read_words(const char* fname, std::map<std::string, long> &words) { std::ifstream vocabfile(fname); if (!vocabfile) return -1; std::string line, word; long count; while (getline(vocabfile, line)) { std::stringstream ss(line); ss >> count; ss >> word; words[word] = count; } vocabfile.close(); return words.size(); } void resegment_words(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, double> &new_freqs, const int maxlen) { for(std::map<std::string, long>::const_iterator iter = words.begin(); iter != words.end(); ++iter) { std::vector<std::string> best_path; viterbi(vocab, maxlen, iter->first, best_path, false); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for word: " << iter->first << std::endl; exit(0); } // Update statistics for (int i=0; i<best_path.size(); i++) new_freqs[best_path[i]] += double(iter->second); } } void resegment_words_w_diff(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, double> &new_freqs, std::map<std::string, std::map<std::string, double> > &diffs, const int maxlen) { std::map<std::string, double> hypo_vocab = vocab; for (std::map<std::string, long>::const_iterator iter = words.begin(); iter != words.end(); ++iter) { std::vector<std::string> best_path; viterbi(vocab, maxlen, iter->first, best_path, false); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for word: " << iter->first << std::endl; exit(0); } // Update statistics std::map<std::string, double> best_path_types; for (int i=0; i<best_path.size(); i++) { new_freqs[best_path[i]] += double(iter->second); best_path_types[best_path[i]] = 0.0; } // Hypothesize what the segmentation would be if some subword didn't exist for (std::map<std::string, double>::iterator hypoiter = best_path_types.begin(); hypoiter != best_path_types.end(); ++hypoiter) { if (diffs.find(hypoiter->first) != diffs.end()) { double stored_value = hypo_vocab.at(hypoiter->first); hypo_vocab.erase(hypoiter->first); std::vector<std::string> hypo_path; viterbi(hypo_vocab, maxlen, hypoiter->first, hypo_path, false); for (int ib=0; ib<best_path.size(); ib++) diffs[hypoiter->first][best_path[ib]] -= double(iter->second); for (int ih=0; ih<hypo_path.size(); ih++) diffs[hypoiter->first][hypo_path[ih]] += double(iter->second); hypo_vocab[hypoiter->first] = stored_value; } } } } double get_sum(const std::map<std::string, double> &vocab) { double total = 0.0; for(std::map<std::string, double>::const_iterator iter = vocab.begin(); iter != vocab.end(); ++iter) { total += iter->second; } return total; } double get_cost(const std::map<std::string, double> &vocab, double densum) { double total = 0.0; double tmp = 0.0; densum = log2(densum); for(std::map<std::string, double>::const_iterator iter = vocab.begin(); iter != vocab.end(); ++iter) { tmp = iter->second * (log2(iter->second)-densum); if (!isnan(tmp)) total += tmp; } return total; } void freqs_to_logprobs(std::map<std::string, double> &vocab, double densum) { densum = log2(densum); for(std::map<std::string, double>::iterator iter = vocab.begin(); iter != vocab.end(); ++iter) vocab[iter->first] = (log2(iter->second)-densum); } void cutoff(std::map<std::string, double> &vocab, double limit) { for(std::map<std::string, double>::iterator iter = vocab.begin(); iter != vocab.end(); ++iter) if (vocab[iter->first] <= limit) vocab.erase(iter->first); } // Select n_candidates number of subwords in the vocabulary as removal candidates // running from the least common subword void init_removal_candidates(int &n_candidates, const int maxlen, const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, std::map<std::string, double> > &diffs) { std::map<std::string, double> new_morph_freqs; resegment_words(words, vocab, new_morph_freqs, maxlen); std::vector<std::pair<std::string, double> > sorted_vocab; sort_vocab(new_morph_freqs, sorted_vocab, false); n_candidates = std::min(n_candidates, (int)vocab.size()); for (int i=0; i<n_candidates; i++) { std::pair<std::string, double> &subword = sorted_vocab[i]; std::map<std::string, double> emptymap; diffs[subword.first] = emptymap; } } bool rank_desc_sort(std::pair<std::string, double> i,std::pair<std::string, double> j) { return (i.second > j.second); } // Perform each of the removals (independent of others in the list) to get // initial order for the removals void rank_removal_candidates(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, std::map<std::string, double> > &diffs, std::map<std::string, double> &new_morph_freqs, const int maxlen, std::vector<std::pair<std::string, double> > &removal_scores) { resegment_words_w_diff(words, vocab, new_morph_freqs, diffs, maxlen); double densum = get_sum(new_morph_freqs); double cost = get_cost(new_morph_freqs, densum); for (std::map<std::string, std::map<std::string, double> >::iterator iter = diffs.begin(); iter != diffs.end(); ++iter) { for (std::map<std::string, double>::iterator diffiter = iter->second.begin(); diffiter != iter->second.end(); ++diffiter) new_morph_freqs[diffiter->first] += diffiter->second; double hypo_densum = get_sum(new_morph_freqs); double hypo_cost = get_cost(new_morph_freqs, hypo_densum); std::pair<std::string, double> removal_score = std::make_pair(iter->first, hypo_cost-cost); removal_scores.push_back(removal_score); for (std::map<std::string, double>::iterator diffiter = iter->second.begin(); diffiter != iter->second.end(); ++diffiter) new_morph_freqs[diffiter->first] -= diffiter->second; } std::sort(removal_scores.begin(), removal_scores.end(), rank_desc_sort); } // Really performs the removal and gives out updated freqs void remove_subword(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, const int maxlen, const std::string &subword, std::map<std::string, double> &new_freqs) { std::map<std::string, double> hypo_vocab = vocab; hypo_vocab.erase(subword); for(std::map<std::string, long>::const_iterator iter = words.begin(); iter != words.end(); ++iter) { // Is this too slow? if (iter->first.find(subword) != std::string::npos) { std::vector<std::string> best_path; viterbi(vocab, maxlen, iter->first, best_path, false); std::vector<std::string> hypo_path; viterbi(hypo_vocab, maxlen, iter->first, hypo_path, false); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for word: " << iter->first << std::endl; exit(0); } if (hypo_path.size() == 0) { std::cerr << "warning, no hypo segmentation for word: " << iter->first << std::endl; exit(0); } // Update statistics for (int i=0; i<best_path.size(); i++) new_freqs[best_path[i]] -= double(iter->second); for (int i=0; i<hypo_path.size(); i++) new_freqs[hypo_path[i]] += double(iter->second); } } new_freqs.erase(subword); for(std::map<std::string, double>::iterator iter = new_freqs.begin(); iter != new_freqs.end(); ++iter) if (iter->second == 0.0) new_freqs.erase(iter->first); } int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "usage: " << argv[0] << " <vocabulary> <words>" << std::endl; exit(0); } int maxlen; std::map<std::string, double> vocab; std::map<std::string, double> new_morph_freqs; std::map<std::string, long> words; std::cerr << "Reading vocabulary " << argv[1] << std::endl; int retval = read_vocab(argv[1], vocab, maxlen); if (retval < 0) { std::cerr << "something went wrong reading vocabulary" << std::endl; exit(0); } std::cerr << "\t" << "size: " << vocab.size() << std::endl; std::cerr << "\t" << "maximum string length: " << maxlen << std::endl; std::cerr << "Reading word list" << std::endl; read_words(argv[2], words); std::cerr << "\t\t\t" << "vocabulary size: " << vocab.size() << std::endl; std::cerr << "Initial cutoffs" << std::endl; const int n_cutoff_iters = 1; int cutoffs[n_cutoff_iters] = { 50 }; for (int i=0; i<n_cutoff_iters; i++) { resegment_words(words, vocab, new_morph_freqs, maxlen); double densum = get_sum(new_morph_freqs); double cost = get_cost(new_morph_freqs, densum); std::cerr << "cost: " << cost << std::endl; vocab.swap(new_morph_freqs); new_morph_freqs.clear(); cutoff(vocab, cutoffs[i]); std::cerr << "\tcutoff: " << cutoffs[i] << "\t" << "vocabulary size: " << vocab.size() << std::endl; densum = get_sum(vocab); freqs_to_logprobs(vocab, densum); } int itern = 1; int n_candidates_per_iter = 5000; double threshold = 0.0; int min_removals_per_iter = 50; std::cerr << "Removing subwords one by one" << std::endl; while (true) { std::cerr << "iteration " << itern << std::endl; std::cerr << "collecting candidate subwords for removal" << std::endl; std::map<std::string, std::map<std::string, double> > diffs; init_removal_candidates(n_candidates_per_iter, maxlen, words, vocab, diffs); std::map<std::string, double> freqs; std::vector<std::pair<std::string, double> > removal_scores; rank_removal_candidates(words, vocab, diffs, freqs, maxlen, removal_scores); // Perform removals one by one if likelihood change below threshold double curr_densum = get_sum(freqs); double curr_cost = get_cost(freqs, curr_densum); std::cerr << "starting cost before removing subwords one by one: " << curr_cost << std::endl; int n_removals = 0; for (int i=0; i<removal_scores.size(); i++) { std::cout << "try removing subword: " << removal_scores[i].first << "\t" << "expected ll diff: " << removal_scores[i].second << std::endl; if (removal_scores[i].second < threshold) break; std::map<std::string, double> hypo_freqs = freqs; remove_subword(words, vocab, maxlen, removal_scores[i].first, hypo_freqs); double hypo_densum = get_sum(hypo_freqs); double hypo_cost = get_cost(hypo_freqs, hypo_densum); if (hypo_cost-curr_cost > 0) { std::cout << "removed subword: " << removal_scores[i].first << "\t" << "change in likelihood: " << hypo_cost-curr_cost << std::endl; curr_densum = hypo_densum; curr_cost = hypo_cost; freqs = hypo_freqs; vocab = freqs; freqs_to_logprobs(vocab, hypo_densum); n_removals++; } } std::cerr << "subwords removed in this iteration: " << n_removals << std::endl; std::cerr << "current vocabulary size: " << vocab.size() << std::endl; std::cerr << "likelihood after the removals: " << curr_cost << std::endl; std::ostringstream vocabfname; vocabfname << "vocab.iter" << itern; write_vocab(vocabfname.str().c_str(), vocab); std::ostringstream freqsfname; freqsfname << "freqs.iter" << itern; write_vocab(freqsfname.str().c_str(), freqs); itern++; if (n_removals < min_removals_per_iter) { std::cerr << "stopping. " << std::endl; break; } } exit(1); } <commit_msg>last bugfix?<commit_after>#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <cmath> #include <sstream> #include <string> #include <vector> #include "factorencoder.hh" int read_words(const char* fname, std::map<std::string, long> &words) { std::ifstream vocabfile(fname); if (!vocabfile) return -1; std::string line, word; long count; while (getline(vocabfile, line)) { std::stringstream ss(line); ss >> count; ss >> word; words[word] = count; } vocabfile.close(); return words.size(); } void resegment_words(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, double> &new_freqs, const int maxlen) { for(std::map<std::string, long>::const_iterator iter = words.begin(); iter != words.end(); ++iter) { std::vector<std::string> best_path; viterbi(vocab, maxlen, iter->first, best_path, false); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for word: " << iter->first << std::endl; exit(0); } // Update statistics for (int i=0; i<best_path.size(); i++) new_freqs[best_path[i]] += double(iter->second); } } void resegment_words_w_diff(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, double> &new_freqs, std::map<std::string, std::map<std::string, double> > &diffs, const int maxlen) { std::map<std::string, double> hypo_vocab = vocab; new_freqs.clear(); for (std::map<std::string, long>::const_iterator iter = words.begin(); iter != words.end(); ++iter) { std::vector<std::string> best_path; viterbi(vocab, maxlen, iter->first, best_path, false); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for word: " << iter->first << std::endl; exit(0); } // Update statistics std::map<std::string, double> best_path_types; for (int i=0; i<best_path.size(); i++) { new_freqs[best_path[i]] += double(iter->second); best_path_types[best_path[i]] = 0.0; } // Hypothesize what the segmentation would be if some subword didn't exist for (std::map<std::string, double>::iterator hypoiter = best_path_types.begin(); hypoiter != best_path_types.end(); ++hypoiter) { if (diffs.find(hypoiter->first) != diffs.end()) { std::cout << "hypo for word: " << iter->first << std::endl; double stored_value = hypo_vocab.at(hypoiter->first); hypo_vocab.erase(hypoiter->first); std::vector<std::string> hypo_path; viterbi(hypo_vocab, maxlen, iter->first, hypo_path, false); for (int ib=0; ib<best_path.size(); ib++) diffs[hypoiter->first][best_path[ib]] -= double(iter->second); for (int ih=0; ih<hypo_path.size(); ih++) diffs[hypoiter->first][hypo_path[ih]] += double(iter->second); diffs[hypoiter->first].erase(hypoiter->first); hypo_vocab[hypoiter->first] = stored_value; } } } } double get_sum(const std::map<std::string, double> &vocab) { double total = 0.0; for(std::map<std::string, double>::const_iterator iter = vocab.begin(); iter != vocab.end(); ++iter) { total += iter->second; } return total; } double get_cost(const std::map<std::string, double> &vocab, double densum) { double total = 0.0; double tmp = 0.0; densum = log2(densum); for(std::map<std::string, double>::const_iterator iter = vocab.begin(); iter != vocab.end(); ++iter) { tmp = iter->second * (log2(iter->second)-densum); if (!isnan(tmp)) total += tmp; } return total; } void freqs_to_logprobs(std::map<std::string, double> &vocab, double densum) { densum = log2(densum); for(std::map<std::string, double>::iterator iter = vocab.begin(); iter != vocab.end(); ++iter) vocab[iter->first] = (log2(iter->second)-densum); } void cutoff(std::map<std::string, double> &vocab, double limit) { for(std::map<std::string, double>::iterator iter = vocab.begin(); iter != vocab.end(); ++iter) if (vocab[iter->first] <= limit) vocab.erase(iter->first); } // Select n_candidates number of subwords in the vocabulary as removal candidates // running from the least common subword void init_removal_candidates(int &n_candidates, const int maxlen, const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, std::map<std::string, double> > &diffs) { std::map<std::string, double> new_morph_freqs; resegment_words(words, vocab, new_morph_freqs, maxlen); std::vector<std::pair<std::string, double> > sorted_vocab; sort_vocab(new_morph_freqs, sorted_vocab, false); n_candidates = std::min(n_candidates, (int)vocab.size()); for (int i=0; i<n_candidates; i++) { std::pair<std::string, double> &subword = sorted_vocab[i]; std::map<std::string, double> emptymap; diffs[subword.first] = emptymap; } } bool rank_desc_sort(std::pair<std::string, double> i,std::pair<std::string, double> j) { return (i.second > j.second); } // Perform each of the removals (independent of others in the list) to get // initial order for the removals void rank_removal_candidates(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, std::map<std::string, std::map<std::string, double> > &diffs, std::map<std::string, double> &new_morph_freqs, const int maxlen, std::vector<std::pair<std::string, double> > &removal_scores) { resegment_words_w_diff(words, vocab, new_morph_freqs, diffs, maxlen); double densum = get_sum(new_morph_freqs); double cost = get_cost(new_morph_freqs, densum); for (std::map<std::string, std::map<std::string, double> >::iterator iter = diffs.begin(); iter != diffs.end(); ++iter) { double stored_value = new_morph_freqs.at(iter->first); for (std::map<std::string, double>::iterator diffiter = iter->second.begin(); diffiter != iter->second.end(); ++diffiter) new_morph_freqs[diffiter->first] += diffiter->second; new_morph_freqs.erase(iter->first); double hypo_densum = get_sum(new_morph_freqs); double hypo_cost = get_cost(new_morph_freqs, hypo_densum); std::pair<std::string, double> removal_score = std::make_pair(iter->first, hypo_cost-cost); removal_scores.push_back(removal_score); for (std::map<std::string, double>::iterator diffiter = iter->second.begin(); diffiter != iter->second.end(); ++diffiter) new_morph_freqs[diffiter->first] -= diffiter->second; new_morph_freqs[iter->first] = stored_value; } std::sort(removal_scores.begin(), removal_scores.end(), rank_desc_sort); } // Really performs the removal and gives out updated freqs void remove_subword(const std::map<std::string, long> &words, const std::map<std::string, double> &vocab, const int maxlen, const std::string &subword, std::map<std::string, double> &new_freqs) { std::map<std::string, double> hypo_vocab = vocab; hypo_vocab.erase(subword); for(std::map<std::string, long>::const_iterator iter = words.begin(); iter != words.end(); ++iter) { // FIXME: Is this too slow? if (iter->first.find(subword) != std::string::npos) { std::vector<std::string> best_path; viterbi(vocab, maxlen, iter->first, best_path, false); std::vector<std::string> hypo_path; viterbi(hypo_vocab, maxlen, iter->first, hypo_path, false); if (best_path.size() == 0) { std::cerr << "warning, no segmentation for word: " << iter->first << std::endl; exit(0); } if (hypo_path.size() == 0) { std::cerr << "warning, no hypo segmentation for word: " << iter->first << std::endl; exit(0); } // Update statistics for (int i=0; i<best_path.size(); i++) new_freqs[best_path[i]] -= double(iter->second); for (int i=0; i<hypo_path.size(); i++) new_freqs[hypo_path[i]] += double(iter->second); } } new_freqs.erase(subword); for(std::map<std::string, double>::iterator iter = new_freqs.begin(); iter != new_freqs.end(); ++iter) if (iter->second == 0.0) new_freqs.erase(iter->first); } int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "usage: " << argv[0] << " <vocabulary> <words>" << std::endl; exit(0); } int maxlen; std::map<std::string, double> vocab; std::map<std::string, double> new_morph_freqs; std::map<std::string, long> words; std::cerr << "Reading vocabulary " << argv[1] << std::endl; int retval = read_vocab(argv[1], vocab, maxlen); if (retval < 0) { std::cerr << "something went wrong reading vocabulary" << std::endl; exit(0); } std::cerr << "\t" << "size: " << vocab.size() << std::endl; std::cerr << "\t" << "maximum string length: " << maxlen << std::endl; std::cerr << "Reading word list" << std::endl; read_words(argv[2], words); std::cerr << "\t\t\t" << "vocabulary size: " << vocab.size() << std::endl; std::cerr << "Initial cutoffs" << std::endl; const int n_cutoff_iters = 1; int cutoffs[n_cutoff_iters] = { 50 }; for (int i=0; i<n_cutoff_iters; i++) { resegment_words(words, vocab, new_morph_freqs, maxlen); double densum = get_sum(new_morph_freqs); double cost = get_cost(new_morph_freqs, densum); std::cerr << "cost: " << cost << std::endl; vocab.swap(new_morph_freqs); new_morph_freqs.clear(); cutoff(vocab, cutoffs[i]); std::cerr << "\tcutoff: " << cutoffs[i] << "\t" << "vocabulary size: " << vocab.size() << std::endl; densum = get_sum(vocab); freqs_to_logprobs(vocab, densum); } int itern = 1; int n_candidates_per_iter = 2; double threshold = -100000.0; int min_removals_per_iter = 50; std::cerr << "Removing subwords one by one" << std::endl; while (true) { std::cerr << "iteration " << itern << std::endl; std::cerr << "collecting candidate subwords for removal" << std::endl; std::map<std::string, std::map<std::string, double> > diffs; init_removal_candidates(n_candidates_per_iter, maxlen, words, vocab, diffs); std::cerr << "ranking candidate subwords" << std::endl; std::map<std::string, double> freqs; std::vector<std::pair<std::string, double> > removal_scores; rank_removal_candidates(words, vocab, diffs, freqs, maxlen, removal_scores); // Perform removals one by one if likelihood change below threshold double curr_densum = get_sum(freqs); double curr_cost = get_cost(freqs, curr_densum); std::cerr << "starting cost before removing subwords one by one: " << curr_cost << std::endl; int n_removals = 0; for (int i=0; i<removal_scores.size(); i++) { std::cout << "try removing subword: " << removal_scores[i].first << "\t" << "expected ll diff: " << removal_scores[i].second << std::endl; if (removal_scores[i].second < threshold) break; std::map<std::string, double> hypo_freqs = freqs; remove_subword(words, vocab, maxlen, removal_scores[i].first, hypo_freqs); double hypo_densum = get_sum(hypo_freqs); double hypo_cost = get_cost(hypo_freqs, hypo_densum); if (hypo_cost-curr_cost > threshold) { std::cout << "removed subword: " << removal_scores[i].first << "\t" << "change in likelihood: " << hypo_cost-curr_cost << std::endl; curr_densum = hypo_densum; curr_cost = hypo_cost; freqs = hypo_freqs; vocab = freqs; freqs_to_logprobs(vocab, hypo_densum); n_removals++; } } std::cerr << "subwords removed in this iteration: " << n_removals << std::endl; std::cerr << "current vocabulary size: " << vocab.size() << std::endl; std::cerr << "likelihood after the removals: " << curr_cost << std::endl; std::ostringstream vocabfname; vocabfname << "vocab.iter" << itern; write_vocab(vocabfname.str().c_str(), vocab); std::ostringstream freqsfname; freqsfname << "freqs.iter" << itern; write_vocab(freqsfname.str().c_str(), freqs); itern++; if (n_removals < min_removals_per_iter) { std::cerr << "stopping. " << std::endl; break; } } exit(1); } <|endoftext|>
<commit_before>#include "test-helpers.h" #include <sstream> #include "text-buffer.h" #include "text-slice.h" using std::move; using std::string; using std::stringstream; TEST_CASE("TextBuffer::build - can build a TextBuffer from a UTF8 stream") { string input = "abγdefg\nhijklmnop"; stringstream stream(input, std::ios_base::in); vector<size_t> progress_reports; TextBuffer buffer = TextBuffer::build(stream, input.size(), "UTF8", 3, [&](size_t percent_done) { progress_reports.push_back(percent_done); }); auto text = buffer.text(); REQUIRE(buffer.text() == Text {u"abγdefg\nhijklmnop"}); REQUIRE(progress_reports == vector<size_t>({3, 5, 8, 11, 14, 17, 18})); } TEST_CASE("TextBuffer::set_text_in_range - basic") { TextBuffer buffer {u"abc\ndef\nghi"}; buffer.set_text_in_range(Range {{0, 2}, {2, 1}}, Text {u"jkl\nmno"}); REQUIRE(buffer.text() == Text {u"abjkl\nmnohi"}); REQUIRE(buffer.text_in_range(Range {{0, 1}, {1, 4}}) == Text {u"bjkl\nmnoh"}); } TEST_CASE("TextBuffer::line_length_for_row - basic") { TextBuffer buffer {u"a\n\nb\r\rc\r\n\r\n"}; REQUIRE(buffer.line_length_for_row(0) == 1); REQUIRE(buffer.line_length_for_row(1) == 0); } TEST_CASE("TextBuffer::set_text_in_range, random edits") { auto t = time(nullptr); for (uint i = 0; i < 100; i++) { auto seed = t + i; srand(seed); printf("Seed: %ld\n", seed); TextBuffer buffer {get_random_string()}; for (uint j = 0; j < 10; j++) { Text original_text = buffer.text(); Range deleted_range = get_random_range(buffer); Text inserted_text = get_random_text(); buffer.set_text_in_range(deleted_range, TextSlice {inserted_text}); original_text.splice(deleted_range.start, deleted_range.extent(), TextSlice {inserted_text}); REQUIRE(buffer.extent() == original_text.extent()); REQUIRE(buffer.text() == original_text); } } } <commit_msg>Make test description work w/ Catch's focus system<commit_after>#include "test-helpers.h" #include <sstream> #include "text-buffer.h" #include "text-slice.h" using std::move; using std::string; using std::stringstream; TEST_CASE("TextBuffer::build - can build a TextBuffer from a UTF8 stream") { string input = "abγdefg\nhijklmnop"; stringstream stream(input, std::ios_base::in); vector<size_t> progress_reports; TextBuffer buffer = TextBuffer::build(stream, input.size(), "UTF8", 3, [&](size_t percent_done) { progress_reports.push_back(percent_done); }); auto text = buffer.text(); REQUIRE(buffer.text() == Text {u"abγdefg\nhijklmnop"}); REQUIRE(progress_reports == vector<size_t>({3, 5, 8, 11, 14, 17, 18})); } TEST_CASE("TextBuffer::set_text_in_range - basic") { TextBuffer buffer {u"abc\ndef\nghi"}; buffer.set_text_in_range(Range {{0, 2}, {2, 1}}, Text {u"jkl\nmno"}); REQUIRE(buffer.text() == Text {u"abjkl\nmnohi"}); REQUIRE(buffer.text_in_range(Range {{0, 1}, {1, 4}}) == Text {u"bjkl\nmnoh"}); } TEST_CASE("TextBuffer::line_length_for_row - basic") { TextBuffer buffer {u"a\n\nb\r\rc\r\n\r\n"}; REQUIRE(buffer.line_length_for_row(0) == 1); REQUIRE(buffer.line_length_for_row(1) == 0); } TEST_CASE("TextBuffer::set_text_in_range - random edits") { auto t = time(nullptr); for (uint i = 0; i < 100; i++) { auto seed = t + i; srand(seed); printf("Seed: %ld\n", seed); TextBuffer buffer {get_random_string()}; for (uint j = 0; j < 10; j++) { Text original_text = buffer.text(); Range deleted_range = get_random_range(buffer); Text inserted_text = get_random_text(); buffer.set_text_in_range(deleted_range, TextSlice {inserted_text}); original_text.splice(deleted_range.start, deleted_range.extent(), TextSlice {inserted_text}); REQUIRE(buffer.extent() == original_text.extent()); REQUIRE(buffer.text() == original_text); } } } <|endoftext|>
<commit_before>#include <iostream> #include "ace/Select_Reactor.h" #include "ace/Reactor.h" #include "ace/OS_NS_unistd.h" #include "ace/Signal.h" #include "ace/Time_Value.h" #include "ace/OS_NS_time.h" #include "ace/Date_Time.h" #include "log.h" #include "version.h" #include "DataStoreReceiver.h" #include "DataStoreConfigManager.h" #include "UserSwitch.inl" #include "LogConfig.inl" #ifdef WIN32 #include "WinSvc.inl" #endif using namespace std; using namespace ammo::gateway; //Handle SIGINT so the program can exit cleanly (otherwise, we just terminate //in the middle of the reactor event loop, which isn't always a good thing). class SigintHandler : public ACE_Event_Handler { public: int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0) { if (signum == SIGINT || signum == SIGTERM) { ACE_Reactor::instance ()->end_reactor_event_loop (); } return 0; } }; class App { public: static App* instance(); static void destroy(); private: static App* _instance; private: App(); ~App(); public: void init(int argc, char* argv[]); void run(); void stop(); private: //Explicitly specify the ACE select reactor; on Windows, ACE defaults //to the WFMO reactor, which has radically different semantics and //violates assumptions we made in our code ACE_Select_Reactor selectReactor; ACE_Reactor newReactor; auto_ptr<ACE_Reactor> delete_instance; ACE_Sig_Action no_sigpipe; ACE_Sig_Action original_action; SigintHandler* handleExit; DataStoreReceiver* receiver; GatewayConnector* gatewayConnector; }; App* App::_instance = NULL; App* App::instance() { if (!_instance) { _instance = new App(); } return _instance; } void App::destroy() { delete _instance; _instance = NULL; } App::App() : newReactor(&selectReactor), delete_instance(ACE_Reactor::instance(&newReactor)), no_sigpipe((ACE_SignalHandler) SIG_IGN), // Set signal handler for SIGPIPE (so we don't crash if a device disconnects during write) handleExit(NULL), receiver(NULL), gatewayConnector(NULL) { } App::~App() { //if (this->receiver) { // delete this->receiver; //} //if (this->gatewayConnector) { // delete this->gatewayConnector; //} } void App::init(int argc, char* argv[]) { dropPrivileges(); setupLogging("DataStoreGatewayPlugin"); LOG_FATAL("========="); LOG_FATAL("AMMO Location Store Gateway Plugin (" << VERSION << " built on " << __DATE__ << " at " << __TIME__ << ")"); // Set signal handler for SIGPIPE (so we don't crash if a device disconnects // during write) no_sigpipe.register_action(SIGPIPE, &original_action); handleExit = new SigintHandler(); ACE_Reactor::instance()->register_handler(SIGINT, handleExit); ACE_Reactor::instance()->register_handler(SIGTERM, handleExit); LOG_DEBUG ("Creating location store receiver..."); receiver = new DataStoreReceiver (); gatewayConnector = new GatewayConnector (receiver); DataStoreConfigManager *config = DataStoreConfigManager::getInstance (receiver, gatewayConnector); // Nothing further is done with 'config' since everything happens // in the constructor. This macro avoids the 'unused' warning. ACE_UNUSED_ARG (config); // Make sure that the receiver and connector have been created and // passed to the config manager before calling this method. if (!receiver->init ()) { // Error msg already output, just exit w/o starting reactor. return; } } void App::run() { ACE_Reactor *reactor = ACE_Reactor::instance (); LOG_DEBUG ("Starting event loop..."); reactor->run_reactor_event_loop (); } void App::stop() { ACE_Reactor::instance()->end_reactor_event_loop(); } #ifdef WIN32 void SvcInit(DWORD argc, LPTSTR* argv) { App::instance()->init(argc, argv); } void SvcRun() { App::instance()->run(); } void SvcStop() { App::instance()->stop(); } int main(int argc, char* argv[]) { const std::string svcName = "DataStoreGatewayPlugin"; // Service installation command line option if (argc == 2) { if (lstrcmpi(argv[1], TEXT("install")) == 0) { try { WinSvc::install(svcName); return 0; } catch (WinSvcException e) { cerr << e.what(); return 1; } } } // Normal service operation WinSvc::callbacks_t callbacks(SvcInit, SvcRun, SvcStop); App::instance(); try { WinSvc::instance(svcName, callbacks); WinSvc::instance()->run(); } catch (WinSvcException e) { LOG_FATAL(e.what()); WinSvc::instance()->SvcReportEvent((char*) (e.what())); } catch (...) { WinSvc::instance()->SvcReportEvent("unknown exception"); } App::destroy(); return 0; } #else int main(int argc, char** argv) { App::instance()->init(argc, argv); App::instance()->run(); App::instance()->destroy(); return 0; } #endif <commit_msg>removed debug catch<commit_after>#include <iostream> #include "ace/Select_Reactor.h" #include "ace/Reactor.h" #include "ace/OS_NS_unistd.h" #include "ace/Signal.h" #include "ace/Time_Value.h" #include "ace/OS_NS_time.h" #include "ace/Date_Time.h" #include "log.h" #include "version.h" #include "DataStoreReceiver.h" #include "DataStoreConfigManager.h" #include "UserSwitch.inl" #include "LogConfig.inl" #ifdef WIN32 #include "WinSvc.inl" #endif using namespace std; using namespace ammo::gateway; //Handle SIGINT so the program can exit cleanly (otherwise, we just terminate //in the middle of the reactor event loop, which isn't always a good thing). class SigintHandler : public ACE_Event_Handler { public: int handle_signal (int signum, siginfo_t * = 0, ucontext_t * = 0) { if (signum == SIGINT || signum == SIGTERM) { ACE_Reactor::instance ()->end_reactor_event_loop (); } return 0; } }; class App { public: static App* instance(); static void destroy(); private: static App* _instance; private: App(); ~App(); public: void init(int argc, char* argv[]); void run(); void stop(); private: //Explicitly specify the ACE select reactor; on Windows, ACE defaults //to the WFMO reactor, which has radically different semantics and //violates assumptions we made in our code ACE_Select_Reactor selectReactor; ACE_Reactor newReactor; auto_ptr<ACE_Reactor> delete_instance; ACE_Sig_Action no_sigpipe; ACE_Sig_Action original_action; SigintHandler* handleExit; DataStoreReceiver* receiver; GatewayConnector* gatewayConnector; }; App* App::_instance = NULL; App* App::instance() { if (!_instance) { _instance = new App(); } return _instance; } void App::destroy() { delete _instance; _instance = NULL; } App::App() : newReactor(&selectReactor), delete_instance(ACE_Reactor::instance(&newReactor)), no_sigpipe((ACE_SignalHandler) SIG_IGN), // Set signal handler for SIGPIPE (so we don't crash if a device disconnects during write) handleExit(NULL), receiver(NULL), gatewayConnector(NULL) { } App::~App() { //if (this->receiver) { // delete this->receiver; //} //if (this->gatewayConnector) { // delete this->gatewayConnector; //} } void App::init(int argc, char* argv[]) { dropPrivileges(); setupLogging("DataStoreGatewayPlugin"); LOG_FATAL("========="); LOG_FATAL("AMMO Location Store Gateway Plugin (" << VERSION << " built on " << __DATE__ << " at " << __TIME__ << ")"); // Set signal handler for SIGPIPE (so we don't crash if a device disconnects // during write) no_sigpipe.register_action(SIGPIPE, &original_action); handleExit = new SigintHandler(); ACE_Reactor::instance()->register_handler(SIGINT, handleExit); ACE_Reactor::instance()->register_handler(SIGTERM, handleExit); LOG_DEBUG ("Creating location store receiver..."); receiver = new DataStoreReceiver (); gatewayConnector = new GatewayConnector (receiver); DataStoreConfigManager *config = DataStoreConfigManager::getInstance (receiver, gatewayConnector); // Nothing further is done with 'config' since everything happens // in the constructor. This macro avoids the 'unused' warning. ACE_UNUSED_ARG (config); // Make sure that the receiver and connector have been created and // passed to the config manager before calling this method. if (!receiver->init ()) { // Error msg already output, just exit w/o starting reactor. return; } } void App::run() { ACE_Reactor *reactor = ACE_Reactor::instance (); LOG_DEBUG ("Starting event loop..."); reactor->run_reactor_event_loop (); } void App::stop() { ACE_Reactor::instance()->end_reactor_event_loop(); } #ifdef WIN32 void SvcInit(DWORD argc, LPTSTR* argv) { App::instance()->init(argc, argv); } void SvcRun() { App::instance()->run(); } void SvcStop() { App::instance()->stop(); } int main(int argc, char* argv[]) { const std::string svcName = "DataStoreGatewayPlugin"; // Service installation command line option if (argc == 2) { if (lstrcmpi(argv[1], TEXT("install")) == 0) { try { WinSvc::install(svcName); return 0; } catch (WinSvcException e) { cerr << e.what(); return 1; } } } // Normal service operation WinSvc::callbacks_t callbacks(SvcInit, SvcRun, SvcStop); App::instance(); try { WinSvc::instance(svcName, callbacks); WinSvc::instance()->run(); } catch (WinSvcException e) { LOG_FATAL(e.what()); } App::destroy(); return 0; } #else int main(int argc, char** argv) { App::instance()->init(argc, argv); App::instance()->run(); App::instance()->destroy(); return 0; } #endif <|endoftext|>
<commit_before>/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere (disa@jhu.edu) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef PROFILER #include <gperftools/profiler.h> #endif #include <limits> #include <vector> #include <map> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" #include "FGlib.h" #include "FG_vector.h" using namespace fg; // We will ignore the race conditions first // NOTE: This script is only meant for undirected graphs!!! namespace { typedef safs::page_byte_array::seq_const_iterator<edge_count> data_seq_iterator; uint64_t g_edge_weight = 0; bool g_changed = false; std::map<vertex_id_t, float> g_volume_map; // Size is Order # Vertices // INIT lets us accumulate enum stage_t { INIT, LEVEL1, RUN, }; stage_t louvain_stage = INIT; // Init the stage edge_count tot_edge_weight = 0; // E class louvain_vertex: public compute_vertex { vertex_id_t cluster; // current cluster float modularity; uint32_t self_edge_weight; public: louvain_vertex(vertex_id_t id): compute_vertex(id) { cluster = id; modularity = std::numeric_limits<float>::min(); self_edge_weight = 0; } void run(vertex_program &prog); void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &, const vertex_message &msg1) {} void compute_modularity(edge_seq_iterator& id_it, data_seq_iterator& weight_it, vertex_id_t& max_cluster, float& max_mod, vertex_id_t my_id); void compute_vol_weight(data_seq_iterator& weight_it, edge_seq_iterator& id_it, vertex_program &prog); }; /* We need this to get the total edge_weight of the graph */ class louvain_vertex_program: public vertex_program_impl<louvain_vertex> { // Thread local edge_count th_local_edge_count; std::map<vertex_id_t, float> th_local_volume_map; public: louvain_vertex_program() { th_local_edge_count = 0; } typedef std::shared_ptr<louvain_vertex_program> ptr; static ptr cast2(vertex_program::ptr prog) { return std::static_pointer_cast<louvain_vertex_program, vertex_program>(prog); } void pp_ec(edge_count weight) { this->th_local_edge_count += weight; } uint32_t get_local_ec() { return th_local_edge_count.get_count(); } void insert_volume(vertex_id_t vid, float vol) { th_local_volume_map[vid] = vol; } std::map<vertex_id_t, float>& get_vol_map() { return th_local_volume_map; } }; /* We need this to do the INIT phase and pass vertex_program_impl to the start method */ class louvain_vertex_program_creater: public vertex_program_creater { public: vertex_program::ptr create() const { return vertex_program::ptr(new louvain_vertex_program()); } }; void louvain_vertex::run(vertex_program &prog) { // Need to recompute the modularity vertex_id_t id = prog.get_vertex_id(*this); request_vertices(&id, 1); } // FIXME: This will only work for the first level void louvain_vertex::compute_modularity(edge_seq_iterator& id_it, data_seq_iterator& weight_it, vertex_id_t& max_cluster, float& max_mod, vertex_id_t my_id) { float delta_mod; // Iterate through all vertices in the g_volume_map & if one is my // neighbor then I need to modify it's volume to not include me. std::map<vertex_id_t, float>::iterator graph_it = g_volume_map.begin(); // Iterator for all graph vertices vertex_id_t nid = INVALID_VERTEX_ID; edge_count e; bool used_neigh = true; // Have I just used one of my neighbors? while (true) { if (graph_it == g_volume_map.end()) { break; } else { if (id_it.has_next() && used_neigh) { nid = id_it.next(); e = weight_it.next(); used_neigh = false; // reset this } // We have an edge between the two vertices if (graph_it->first == nid) { delta_mod = ((e.get_count() - 0) / g_edge_weight) + (((g_volume_map[my_id] - this->self_edge_weight) - (g_volume_map[graph_it->first] - e.get_count())) * g_volume_map[my_id]) / (float)(2*(g_edge_weight^2)); used_neigh = true; } else { /* No edge between the two vertices */ delta_mod = ((((g_volume_map[my_id] - this->self_edge_weight) - g_volume_map[graph_it->first])) * g_volume_map[my_id]) / (float)(2*(g_edge_weight^2)); } BOOST_LOG_TRIVIAL(info) << "v" << my_id << " delta_mod for v" << graph_it->first << " = " << delta_mod; if (delta_mod > max_mod) { max_mod = delta_mod; max_cluster = graph_it->first; } } ++graph_it; } } // If anything changes cluster we cannot converge void toggle_changed() { if (!g_changed) g_changed = true; } void louvain_vertex::compute_vol_weight(data_seq_iterator& weight_it, edge_seq_iterator& id_it, vertex_program &prog) { edge_count local_edge_weight = 0; while (weight_it.has_next()) { edge_count e = weight_it.next(); vertex_id_t nid = id_it.next(); local_edge_weight += e.get_count(); if (nid == prog.get_vertex_id(*this)) { this->self_edge_weight += e.get_count(); } } ((louvain_vertex_program&)prog). pp_ec(local_edge_weight); ((louvain_vertex_program&)prog).insert_volume(prog.get_vertex_id(*this), local_edge_weight.get_count() + (2*this->self_edge_weight)); } // NOTE: If I know your ID I know what cluster you're in void louvain_vertex::run(vertex_program &prog, const page_vertex &vertex) { switch (louvain_stage) { case INIT: /* INIT just accums the global edge_count. I chose OUT_EDGE at random */ { data_seq_iterator weight_it = ((const page_directed_vertex&)vertex).get_data_seq_it<edge_count>(OUT_EDGE); edge_seq_iterator id_it = vertex.get_neigh_seq_it(OUT_EDGE); compute_vol_weight(weight_it, id_it, prog); } break; case LEVEL1: { // Compute the new cluster based on modularity float max_mod = this->modularity; vertex_id_t max_cluster = this->cluster; // Ignore's all not connected to this vertex edge_seq_iterator id_it = vertex.get_neigh_seq_it(OUT_EDGE); data_seq_iterator weight_it = ((const page_directed_vertex&)vertex).get_data_seq_it<edge_count>(OUT_EDGE); compute_modularity(id_it, weight_it, max_cluster, max_mod, prog.get_vertex_id(*this)); if (this->cluster != max_cluster) { BOOST_LOG_TRIVIAL(info) << "Vertex " << prog.get_vertex_id(*this) << " with mod = " << this->modularity << " < " << max_mod << " ,moved from cluster " << this->cluster << " ==> " << max_cluster << "\n"; toggle_changed(); } else { BOOST_LOG_TRIVIAL(info) << "Vertex " << prog.get_vertex_id(*this) << " with mod = " << this->modularity << " ,stayed in cluster " << this->cluster << "\n"; } this->cluster = max_cluster; this->modularity = max_mod; } break; case RUN: BOOST_LOG_TRIVIAL(fatal) << "Run unimplemented!"; break; default: assert(0); } } } namespace fg { void compute_louvain(FG_graph::ptr fg, const uint32_t levels) { graph_index::ptr index = NUMA_graph_index<louvain_vertex>::create( fg->get_graph_header()); graph_engine::ptr graph = fg->create_engine(index); BOOST_LOG_TRIVIAL(info) << "Starting Louvain with " << levels << " levels"; BOOST_LOG_TRIVIAL(info) << "prof_file: " << graph_conf.get_prof_file().c_str(); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); #endif struct timeval start, end; gettimeofday(&start, NULL); /*~~~~~~~~~~~~~~~~~~~~~~~~~~ Compute Vol & Weight ~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ graph->start_all(vertex_initializer::ptr(), vertex_program_creater::ptr(new louvain_vertex_program_creater())); graph->wait4complete(); std::vector<vertex_program::ptr> ec_progs; graph->get_vertex_programs(ec_progs); BOOST_FOREACH(vertex_program::ptr vprog, ec_progs) { louvain_vertex_program::ptr lvp = louvain_vertex_program::cast2(vprog); g_edge_weight += lvp->get_local_ec(); g_volume_map.insert(lvp->get_vol_map().begin(), lvp->get_vol_map().end()); } #if 1 BOOST_LOG_TRIVIAL(info) << "The graph's total edge weight is " << g_edge_weight << "\n"; for (std::map<vertex_id_t, float>::iterator it = g_volume_map.begin(); it != g_volume_map.end(); it++) { BOOST_LOG_TRIVIAL(info) << "Vertex: " << it->first << ", Volume: " << it->second; } BOOST_LOG_TRIVIAL(info) << "\x1B[31m====================================================\x1B[0m\n"; #endif /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Compute modularity ~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #if 1 louvain_stage = LEVEL1; do { g_changed = false; graph->start_all(); graph->wait4complete(); } while (g_changed); louvain_stage = RUN; BOOST_LOG_TRIVIAL(info) << "\n Reached running stage\n"; #endif gettimeofday(&end, NULL); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif BOOST_LOG_TRIVIAL(info) << boost::format("It takes %1% seconds") % time_diff(start, end); return; } } <commit_msg>[Graph]: Added a map merger for per thread hash maps<commit_after>/** * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere (disa@jhu.edu) * * This file is part of FlashGraph. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef PROFILER #include <gperftools/profiler.h> #endif #include <limits> #include <vector> #include <map> #include <algorithm> #include "thread.h" #include "io_interface.h" #include "container.h" #include "concurrency.h" #include "vertex_index.h" #include "graph_engine.h" #include "graph_config.h" #include "FGlib.h" #include "FG_vector.h" using namespace fg; // NOTE: This script is only meant for undirected graphs!!! namespace { typedef safs::page_byte_array::seq_const_iterator<edge_count> data_seq_iterator; uint64_t g_edge_weight = 0; bool g_changed = false; // INIT lets us accumulate enum stage_t { INIT, LEVEL1, RUN, }; stage_t louvain_stage = INIT; // Init the stage edge_count tot_edge_weight = 0; // Edge weight of the entire graph class cluster { uint32_t weight; uint32_t volume; std::vector<vertex_id_t> members; pthread_spinlock_t lock; public: cluster() { weight = 0; volume = 0; pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE); } void weight_pe(uint32_t weight) { this->weight += weight; } uint32_t get_weight() { return weight; } void volume_pe(uint32_t volume) { this->volume += volume; } uint32_t get_volume() { return volume; } void add_member(vertex_id_t member, uint32_t volume) { pthread_spin_lock(&lock); // FIXME: Locking :( members.push_back(member); this->volume += volume; pthread_spin_unlock(&lock); } void remove_member(vertex_id_t member_id, uint32_t volume) { pthread_spin_lock(&lock); // FIXME: Locking :( std::vector<vertex_id_t>::iterator it = std::find(members.begin(), members.end(), member_id); assert(it == members.end()); // TODO: rm -- Should be impossible members.erase(it); this->volume -= volume; pthread_spin_unlock(&lock); } std::vector<vertex_id_t>& get_members() { return this->members; } }; std::map<vertex_id_t, float> g_volume_map; // Per-vertex volume std::map<vertex_id_t, cluster> cluster_map; // Keep track of what cluster each vertex is in class louvain_vertex: public compute_vertex { vertex_id_t cluster; // current cluster float modularity; uint32_t self_edge_weight; uint32_t volume; public: louvain_vertex(vertex_id_t id): compute_vertex(id) { cluster = id; modularity = std::numeric_limits<float>::min(); self_edge_weight = 0; volume = 0; } void run(vertex_program &prog); void run(vertex_program &prog, const page_vertex &vertex); void run_on_message(vertex_program &, const vertex_message &msg1) {} void compute_modularity(edge_seq_iterator& id_it, data_seq_iterator& weight_it, vertex_id_t& max_cluster, float& max_mod, vertex_id_t my_id); void compute_vol_weight(data_seq_iterator& weight_it, edge_seq_iterator& id_it, vertex_program &prog); }; /* We need this to get the total edge_weight of the graph */ class louvain_vertex_program: public vertex_program_impl<louvain_vertex> { // Thread local edge_count th_local_edge_count; std::map<vertex_id_t, float> th_local_volume_map; public: louvain_vertex_program() { th_local_edge_count = 0; } typedef std::shared_ptr<louvain_vertex_program> ptr; static ptr cast2(vertex_program::ptr prog) { return std::static_pointer_cast<louvain_vertex_program, vertex_program>(prog); } void pp_ec(edge_count weight) { this->th_local_edge_count += weight; } uint32_t get_local_ec() { return th_local_edge_count.get_count(); } void update_volume(vertex_id_t vid, float vol) { std::map<vertex_id_t, float>::iterator it = th_local_volume_map.find(vid); if (it == th_local_volume_map.end()) { th_local_volume_map[vid] = vol; } else { it->second += vol; } } std::map<vertex_id_t, float>& get_vol_map() { return th_local_volume_map; } }; /* We need this to do the INIT phase and pass vertex_program_impl to the start method */ class louvain_vertex_program_creater: public vertex_program_creater { public: vertex_program::ptr create() const { return vertex_program::ptr(new louvain_vertex_program()); } }; void louvain_vertex::run(vertex_program &prog) { // Need to recompute the modularity vertex_id_t id = prog.get_vertex_id(*this); request_vertices(&id, 1); } // FIXME: This will only work for the first level void louvain_vertex::compute_modularity(edge_seq_iterator& id_it, data_seq_iterator& weight_it, vertex_id_t& max_cluster, float& max_mod, vertex_id_t my_id) { float delta_mod; // Iterate through all vertices in the g_volume_map & if one is my // neighbor then I need to modify it's volume to not include me. std::map<vertex_id_t, float>::iterator graph_it = g_volume_map.begin(); // Iterator for all graph vertices while(id_it.has_next()) { vertex_id_t nid = id_it.next(); edge_count e = weight_it.next(); delta_mod = ((e.get_count() - 0) / g_edge_weight) + (((g_volume_map[my_id] - this->self_edge_weight) - (g_volume_map[nid] - e.get_count())) * g_volume_map[my_id]) / (float)(2*(g_edge_weight^2)); BOOST_LOG_TRIVIAL(info) << "v" << my_id << " delta_mod for v" << graph_it->first << " = " << delta_mod; if (delta_mod > max_mod) { max_mod = delta_mod; max_cluster = graph_it->first; } } } // If anything changes cluster we cannot converge void set_changed(bool changed) { if (!g_changed) g_changed = changed; } void louvain_vertex::compute_vol_weight(data_seq_iterator& weight_it, edge_seq_iterator& id_it, vertex_program &prog) { edge_count local_edge_weight = 0; while (weight_it.has_next()) { edge_count e = weight_it.next(); vertex_id_t nid = id_it.next(); local_edge_weight += e.get_count(); if (nid == prog.get_vertex_id(*this)) { this->self_edge_weight += e.get_count(); } } ((louvain_vertex_program&)prog). pp_ec(local_edge_weight); this->volume = local_edge_weight.get_count() + (2*this->self_edge_weight); ((louvain_vertex_program&)prog).update_volume(this->cluster, local_edge_weight.get_count() + (2*this->self_edge_weight)); } // NOTE: If I know your ID I know what cluster you're in void louvain_vertex::run(vertex_program &prog, const page_vertex &vertex) { switch (louvain_stage) { case INIT: /* INIT just accums the global edge_count. I chose OUT_EDGE at random */ { data_seq_iterator weight_it = ((const page_directed_vertex&)vertex).get_data_seq_it<edge_count>(OUT_EDGE); edge_seq_iterator id_it = vertex.get_neigh_seq_it(OUT_EDGE); compute_vol_weight(weight_it, id_it, prog); } break; case LEVEL1: { // Compute the new cluster based on modularity float max_mod = this->modularity; vertex_id_t max_cluster = this->cluster; // Ignore's all not connected to this vertex edge_seq_iterator id_it = vertex.get_neigh_seq_it(OUT_EDGE); data_seq_iterator weight_it = ((const page_directed_vertex&)vertex).get_data_seq_it<edge_count>(OUT_EDGE); compute_modularity(id_it, weight_it, max_cluster, max_mod, prog.get_vertex_id(*this)); if (this->cluster != max_cluster) { BOOST_LOG_TRIVIAL(info) << "Vertex " << prog.get_vertex_id(*this) << " with mod = " << this->modularity << " < " << max_mod << " ,moved from cluster " << this->cluster << " ==> " << max_cluster << "\n"; set_changed(true); } else { BOOST_LOG_TRIVIAL(info) << "Vertex " << prog.get_vertex_id(*this) << " with mod = " << this->modularity << " ,stayed in cluster " << this->cluster << "\n"; } this->cluster = max_cluster; this->modularity = max_mod; } break; case RUN: BOOST_LOG_TRIVIAL(fatal) << "Run unimplemented!"; break; default: assert(0); } } // General Addition function for merging maps template <typename T> T add(T arg1, T arg2) { return arg1 + arg2; } template <typename T, typename U> void build_merge_map (std::map<T, U>& add_map, std::map<T, U>& agg_map, std::map<T, U>& new_map, U (*merge_func) (U, U)) { if (agg_map.size() == 0 || add_map.size() == 0) { return; } typename std::map<T,U>::iterator add_it = add_map.begin(); // Always iterate over the add maps keys typename std::map<T,U>::iterator agg_it = agg_map.begin(); for (; add_it != add_map.end(); ++add_it) { // skip the keys we don't care about while (agg_it->first < add_it->first) { if (++agg_it == agg_map.end()) { // There are no more keys in the agg_map new_map.insert(add_it, add_map.end()); // Get the rest of the map break; } } if (add_it->first == agg_it->first) { new_map[add_it->first] = merge_func(add_it->second, agg_it->second); } else { new_map[add_it->first] = add_it->second; } } } } namespace fg { void compute_louvain(FG_graph::ptr fg, const uint32_t levels) { graph_index::ptr index = NUMA_graph_index<louvain_vertex>::create( fg->get_graph_header()); graph_engine::ptr graph = fg->create_engine(index); BOOST_LOG_TRIVIAL(info) << "Starting Louvain with " << levels << " levels"; BOOST_LOG_TRIVIAL(info) << "prof_file: " << graph_conf.get_prof_file().c_str(); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStart(graph_conf.get_prof_file().c_str()); #endif struct timeval start, end; gettimeofday(&start, NULL); /*~~~~~~~~~~~~~~~~~~~~~~~~~~ Compute Vol & Weight ~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ graph->start_all(vertex_initializer::ptr(), vertex_program_creater::ptr(new louvain_vertex_program_creater())); graph->wait4complete(); std::vector<vertex_program::ptr> ec_progs; graph->get_vertex_programs(ec_progs); BOOST_FOREACH(vertex_program::ptr vprog, ec_progs) { louvain_vertex_program::ptr lvp = louvain_vertex_program::cast2(vprog); g_edge_weight += lvp->get_local_ec(); // Merge the volume maps std::map<vertex_id_t, float> merge_map; float (*add_func) (float, float); // Function pointer to add map add_func = &add; build_merge_map(lvp->get_vol_map(), g_volume_map, merge_map, add_func); g_volume_map.insert(merge_map.begin(), merge_map.end()); } #if 1 BOOST_LOG_TRIVIAL(info) << "The graph's total edge weight is " << g_edge_weight << "\n"; for (std::map<vertex_id_t, float>::iterator it = g_volume_map.begin(); it != g_volume_map.end(); it++) { BOOST_LOG_TRIVIAL(info) << "Vertex: " << it->first << ", Volume: " << it->second; } BOOST_LOG_TRIVIAL(info) << "\x1B[31m====================================================\x1B[0m\n"; #endif /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Compute modularity ~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #if 1 louvain_stage = LEVEL1; do { set_changed(false); graph->start_all(); graph->wait4complete(); } while (g_changed); louvain_stage = RUN; BOOST_LOG_TRIVIAL(info) << "\n Reached running stage\n"; #endif gettimeofday(&end, NULL); #ifdef PROFILER if (!graph_conf.get_prof_file().empty()) ProfilerStop(); #endif BOOST_LOG_TRIVIAL(info) << boost::format("It takes %1% seconds") % time_diff(start, end); return; } } <|endoftext|>
<commit_before>#include "log.h" #include "config.h" #include <sys/time.h> #include <sys/syscall.h> #include <stdarg.h> // FIXME: See note below. #include "simulator.h" #include "core_manager.h" //#define DISABLE_LOGGING using namespace std; Log *Log::_singleton; Log::Log(UInt32 coreCount) : _coreCount(coreCount) , _startTime(0) { char filename[256]; _coreFiles = new FILE* [2 * _coreCount]; for (UInt32 i = 0; i < _coreCount; i++) { sprintf(filename, "output_files/app_%u", i); _coreFiles[i] = fopen(filename, "w"); assert(_coreFiles[i] != NULL); } for (UInt32 i = _coreCount; i < 2 * _coreCount; i++) { sprintf(filename, "output_files/sim_%u", i-_coreCount); _coreFiles[i] = fopen(filename, "w"); assert(_coreFiles[i] != NULL); } _coreLocks = new Lock [2 * _coreCount]; assert(Config::getSingleton()->getProcessCount() != 0); _systemFiles = new FILE* [Config::getSingleton()->getProcessCount()]; _systemLocks = new Lock [Config::getSingleton()->getProcessCount()]; for (UInt32 i = 0; i < Config::getSingleton()->getProcessCount(); i++) { sprintf(filename, "output_files/system_%u", i); _systemFiles[i] = fopen(filename, "w"); assert(_systemFiles[i] != NULL); } _defaultFile = fopen("output_files/system-default","w"); Config::getSingleton()->getDisabledLogModules(_disabledModules); assert(_singleton == NULL); _singleton = this; } Log::~Log() { _singleton = NULL; for (UInt32 i = 0; i < 2 * _coreCount; i++) { fclose(_coreFiles[i]); } delete [] _coreLocks; delete [] _coreFiles; for (UInt32 i = 0; i < Config::getSingleton()->getProcessCount(); i++) { fclose(_systemFiles[i]); } delete [] _systemFiles; fclose(_defaultFile); } Log* Log::getSingleton() { assert(_singleton); return _singleton; } Boolean Log::isEnabled(const char* module) { return _disabledModules.find(module) == _disabledModules.end(); } UInt64 Log::getTimestamp() { timeval t; gettimeofday(&t, NULL); UInt64 time = (((UInt64)t.tv_sec) * 1000000 + t.tv_usec); if (_startTime == 0) _startTime = time; return time - _startTime; } void Log::discoverCore(core_id_t *core_id, bool *sim_thread) { CoreManager *core_manager; if (!Sim() || !(core_manager = Sim()->getCoreManager())) { *core_id = INVALID_CORE_ID; *sim_thread = false; return; } *core_id = core_manager->getCurrentCoreID(); if (*core_id != INVALID_CORE_ID) { *sim_thread = false; return; } else { *core_id = core_manager->getCurrentSimThreadCoreID(); *sim_thread = true; return; } } void Log::getFile(core_id_t core_id, bool sim_thread, FILE **file, Lock **lock) { *file = NULL; *lock = NULL; if (core_id == INVALID_CORE_ID) { // System file -- use process num if available if (Config::getSingleton()->getCurrentProcessNum() != (UInt32) -1) { assert(Config::getSingleton()->getCurrentProcessNum() < Config::getSingleton()->getProcessCount()); *file = _systemFiles[Config::getSingleton()->getCurrentProcessNum()]; *lock = &_systemLocks[Config::getSingleton()->getCurrentProcessNum()]; } else { *file = _defaultFile; *lock = &_defaultLock; } } else { // Core file UInt32 fileID = core_id + (sim_thread ? _coreCount : 0); *file = _coreFiles[fileID]; *lock = &_coreLocks[fileID]; } } std::string Log::getModule(const char *filename) { #ifdef LOCK_LOGS _modules_lock.acquire(); #endif std::map<const char*, std::string>::const_iterator it = _modules.find(filename); #ifdef LOCK_LOGS _modules_lock.release(); #endif if (it != _modules.end()) { return it->second; } else { // build module string string mod; for (UInt32 i = 0; i < MODULE_LENGTH && filename[i] != '\0'; i++) mod.push_back(filename[i]); while (mod.length() < MODULE_LENGTH) mod.push_back(' '); pair<const char*, std::string> p(filename, mod); #ifdef LOCK_LOGS _modules_lock.acquire(); #endif _modules.insert(p); #ifdef LOCK_LOGS _modules_lock.release(); #endif return mod; } } void Log::log(ErrorState err, const char* source_file, SInt32 source_line, const char *format, ...) { #ifdef DISABLE_LOGGING if (err != Error) return; #endif core_id_t core_id; bool sim_thread; discoverCore(&core_id, &sim_thread); if (!isEnabled(source_file)) return; FILE *file; Lock *lock; getFile(core_id, sim_thread, &file, &lock); int tid = syscall(__NR_gettid); lock->acquire(); std::string module = getModule(source_file); // This is ugly, but it just prints the time stamp, process number, core number, source file/line if (core_id != INVALID_CORE_ID) // valid core id fprintf(file, "%-10llu [%5d] [%2i] [%2i] [%s:%4d]%s", getTimestamp(), tid, Config::getSingleton()->getCurrentProcessNum(), core_id, module.c_str(), source_line, (sim_thread ? "* " : " ")); else if (Config::getSingleton()->getCurrentProcessNum() != (UInt32)-1) // valid proc id fprintf(file, "%-10llu [%5d] [%2i] [ ] [%s:%4d] ", getTimestamp(), tid, Config::getSingleton()->getCurrentProcessNum(), module.c_str(), source_line); else // who knows fprintf(file, "%-10llu [%5d] [ ] [ ] [%s:%4d] ", getTimestamp(), tid, module.c_str(), source_line); switch (err) { case None: default: break; case Warning: fprintf(file, "*WARNING* "); break; case Error: fprintf(file, "*ERROR* "); break; }; va_list args; va_start(args, format); vfprintf(file, format, args); va_end(args); fprintf(file, "\n"); fflush(file); lock->release(); if (err == Error) abort(); } void Log::notifyWarning() { if (_state == None) { fprintf(stderr, "LOG : Check logs -- there is a warning!\n"); _state = Warning; } } void Log::notifyError() { if (_state == None || _state == Warning) { fprintf(stderr, "LOG : Check logs -- there is an ERROR!\n"); _state = Error; } abort(); } <commit_msg>[log] Output base part of filename only.<commit_after>#include "log.h" #include "config.h" #include <sys/time.h> #include <sys/syscall.h> #include <stdarg.h> // FIXME: See note below. #include "simulator.h" #include "core_manager.h" //#define DISABLE_LOGGING using namespace std; Log *Log::_singleton; Log::Log(UInt32 coreCount) : _coreCount(coreCount) , _startTime(0) { char filename[256]; _coreFiles = new FILE* [2 * _coreCount]; for (UInt32 i = 0; i < _coreCount; i++) { sprintf(filename, "output_files/app_%u", i); _coreFiles[i] = fopen(filename, "w"); assert(_coreFiles[i] != NULL); } for (UInt32 i = _coreCount; i < 2 * _coreCount; i++) { sprintf(filename, "output_files/sim_%u", i-_coreCount); _coreFiles[i] = fopen(filename, "w"); assert(_coreFiles[i] != NULL); } _coreLocks = new Lock [2 * _coreCount]; assert(Config::getSingleton()->getProcessCount() != 0); _systemFiles = new FILE* [Config::getSingleton()->getProcessCount()]; _systemLocks = new Lock [Config::getSingleton()->getProcessCount()]; for (UInt32 i = 0; i < Config::getSingleton()->getProcessCount(); i++) { sprintf(filename, "output_files/system_%u", i); _systemFiles[i] = fopen(filename, "w"); assert(_systemFiles[i] != NULL); } _defaultFile = fopen("output_files/system-default","w"); Config::getSingleton()->getDisabledLogModules(_disabledModules); assert(_singleton == NULL); _singleton = this; } Log::~Log() { _singleton = NULL; for (UInt32 i = 0; i < 2 * _coreCount; i++) { fclose(_coreFiles[i]); } delete [] _coreLocks; delete [] _coreFiles; for (UInt32 i = 0; i < Config::getSingleton()->getProcessCount(); i++) { fclose(_systemFiles[i]); } delete [] _systemFiles; fclose(_defaultFile); } Log* Log::getSingleton() { assert(_singleton); return _singleton; } Boolean Log::isEnabled(const char* module) { return _disabledModules.find(module) == _disabledModules.end(); } UInt64 Log::getTimestamp() { timeval t; gettimeofday(&t, NULL); UInt64 time = (((UInt64)t.tv_sec) * 1000000 + t.tv_usec); if (_startTime == 0) _startTime = time; return time - _startTime; } void Log::discoverCore(core_id_t *core_id, bool *sim_thread) { CoreManager *core_manager; if (!Sim() || !(core_manager = Sim()->getCoreManager())) { *core_id = INVALID_CORE_ID; *sim_thread = false; return; } *core_id = core_manager->getCurrentCoreID(); if (*core_id != INVALID_CORE_ID) { *sim_thread = false; return; } else { *core_id = core_manager->getCurrentSimThreadCoreID(); *sim_thread = true; return; } } void Log::getFile(core_id_t core_id, bool sim_thread, FILE **file, Lock **lock) { *file = NULL; *lock = NULL; if (core_id == INVALID_CORE_ID) { // System file -- use process num if available if (Config::getSingleton()->getCurrentProcessNum() != (UInt32) -1) { assert(Config::getSingleton()->getCurrentProcessNum() < Config::getSingleton()->getProcessCount()); *file = _systemFiles[Config::getSingleton()->getCurrentProcessNum()]; *lock = &_systemLocks[Config::getSingleton()->getCurrentProcessNum()]; } else { *file = _defaultFile; *lock = &_defaultLock; } } else { // Core file UInt32 fileID = core_id + (sim_thread ? _coreCount : 0); *file = _coreFiles[fileID]; *lock = &_coreLocks[fileID]; } } std::string Log::getModule(const char *filename) { #ifdef LOCK_LOGS _modules_lock.acquire(); #endif std::map<const char*, std::string>::const_iterator it = _modules.find(filename); #ifdef LOCK_LOGS _modules_lock.release(); #endif if (it != _modules.end()) { return it->second; } else { // build module string string mod; // find actual file name ... const char *ptr = strrchr(filename, '/'); if (ptr != NULL) filename = ptr + 1; for (UInt32 i = 0; i < MODULE_LENGTH && filename[i] != '\0'; i++) mod.push_back(filename[i]); while (mod.length() < MODULE_LENGTH) mod.push_back(' '); pair<const char*, std::string> p(filename, mod); #ifdef LOCK_LOGS _modules_lock.acquire(); #endif _modules.insert(p); #ifdef LOCK_LOGS _modules_lock.release(); #endif return mod; } } void Log::log(ErrorState err, const char* source_file, SInt32 source_line, const char *format, ...) { #ifdef DISABLE_LOGGING if (err != Error) return; #endif core_id_t core_id; bool sim_thread; discoverCore(&core_id, &sim_thread); if (!isEnabled(source_file)) return; FILE *file; Lock *lock; getFile(core_id, sim_thread, &file, &lock); int tid = syscall(__NR_gettid); lock->acquire(); std::string module = getModule(source_file); // This is ugly, but it just prints the time stamp, process number, core number, source file/line if (core_id != INVALID_CORE_ID) // valid core id fprintf(file, "%-10llu [%5d] [%2i] [%2i] [%s:%4d]%s", getTimestamp(), tid, Config::getSingleton()->getCurrentProcessNum(), core_id, module.c_str(), source_line, (sim_thread ? "* " : " ")); else if (Config::getSingleton()->getCurrentProcessNum() != (UInt32)-1) // valid proc id fprintf(file, "%-10llu [%5d] [%2i] [ ] [%s:%4d] ", getTimestamp(), tid, Config::getSingleton()->getCurrentProcessNum(), module.c_str(), source_line); else // who knows fprintf(file, "%-10llu [%5d] [ ] [ ] [%s:%4d] ", getTimestamp(), tid, module.c_str(), source_line); switch (err) { case None: default: break; case Warning: fprintf(file, "*WARNING* "); break; case Error: fprintf(file, "*ERROR* "); break; }; va_list args; va_start(args, format); vfprintf(file, format, args); va_end(args); fprintf(file, "\n"); fflush(file); lock->release(); if (err == Error) abort(); } void Log::notifyWarning() { if (_state == None) { fprintf(stderr, "LOG : Check logs -- there is a warning!\n"); _state = Warning; } } void Log::notifyError() { if (_state == None || _state == Warning) { fprintf(stderr, "LOG : Check logs -- there is an ERROR!\n"); _state = Error; } abort(); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief ルネサス RX 選択 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #if defined(SIG_RX621) #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX621/system.hpp" #include "RX621/sci.hpp" #include "RX621/icu.hpp" #elif defined(SIG_RX24T) #include "RX24T/peripheral.hpp" #include "RX600/port.hpp" #include "RX24T/system.hpp" #include "RX24T/dtc.hpp" #include "RX24T/icu.hpp" #include "RX24T/mtu3.hpp" #include "RX24T/poe3.hpp" #include "RX24T/tmr.hpp" #include "RX600/cmt.hpp" #include "RX24T/sci.hpp" #include "RX24T/riic.hpp" #include "RX24T/rspi.hpp" #include "RX24T/crc.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/da.hpp" #include "RX24T/cmpc.hpp" #include "RX24T/doc.hpp" #include "RX24T/port_map.hpp" #include "RX24T/power_cfg.hpp" #include "RX24T/icu_mgr.hpp" #elif defined(SIG_RX63T) #include "RX63T/peripheral.hpp" #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX63T/system.hpp" #include "RX63T/sci.hpp" #include "RX63T/icu.hpp" #include "RX63T/port_map.hpp" #include "RX63T/power_cfg.hpp" #include "RX63T/icu_mgr.hpp" #elif defined(SIG_RX64M) #include "RX64M/peripheral.hpp" #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX64M/system.hpp" #include "RX64M/mpc.hpp" #include "RX64M/icu.hpp" #include "RX64M/sci.hpp" #include "RX64M/riic.hpp" #include "RX64M/port_map.hpp" #include "RX64M/power_cfg.hpp" #include "RX64M/icu_mgr.hpp" #else # error "Requires SIG_XXX to be defined" #endif <commit_msg>add bus.hpp<commit_after>#pragma once //=====================================================================// /*! @file @brief ルネサス RX 選択 @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #if defined(SIG_RX621) #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX621/system.hpp" #include "RX621/sci.hpp" #include "RX621/icu.hpp" #elif defined(SIG_RX24T) #include "RX24T/peripheral.hpp" #include "RX600/port.hpp" #include "RX24T/system.hpp" #include "RX24T/dtc.hpp" #include "RX24T/icu.hpp" #include "RX24T/mtu3.hpp" #include "RX24T/poe3.hpp" #include "RX24T/tmr.hpp" #include "RX600/cmt.hpp" #include "RX24T/sci.hpp" #include "RX24T/riic.hpp" #include "RX24T/rspi.hpp" #include "RX24T/crc.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/da.hpp" #include "RX24T/cmpc.hpp" #include "RX24T/doc.hpp" #include "RX24T/port_map.hpp" #include "RX24T/power_cfg.hpp" #include "RX24T/icu_mgr.hpp" #elif defined(SIG_RX63T) #include "RX63T/peripheral.hpp" #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX63T/system.hpp" #include "RX63T/sci.hpp" #include "RX63T/icu.hpp" #include "RX63T/port_map.hpp" #include "RX63T/power_cfg.hpp" #include "RX63T/icu_mgr.hpp" #elif defined(SIG_RX64M) #include "RX64M/peripheral.hpp" #include "RX600/port.hpp" #include "RX600/cmt.hpp" #include "RX64M/system.hpp" #include "RX64M/bus.hpp" #include "RX64M/mpc.hpp" #include "RX64M/icu.hpp" #include "RX64M/sci.hpp" #include "RX64M/riic.hpp" #include "RX64M/port_map.hpp" #include "RX64M/power_cfg.hpp" #include "RX64M/icu_mgr.hpp" #else # error "Requires SIG_XXX to be defined" #endif <|endoftext|>
<commit_before>#include <Arduino.h> #include <SPI.h> #include <math.h> #include "Heater.h" // E0 Main extruder const int E0_enable = 26; // low == enabled const int E0_step = 34; const int E0_dir = 43; const int E0_MS1 = 65; const int E0_MS2 = 66; const int E0_digipot_channel = 0; const float E0_steps_per_mm = 38.197; const int E0_heater_pin = 9; const int E0_digipot_setting = 100; const bool E0_EXTRUDE = 0; const bool E0_RETRACT = 1; const int E0_thermistor = 0; const int BETA_NOZZLE = 4267; // Semitec 104GT-2 Thermistor const long R_ZERO = 100000; // Resistance at 25C const int E0_SAMPLE_TIME = 500; // milliseconds const int LED_PIN = 13; const int MAX_VELOCITY = 10430; // 0.3183 increments/cycle * 2^15 = 10430 const int MAX_ACCELERATION = 4; // 1.1406*10^-4 * 2^15 = 3.73 = 3 int E0_acceleration = 0; int E0_velocity = 0; signed int E0_position = 0; int target_velocity = 0; unsigned long motor_test_time = 0; int micro_step_scale = 1; // The micro step scale can be 1, 2, 4, or 16 based on // the stepper driver data sheet // Nozzle Heater Heater E0_heater(E0_heater_pin, E0_thermistor, BETA_NOZZLE, R_ZERO, E0_SAMPLE_TIME, "E0"); // Digipot const int slave_select_pin = 38; // Fans const int small_fan = 5; const int large_fan = 8; unsigned long last_fan_time = 0; const int FAN_SAMPLE_TIME = 2000; // Bed Heater const int bed_heater_pin = 3; const int BETA_BED = 3950; // Not sure this is correct const int bed_thermistor = 56; const int bed_sample_time = 1000; // milliseconds Heater bed_heater(bed_heater_pin, bed_thermistor, BETA_BED, R_ZERO, bed_sample_time, "Bed"); // Stepper Motor const int MIN_HIGH_PULSE = 200; // microseconds const int MIN_LOW_PULSE = 5; //microseconds // TODO: Add ramp information // Inputs from robot const int MAN_EXTRUDE = 84, HEAT_BED = 83, HEAT_NOZZLE = 82, PROG_FEED = 80, ALL_STOP = 79; // Outputs to robot const int BED_AT_TEMP = 71, NOZZLE_AT_TEMP = 72; void setup() { // put your setup code here, to run once: pinMode(E0_enable, OUTPUT); pinMode(E0_step, OUTPUT); pinMode(E0_dir, OUTPUT); pinMode(E0_MS1, OUTPUT); pinMode(E0_MS2, OUTPUT); pinMode(slave_select_pin, OUTPUT); pinMode(small_fan, OUTPUT); pinMode(large_fan, OUTPUT); // Inputs from robot pinMode(MAN_EXTRUDE, INPUT); pinMode(HEAT_BED, INPUT); pinMode(HEAT_NOZZLE, INPUT); pinMode(PROG_FEED, INPUT); pinMode(ALL_STOP, INPUT); // Outputs to robot pinMode(BED_AT_TEMP, OUTPUT); pinMode(NOZZLE_AT_TEMP, OUTPUT); pinMode(LED_PIN, OUTPUT); Serial.begin(9600); /* The Rambo board has programmable potentiometers or 'digipots' for tuning each individual stepper motor. the following code handles that */ SPI.begin(); digitalWrite(slave_select_pin, LOW); SPI.transfer(E0_digipot_channel); SPI.transfer(E0_digipot_setting); SPI.end(); digitalWrite(slave_select_pin, HIGH); digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); digitalWrite(E0_dir, LOW); E0_heater.setTunings(50, 1, 9); // Initial Nozzle PID parameters E0_heater.setTargetTemp(100); bed_heater.setTunings(50, 0.5, 9); // Initial Bed PID Values bed_heater.setTargetTemp(35); // initialize timer 3 for the stepper motor interrupts noInterrupts(); // clear current bit selections TCCR3A = 0; TCCR3B = 0; TCNT3 = 0; OCR3A = 1600; // compare match register 10kHz TCCR3B |= (1 << WGM12); // CTC mode TCCR3B |= (1 << CS10); // No prescaling TIMSK3 |= (1 << OCIE3A); // enable timer compare interrupt interrupts(); // enable global interupts } /** scaleMicroStep() checks the current commanded velocity and determines if it is within one of the available micro step ranges. Using micro steps enables better lower speed performance and more reliable accelerations from zero. The available micro steps are 1 (full speed) 2, 4, and 16. */ void scaleMicroStep(){ int holdScale = MAX_VELOCITY/abs(E0_velocity); if(holdScale >= 16){ micro_step_scale = 16; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 4){ micro_step_scale = 4; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 2){ micro_step_scale = 2; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, LOW); } else{ micro_step_scale = 1; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); } delayMicroseconds(2); } ISR(TIMER3_COMPA_vect){ noInterrupts(); E0_velocity += E0_acceleration; if(E0_velocity > MAX_VELOCITY){ E0_velocity = MAX_VELOCITY; } else if(E0_velocity < -MAX_VELOCITY){ E0_velocity = -MAX_VELOCITY; } if(E0_velocity < 0){ // Retract filament digitalWrite(E0_dir, HIGH); } else{ // Extrude filament digitalWrite(E0_dir, LOW); } scaleMicroStep(); E0_position += E0_velocity*micro_step_scale; if(SREG & 0b00001000){ // The third bit in SREG is the overflow flag. If we overflow // Then we know we should increment the stepper E0_position -= 0x8000; // Subtract a 1 in 16bit math digitalWrite(E0_step, HIGH); delayMicroseconds(2); digitalWrite(E0_step, LOW); } if(target_velocity - E0_velocity > MAX_ACCELERATION){ E0_acceleration = MAX_ACCELERATION; } else if(E0_velocity - target_velocity > MAX_ACCELERATION){ E0_acceleration = -MAX_ACCELERATION; } else{ E0_acceleration = 0; } interrupts(); } void setFans(){ /* Tests the current temperature of the nozzle and then turns on the fans if they are above their temperatures. */ unsigned long now = millis(); if(now - last_fan_time > FAN_SAMPLE_TIME){ float currTemp = E0_heater.getCurrTemp(); if (currTemp > 100) { analogWrite(small_fan, 255); } if(currTemp > 180){ analogWrite(large_fan, 255); } last_fan_time = now; } } void testMotor(){ noInterrupts(); unsigned long ellapsed = millis() - motor_test_time; if((E0_velocity >= MAX_VELOCITY || E0_velocity <= -MAX_VELOCITY) && motor_test_time==0){ motor_test_time = millis(); // E0_acceleration *= -1; } else if(motor_test_time >0 && ellapsed < 1500){ } else if(motor_test_time>0 && ellapsed >= 1500){ motor_test_time = 0; E0_acceleration *= -1; } interrupts(); } void loop() { if(digitalRead(HEAT_NOZZLE)){ E0_heater.setTargetTemp(100); if(E0_heater.atTemp()){ digitalWrite(NOZZLE_AT_TEMP, HIGH); } else{ digitalWrite(NOZZLE_AT_TEMP, LOW); } } else{ E0_heater.setTargetTemp(0); } if(digitalRead(MAN_EXTRUDE)){ target_velocity = 100*2.086; } else{ target_velocity = 0; } E0_heater.compute(); bed_heater.compute(); setFans(); } <commit_msg>Changed inputs to use pull up resistors<commit_after>#include <Arduino.h> #include <SPI.h> #include <math.h> #include "Heater.h" // E0 Main extruder const int E0_enable = 26; // low == enabled const int E0_step = 34; const int E0_dir = 43; const int E0_MS1 = 65; const int E0_MS2 = 66; const int E0_digipot_channel = 0; const float E0_steps_per_mm = 38.197; const int E0_heater_pin = 9; const int E0_digipot_setting = 100; const bool E0_EXTRUDE = 0; const bool E0_RETRACT = 1; const int E0_thermistor = 0; const int BETA_NOZZLE = 4267; // Semitec 104GT-2 Thermistor const long R_ZERO = 100000; // Resistance at 25C const int E0_SAMPLE_TIME = 500; // milliseconds const int LED_PIN = 13; const int MAX_VELOCITY = 10430; // 0.3183 increments/cycle * 2^15 = 10430 const int MAX_ACCELERATION = 4; // 1.1406*10^-4 * 2^15 = 3.73 = 3 int E0_acceleration = 0; int E0_velocity = 0; signed int E0_position = 0; int target_velocity = 0; unsigned long motor_test_time = 0; int micro_step_scale = 1; // The micro step scale can be 1, 2, 4, or 16 based on // the stepper driver data sheet // Nozzle Heater Heater E0_heater(E0_heater_pin, E0_thermistor, BETA_NOZZLE, R_ZERO, E0_SAMPLE_TIME, "E0"); // Digipot const int slave_select_pin = 38; // Fans const int small_fan = 5; const int large_fan = 8; unsigned long last_fan_time = 0; const int FAN_SAMPLE_TIME = 2000; // Bed Heater const int bed_heater_pin = 3; const int BETA_BED = 3950; // Not sure this is correct const int bed_thermistor = 56; const int bed_sample_time = 1000; // milliseconds Heater bed_heater(bed_heater_pin, bed_thermistor, BETA_BED, R_ZERO, bed_sample_time, "Bed"); // Stepper Motor const int MIN_HIGH_PULSE = 200; // microseconds const int MIN_LOW_PULSE = 5; //microseconds // TODO: Add ramp information // Inputs from robot const int MAN_EXTRUDE = 84, HEAT_BED = 83, HEAT_NOZZLE = 82, PROG_FEED = 80, ALL_STOP = 79; // Outputs to robot const int BED_AT_TEMP = 71, NOZZLE_AT_TEMP = 72; // Report unsigned long last_report_time = 0; void setup() { // put your setup code here, to run once: pinMode(E0_enable, OUTPUT); pinMode(E0_step, OUTPUT); pinMode(E0_dir, OUTPUT); pinMode(E0_MS1, OUTPUT); pinMode(E0_MS2, OUTPUT); pinMode(slave_select_pin, OUTPUT); pinMode(small_fan, OUTPUT); pinMode(large_fan, OUTPUT); // Inputs from robot pinMode(MAN_EXTRUDE, INPUT_PULLUP); pinMode(HEAT_BED, INPUT_PULLUP); pinMode(HEAT_NOZZLE, INPUT_PULLUP); pinMode(PROG_FEED, INPUT_PULLUP); pinMode(ALL_STOP, INPUT_PULLUP); // Outputs to robot pinMode(BED_AT_TEMP, OUTPUT); pinMode(NOZZLE_AT_TEMP, OUTPUT); pinMode(LED_PIN, OUTPUT); Serial.begin(9600); /* The Rambo board has programmable potentiometers or 'digipots' for tuning each individual stepper motor. the following code handles that */ SPI.begin(); digitalWrite(slave_select_pin, LOW); SPI.transfer(E0_digipot_channel); SPI.transfer(E0_digipot_setting); SPI.end(); digitalWrite(slave_select_pin, HIGH); digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); digitalWrite(E0_dir, LOW); E0_heater.setTunings(50, 1, 9); // Initial Nozzle PID parameters E0_heater.setTargetTemp(100); bed_heater.setTunings(50, 0.5, 9); // Initial Bed PID Values bed_heater.setTargetTemp(35); // initialize timer 3 for the stepper motor interrupts noInterrupts(); // clear current bit selections TCCR3A = 0; TCCR3B = 0; TCNT3 = 0; OCR3A = 1600; // compare match register 10kHz TCCR3B |= (1 << WGM12); // CTC mode TCCR3B |= (1 << CS10); // No prescaling TIMSK3 |= (1 << OCIE3A); // enable timer compare interrupt interrupts(); // enable global interupts } /** scaleMicroStep() checks the current commanded velocity and determines if it is within one of the available micro step ranges. Using micro steps enables better lower speed performance and more reliable accelerations from zero. The available micro steps are 1 (full speed) 2, 4, and 16. */ void scaleMicroStep(){ int holdScale = MAX_VELOCITY/abs(E0_velocity); if(holdScale >= 16){ micro_step_scale = 16; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 4){ micro_step_scale = 4; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 2){ micro_step_scale = 2; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, LOW); } else{ micro_step_scale = 1; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); } delayMicroseconds(2); } ISR(TIMER3_COMPA_vect){ noInterrupts(); E0_velocity += E0_acceleration; if(E0_velocity > MAX_VELOCITY){ E0_velocity = MAX_VELOCITY; } else if(E0_velocity < -MAX_VELOCITY){ E0_velocity = -MAX_VELOCITY; } if(E0_velocity < 0){ // Retract filament digitalWrite(E0_dir, HIGH); } else{ // Extrude filament digitalWrite(E0_dir, LOW); } scaleMicroStep(); E0_position += E0_velocity*micro_step_scale; if(SREG & 0b00001000){ // The third bit in SREG is the overflow flag. If we overflow // Then we know we should increment the stepper E0_position -= 0x8000; // Subtract a 1 in 16bit math digitalWrite(E0_step, HIGH); delayMicroseconds(2); digitalWrite(E0_step, LOW); } if(target_velocity - E0_velocity > MAX_ACCELERATION){ E0_acceleration = MAX_ACCELERATION; } else if(E0_velocity - target_velocity > MAX_ACCELERATION){ E0_acceleration = -MAX_ACCELERATION; } else{ E0_acceleration = 0; } interrupts(); } void setFans(){ /* Tests the current temperature of the nozzle and then turns on the fans if they are above their temperatures. */ unsigned long now = millis(); if(now - last_fan_time > FAN_SAMPLE_TIME){ float currTemp = E0_heater.getCurrTemp(); if (currTemp > 100) { analogWrite(small_fan, 255); } if(currTemp > 180){ analogWrite(large_fan, 255); } last_fan_time = now; } } void testMotor(){ noInterrupts(); unsigned long ellapsed = millis() - motor_test_time; if((E0_velocity >= MAX_VELOCITY || E0_velocity <= -MAX_VELOCITY) && motor_test_time==0){ motor_test_time = millis(); // E0_acceleration *= -1; } else if(motor_test_time >0 && ellapsed < 1500){ } else if(motor_test_time>0 && ellapsed >= 1500){ motor_test_time = 0; E0_acceleration *= -1; } interrupts(); } void report(){ unsigned long now = millis(); if(now - last_report_time > 1000){ Serial.print("velocity target: "); Serial.println(target_velocity); Serial.print("Accel: "); Serial.println(E0_acceleration); Serial.print("MAN_EXTRUDE: "); Serial.println(digitalRead(MAN_EXTRUDE)); Serial.println(); last_report_time = now; } } void loop() { if(!digitalRead(HEAT_NOZZLE)){ E0_heater.setTargetTemp(100); if(E0_heater.atTemp()){ digitalWrite(NOZZLE_AT_TEMP, HIGH); } else{ digitalWrite(NOZZLE_AT_TEMP, LOW); } } else{ E0_heater.setTargetTemp(0); } if(!digitalRead(MAN_EXTRUDE)){ target_velocity = 100*2.086; } else{ target_velocity = 0; } E0_heater.compute(); bed_heater.compute(); setFans(); report(); } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include <OISKeyboard.h> #include "OgreOverlay.h" #include "EC_OgreConsoleOverlay.h" #include "OgreRenderingModule.h" #include "InputEvents.h" #include "ConsoleModule.h" #include "ConsoleManager.h" #include "CommandManager.h" namespace Console { class LogListener : public Foundation::LogListenerInterface { LogListener(); OgreOverlay *console_; public: LogListener(OgreOverlay *console) : Foundation::LogListenerInterface(), console_(console) {} virtual ~LogListener() {} virtual void LogMessage(const std::string &message) { console_->Print(message); } }; ///////////////////////////////////////////// OgreOverlay::OgreOverlay(Foundation::ModuleInterface *module) : Console::ConsoleServiceInterface() , module_(module) , log_listener_(LogListenerPtr(new LogListener(this))) , max_lines_(256) , max_visible_lines(1) , text_position_(0) , prompt_timer_(0) , update_(false) , scroll_line_size_(20) , cursor_offset_(0) { Foundation::Framework *framework = module_->GetFramework(); cursor_blink_freq_ = framework->GetDefaultConfig().DeclareSetting("DebugConsole", "cursor_blink_frequency", 0.5f); if ( framework->GetModuleManager()->HasModule(Foundation::Module::MT_Renderer) ) { OgreRenderer::OgreRenderingModule *rendering_module = framework->GetModuleManager()->GetModule<OgreRenderer::OgreRenderingModule>(Foundation::Module::MT_Renderer); if (rendering_module) rendering_module->GetRenderer()->SubscribeLogListener(log_listener_); } } OgreOverlay::~OgreOverlay() { Foundation::Framework *framework = module_->GetFramework(); console_overlay_.reset(); if ( framework->GetServiceManager()->IsRegistered(Foundation::Service::ST_SceneManager)) { Foundation::SceneManagerServiceInterface *scene_manager = framework->GetService<Foundation::SceneManagerServiceInterface>(Foundation::Service::ST_SceneManager); if (scene_manager->HasScene("Console")) { scene_manager->DeleteScene("Console"); } } if ( framework->GetModuleManager()->HasModule(Foundation::Module::MT_Renderer) ) { OgreRenderer::OgreRenderingModule *rendering_module = framework->GetModuleManager()->GetModule<OgreRenderer::OgreRenderingModule>(Foundation::Module::MT_Renderer); if (rendering_module) rendering_module->GetRenderer()->UnsubscribeLogListener(log_listener_); } } void OgreOverlay::Create() { Foundation::Framework *framework = module_->GetFramework(); if ( framework->GetServiceManager()->IsRegistered(Foundation::Service::ST_SceneManager) && framework->GetComponentManager()->CanCreate("EC_OgreConsoleOverlay") ) { Foundation::SceneManagerServiceInterface *scene_manager = framework->GetService<Foundation::SceneManagerServiceInterface>(Foundation::Service::ST_SceneManager); if (scene_manager->HasScene("Console")) throw Core::Exception("Scene for console already exists."); Foundation::ScenePtr scene = scene_manager->CreateScene("Console"); Foundation::EntityPtr entity = scene->CreateEntity(scene->GetNextFreeId()); console_overlay_ = framework->GetComponentManager()->CreateComponent("EC_OgreConsoleOverlay"); entity->AddEntityComponent(console_overlay_); max_visible_lines = checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->GetMaxVisibleLines(); update_ = true; } ConsolePtr manager = checked_static_cast<ConsoleModule*>(module_)->GetConsole(); command_manager_ = checked_static_cast<ConsoleManager*>(manager.get())->GetCommandManager(); } // virtual void OgreOverlay::Print(const std::string &text) { { Core::MutexLock lock(mutex_); message_lines_.push_front(text); if (message_lines_.size() >= max_lines_) message_lines_.pop_back(); update_ = true; } } // virtual void OgreOverlay::Scroll(int rel) { { Core::MutexLock lock(mutex_); int lines = rel / scroll_line_size_; if (static_cast<int>(text_position_) + lines < 0) lines = -(lines - (lines - static_cast<int>(text_position_))); if (text_position_ + lines > message_lines_.size() - max_visible_lines - 1) lines -= (lines - ((message_lines_.size() - max_visible_lines - 1) - text_position_)); text_position_ += lines; update_ = true; } } void OgreOverlay::SetVisible(bool visible) { if (console_overlay_) { checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->SetVisible(visible); } if (visible) { update_ = true; } } bool OgreOverlay::IsVisible() const { if (console_overlay_) { return checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->IsVisible(); } return false; } bool OgreOverlay::IsActive() const { if (console_overlay_) { return checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->IsActive(); } return false; } void OgreOverlay::Update(Core::f64 frametime) { checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->Update(frametime); bool update = false; { Core::MutexLock lock(mutex_); update = update_; } // blink prompt cursor static bool show_cursor = false; prompt_timer_ += frametime; if (prompt_timer_ > cursor_blink_freq_) { show_cursor = !show_cursor; prompt_timer_ = 0.f; update = true; } if (update) { std::string page; FormatPage(page); std::string prompt; size_t cursor_offset; { Core::MutexLock lock(mutex_); prompt = command_line_; cursor_offset = cursor_offset_; update_ = false; } // add cursor if (show_cursor) prompt.insert(prompt.size() - cursor_offset, "_"); else if (cursor_offset > 0) prompt.insert(prompt.size() - cursor_offset, " "); //add the prompt page += ">" + prompt; Display(page); } } bool OgreOverlay::HandleKeyDown(int code, unsigned int text) { bool result = true; switch (code) { case OIS::KC_PGUP: Scroll(scroll_line_size_ * max_visible_lines - 2); break; case OIS::KC_PGDOWN: Scroll(-scroll_line_size_ * max_visible_lines - 2); break; case OIS::KC_UP: Scroll(scroll_line_size_); break; case OIS::KC_DOWN: Scroll(-scroll_line_size_); break; case OIS::KC_BACK: { Core::MutexLock lock(mutex_); if (command_line_.empty() == false && cursor_offset_ < command_line_.length()) { command_line_ = command_line_.substr(0, command_line_.length() - cursor_offset_ - 1) + command_line_.substr(command_line_.length() - cursor_offset_, cursor_offset_); } break; } case OIS::KC_LEFT: MoveCursor(-1); break; case OIS::KC_RIGHT: MoveCursor(1); break; case OIS::KC_RETURN: { std::string command_line; { Core::MutexLock lock(mutex_); command_line = command_line_; command_line_.clear(); text_position_ = 0; cursor_offset_ = 0; } if (command_manager_) command_manager_->QueueCommand(command_line); Print(command_line); } break; default: Core::MutexLock lock(mutex_); result = AddCharacter(text, command_line_, cursor_offset_); break; } if (result) update_ = true; return result; } void OgreOverlay::MoveCursor(int offset) { int offset_neg = -offset; if (offset_neg < 0) { Core::MutexLock lock(mutex_); if (cursor_offset_ >= -offset_neg) cursor_offset_ += offset_neg; } else { Core::MutexLock lock(mutex_); cursor_offset_ = std::min(cursor_offset_ + offset_neg, command_line_.length()); } } void OgreOverlay::FormatPage(std::string &pageOut) { Core::MutexLock lock(mutex_); if (!console_overlay_) return; std::string page; size_t num_lines = 0; Core::StringList::const_iterator line = message_lines_.begin(); assert (message_lines_.size() > text_position_); std::advance(line, text_position_); for ( ; line != message_lines_.end() ; ++line) { num_lines++; pageOut = *line + '\n' + pageOut; if (num_lines >= max_visible_lines) break; } } void OgreOverlay::Display(const std::string &page) { checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*>(console_overlay_.get())->Display(page); } bool OgreOverlay::AddCharacter(unsigned int character, std::string &lineOut, size_t offset) { assert (offset >= 0 && offset <= lineOut.size()); if (character != 0) { // validate characters. Might no be strictly necessary. static const char legalchars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890+!\"#$'<>|%&/()=?[]{}\\*-_.:,; "; int c; for (c = 0 ; c<sizeof(legalchars) - 1 ; ++c) { if (legalchars[c] == character) { std::string s_char; s_char += character; lineOut.insert(lineOut.size() - offset, std::string(s_char)); return true; } } } return false; } } <commit_msg>Added support for 'delete' key in ogre debug console.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include <OISKeyboard.h> #include "OgreOverlay.h" #include "EC_OgreConsoleOverlay.h" #include "OgreRenderingModule.h" #include "InputEvents.h" #include "ConsoleModule.h" #include "ConsoleManager.h" #include "CommandManager.h" namespace Console { class LogListener : public Foundation::LogListenerInterface { LogListener(); OgreOverlay *console_; public: LogListener(OgreOverlay *console) : Foundation::LogListenerInterface(), console_(console) {} virtual ~LogListener() {} virtual void LogMessage(const std::string &message) { console_->Print(message); } }; ///////////////////////////////////////////// OgreOverlay::OgreOverlay(Foundation::ModuleInterface *module) : Console::ConsoleServiceInterface() , module_(module) , log_listener_(LogListenerPtr(new LogListener(this))) , max_lines_(256) , max_visible_lines(1) , text_position_(0) , prompt_timer_(0) , update_(false) , scroll_line_size_(20) , cursor_offset_(0) { Foundation::Framework *framework = module_->GetFramework(); cursor_blink_freq_ = framework->GetDefaultConfig().DeclareSetting("DebugConsole", "cursor_blink_frequency", 0.5f); if ( framework->GetModuleManager()->HasModule(Foundation::Module::MT_Renderer) ) { OgreRenderer::OgreRenderingModule *rendering_module = framework->GetModuleManager()->GetModule<OgreRenderer::OgreRenderingModule>(Foundation::Module::MT_Renderer); if (rendering_module) rendering_module->GetRenderer()->SubscribeLogListener(log_listener_); } } OgreOverlay::~OgreOverlay() { Foundation::Framework *framework = module_->GetFramework(); console_overlay_.reset(); if ( framework->GetServiceManager()->IsRegistered(Foundation::Service::ST_SceneManager)) { Foundation::SceneManagerServiceInterface *scene_manager = framework->GetService<Foundation::SceneManagerServiceInterface>(Foundation::Service::ST_SceneManager); if (scene_manager->HasScene("Console")) { scene_manager->DeleteScene("Console"); } } if ( framework->GetModuleManager()->HasModule(Foundation::Module::MT_Renderer) ) { OgreRenderer::OgreRenderingModule *rendering_module = framework->GetModuleManager()->GetModule<OgreRenderer::OgreRenderingModule>(Foundation::Module::MT_Renderer); if (rendering_module) rendering_module->GetRenderer()->UnsubscribeLogListener(log_listener_); } } void OgreOverlay::Create() { Foundation::Framework *framework = module_->GetFramework(); if ( framework->GetServiceManager()->IsRegistered(Foundation::Service::ST_SceneManager) && framework->GetComponentManager()->CanCreate("EC_OgreConsoleOverlay") ) { Foundation::SceneManagerServiceInterface *scene_manager = framework->GetService<Foundation::SceneManagerServiceInterface>(Foundation::Service::ST_SceneManager); if (scene_manager->HasScene("Console")) throw Core::Exception("Scene for console already exists."); Foundation::ScenePtr scene = scene_manager->CreateScene("Console"); Foundation::EntityPtr entity = scene->CreateEntity(scene->GetNextFreeId()); console_overlay_ = framework->GetComponentManager()->CreateComponent("EC_OgreConsoleOverlay"); entity->AddEntityComponent(console_overlay_); max_visible_lines = checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->GetMaxVisibleLines(); update_ = true; } ConsolePtr manager = checked_static_cast<ConsoleModule*>(module_)->GetConsole(); command_manager_ = checked_static_cast<ConsoleManager*>(manager.get())->GetCommandManager(); } // virtual void OgreOverlay::Print(const std::string &text) { { Core::MutexLock lock(mutex_); message_lines_.push_front(text); if (message_lines_.size() >= max_lines_) message_lines_.pop_back(); update_ = true; } } // virtual void OgreOverlay::Scroll(int rel) { { Core::MutexLock lock(mutex_); int lines = rel / scroll_line_size_; if (static_cast<int>(text_position_) + lines < 0) lines = -(lines - (lines - static_cast<int>(text_position_))); if (text_position_ + lines > message_lines_.size() - max_visible_lines - 1) lines -= (lines - ((message_lines_.size() - max_visible_lines - 1) - text_position_)); text_position_ += lines; update_ = true; } } void OgreOverlay::SetVisible(bool visible) { if (console_overlay_) { checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->SetVisible(visible); } if (visible) { update_ = true; } } bool OgreOverlay::IsVisible() const { if (console_overlay_) { return checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->IsVisible(); } return false; } bool OgreOverlay::IsActive() const { if (console_overlay_) { return checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->IsActive(); } return false; } void OgreOverlay::Update(Core::f64 frametime) { checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*> (console_overlay_.get())->Update(frametime); bool update = false; { Core::MutexLock lock(mutex_); update = update_; } // blink prompt cursor static bool show_cursor = false; prompt_timer_ += frametime; if (prompt_timer_ > cursor_blink_freq_) { show_cursor = !show_cursor; prompt_timer_ = 0.f; update = true; } if (update) { std::string page; FormatPage(page); std::string prompt; size_t cursor_offset; { Core::MutexLock lock(mutex_); prompt = command_line_; cursor_offset = cursor_offset_; update_ = false; } // add cursor if (show_cursor) prompt.insert(prompt.size() - cursor_offset, "_"); else if (cursor_offset > 0) prompt.insert(prompt.size() - cursor_offset, " "); //add the prompt page += ">" + prompt; Display(page); } } bool OgreOverlay::HandleKeyDown(int code, unsigned int text) { bool result = true; switch (code) { case OIS::KC_PGUP: Scroll(scroll_line_size_ * max_visible_lines - 2); break; case OIS::KC_PGDOWN: Scroll(-scroll_line_size_ * max_visible_lines - 2); break; case OIS::KC_UP: Scroll(scroll_line_size_); break; case OIS::KC_DOWN: Scroll(-scroll_line_size_); break; case OIS::KC_BACK: { Core::MutexLock lock(mutex_); if (command_line_.empty() == false && cursor_offset_ < command_line_.length()) { command_line_ = command_line_.substr(0, command_line_.length() - cursor_offset_ - 1) + command_line_.substr(command_line_.length() - cursor_offset_, cursor_offset_); } break; } case OIS::KC_DELETE: { Core::MutexLock lock(mutex_); if (command_line_.empty() == false && cursor_offset_ != 0) { command_line_ = command_line_.substr(0, command_line_.length() - cursor_offset_) + command_line_.substr(command_line_.length() - cursor_offset_ + 1, cursor_offset_ - 1); cursor_offset_--; } break; } case OIS::KC_LEFT: MoveCursor(-1); break; case OIS::KC_RIGHT: MoveCursor(1); break; case OIS::KC_RETURN: { std::string command_line; { Core::MutexLock lock(mutex_); command_line = command_line_; command_line_.clear(); text_position_ = 0; cursor_offset_ = 0; } if (command_manager_) command_manager_->QueueCommand(command_line); Print(command_line); } break; default: Core::MutexLock lock(mutex_); result = AddCharacter(text, command_line_, cursor_offset_); break; } if (result) update_ = true; return result; } void OgreOverlay::MoveCursor(int offset) { int offset_neg = -offset; if (offset_neg < 0) { Core::MutexLock lock(mutex_); if (cursor_offset_ >= -offset_neg) cursor_offset_ += offset_neg; } else { Core::MutexLock lock(mutex_); cursor_offset_ = std::min(cursor_offset_ + offset_neg, command_line_.length()); } } void OgreOverlay::FormatPage(std::string &pageOut) { Core::MutexLock lock(mutex_); if (!console_overlay_) return; std::string page; size_t num_lines = 0; Core::StringList::const_iterator line = message_lines_.begin(); assert (message_lines_.size() > text_position_); std::advance(line, text_position_); for ( ; line != message_lines_.end() ; ++line) { num_lines++; pageOut = *line + '\n' + pageOut; if (num_lines >= max_visible_lines) break; } } void OgreOverlay::Display(const std::string &page) { checked_static_cast<OgreRenderer::EC_OgreConsoleOverlay*>(console_overlay_.get())->Display(page); } bool OgreOverlay::AddCharacter(unsigned int character, std::string &lineOut, size_t offset) { assert (offset >= 0 && offset <= lineOut.size()); if (character != 0) { // validate characters. Might no be strictly necessary. static const char legalchars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890+!\"#$'<>|%&/()=?[]{}\\*-_.:,; "; int c; for (c = 0 ; c<sizeof(legalchars) - 1 ; ++c) { if (legalchars[c] == character) { std::string s_char; s_char += character; lineOut.insert(lineOut.size() - offset, std::string(s_char)); return true; } } } return false; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: menumanager.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2003-06-10 09:09:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ #define __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ /** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble with solaris headers ... */ #include <vector> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_ACCEL_HXX #include <vcl/accel.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif #define REFERENCE ::com::sun::star::uno::Reference #define XFRAME ::com::sun::star::frame::XFrame #define XDISPATCH ::com::sun::star::frame::XDispatch #define XDISPATCHPROVIDER ::com::sun::star::frame::XDispatchProvider #define XSTATUSLISTENER ::com::sun::star::frame::XStatusListener #define XEVENTLISTENER ::com::sun::star::lang::XEventListener #define FEATURSTATEEVENT ::com::sun::star::frame::FeatureStateEvent #define RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException #define EVENTOBJECT ::com::sun::star::lang::EventObject namespace framework { class BmkMenu; class AddonMenu; class AddonPopupMenu; class MenuManager : public XSTATUSLISTENER , public ThreadHelpBase , public ::cppu::OWeakObject { public: MenuManager( REFERENCE< XFRAME >& rFrame, Menu* pMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( REFERENCE< XFRAME >& rFrame, BmkMenu* pBmkMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( REFERENCE< XFRAME >& rFrame, AddonMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( REFERENCE< XFRAME >& rFrame, AddonPopupMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); virtual ~MenuManager(); // XInterface virtual void SAL_CALL acquire() throw() { OWeakObject::acquire(); } virtual void SAL_CALL release() throw() { OWeakObject::release(); } virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( RUNTIMEEXCEPTION ); // XStatusListener virtual void SAL_CALL statusChanged( const FEATURSTATEEVENT& Event ) throw ( RUNTIMEEXCEPTION ); // XEventListener virtual void SAL_CALL disposing( const EVENTOBJECT& Source ) throw ( RUNTIMEEXCEPTION ); DECL_LINK( Select, Menu * ); Menu* GetMenu() const { return m_pVCLMenu; } void RemoveListener(); protected: DECL_LINK( Highlight, Menu * ); DECL_LINK( Activate, Menu * ); DECL_LINK( Deactivate, Menu * ); private: void UpdateSpecialFileMenu( Menu* pMenu ); void UpdateSpecialWindowMenu( Menu* pMenu ); struct MenuItemHandler { MenuItemHandler( USHORT aItemId, MenuManager* pManager, REFERENCE< XDISPATCH >& rDispatch ) : nItemId( aItemId ), pSubMenuManager( pManager ), xMenuItemDispatch( rDispatch ) {} USHORT nItemId; ::rtl::OUString aTargetFrame; ::rtl::OUString aMenuItemURL; ::rtl::OUString aFilter; ::rtl::OUString aPassword; ::rtl::OUString aTitle; MenuManager* pSubMenuManager; REFERENCE< XDISPATCH > xMenuItemDispatch; }; void CreatePicklistArguments( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList, const MenuItemHandler* ); MenuItemHandler* GetMenuItemHandler( USHORT nItemId ); sal_Bool m_bInitialized; sal_Bool m_bDeleteMenu; sal_Bool m_bDeleteChildren; sal_Bool m_bActive; sal_Bool m_bIsBookmarkMenu; sal_Bool m_bWasHiContrast; sal_Bool m_bShowMenuImages; ::rtl::OUString m_aMenuItemCommand; Menu* m_pVCLMenu; REFERENCE< XFRAME > m_xFrame; ::std::vector< MenuItemHandler* > m_aMenuItemHandlerVector; }; } // namespace #endif <commit_msg>INTEGRATION: CWS binfilter (1.14.46); FILE MERGED 2004/04/19 09:46:20 aw 1.14.46.3: #110098# Necessary adaptions to framework after resynching binfilter to SRC680m33 2003/08/08 10:18:14 aw 1.14.46.2: RESYNC: (1.14-1.15); FILE MERGED 2003/07/18 12:22:41 aw 1.14.46.1: #110897# See the task. All changes to avoid usage of getProcessServiceManager().<commit_after>/************************************************************************* * * $RCSfile: menumanager.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: rt $ $Date: 2004-05-03 13:16:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ #define __FRAMEWORK_CLASSES_MENUMANAGER_HXX_ /** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble with solaris headers ... */ #include <vector> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_FEATURESTATEEVENT_HPP_ #include <com/sun/star/frame/FeatureStateEvent.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _SV_MENU_HXX #include <vcl/menu.hxx> #endif #ifndef _SV_ACCEL_HXX #include <vcl/accel.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_HXX_ #include <macros/debug.hxx> #endif // #110897# #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #define REFERENCE ::com::sun::star::uno::Reference #define XFRAME ::com::sun::star::frame::XFrame #define XDISPATCH ::com::sun::star::frame::XDispatch #define XDISPATCHPROVIDER ::com::sun::star::frame::XDispatchProvider #define XSTATUSLISTENER ::com::sun::star::frame::XStatusListener #define XEVENTLISTENER ::com::sun::star::lang::XEventListener #define FEATURSTATEEVENT ::com::sun::star::frame::FeatureStateEvent #define RUNTIMEEXCEPTION ::com::sun::star::uno::RuntimeException #define EVENTOBJECT ::com::sun::star::lang::EventObject namespace framework { class BmkMenu; class AddonMenu; class AddonPopupMenu; class MenuManager : public XSTATUSLISTENER , public ThreadHelpBase , public ::cppu::OWeakObject { public: // #110897# MenuManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, REFERENCE< XFRAME >& rFrame, Menu* pMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, REFERENCE< XFRAME >& rFrame, BmkMenu* pBmkMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, REFERENCE< XFRAME >& rFrame, AddonMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); MenuManager( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, REFERENCE< XFRAME >& rFrame, AddonPopupMenu* pAddonMenu, sal_Bool bDelete, sal_Bool bDeleteChildren ); virtual ~MenuManager(); // XInterface virtual void SAL_CALL acquire() throw() { OWeakObject::acquire(); } virtual void SAL_CALL release() throw() { OWeakObject::release(); } virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( RUNTIMEEXCEPTION ); // XStatusListener virtual void SAL_CALL statusChanged( const FEATURSTATEEVENT& Event ) throw ( RUNTIMEEXCEPTION ); // XEventListener virtual void SAL_CALL disposing( const EVENTOBJECT& Source ) throw ( RUNTIMEEXCEPTION ); DECL_LINK( Select, Menu * ); Menu* GetMenu() const { return m_pVCLMenu; } void RemoveListener(); // #110897# const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory(); protected: DECL_LINK( Highlight, Menu * ); DECL_LINK( Activate, Menu * ); DECL_LINK( Deactivate, Menu * ); private: void UpdateSpecialFileMenu( Menu* pMenu ); void UpdateSpecialWindowMenu( Menu* pMenu ); struct MenuItemHandler { MenuItemHandler( USHORT aItemId, MenuManager* pManager, REFERENCE< XDISPATCH >& rDispatch ) : nItemId( aItemId ), pSubMenuManager( pManager ), xMenuItemDispatch( rDispatch ) {} USHORT nItemId; ::rtl::OUString aTargetFrame; ::rtl::OUString aMenuItemURL; ::rtl::OUString aFilter; ::rtl::OUString aPassword; ::rtl::OUString aTitle; MenuManager* pSubMenuManager; REFERENCE< XDISPATCH > xMenuItemDispatch; }; void CreatePicklistArguments( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgsList, const MenuItemHandler* ); MenuItemHandler* GetMenuItemHandler( USHORT nItemId ); sal_Bool m_bInitialized; sal_Bool m_bDeleteMenu; sal_Bool m_bDeleteChildren; sal_Bool m_bActive; sal_Bool m_bIsBookmarkMenu; sal_Bool m_bWasHiContrast; sal_Bool m_bShowMenuImages; ::rtl::OUString m_aMenuItemCommand; Menu* m_pVCLMenu; REFERENCE< XFRAME > m_xFrame; ::std::vector< MenuItemHandler* > m_aMenuItemHandlerVector; // #110897# const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& mxServiceFactory; }; } // namespace #endif <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) class Solution { public: /** * @param source: A string * @param target: A string * @return: A string denote the minimum window * Return "" if there is no such a string */ string minWindow(string &source, string &target) { if (source.empty() || source.length() < target.length()) { return ""; } const int ASCII_MAX = 256; vector<int> expCnt(ASCII_MAX, 0); vector<int> curCnt(ASCII_MAX, 0); int cnt = 0; int start = 0; int min_width = INT_MAX; int min_start = 0; for (const auto& c : T) { ++expCnt[c]; } for (int i = 0; i < source.length(); ++i) { if (expCnt[S[i]] > 0) { ++curCnt[S[i]]; if (curCnt[S[i]] <= expCnt[S[i]]) { // Counting expected elements. ++cnt; } } if (cnt == target.size()) { // If window meets the requirement. while (expCnt[S[start]] == 0 || // Adjust left bound of window. curCnt[S[start]] > expCnt[S[start]]) { --curCnt[S[start]]; ++start; } if (min_width > i - start + 1) { // Update minimum window. min_width = i - start + 1; min_start = start; } } } if (min_width == INT_MAX) { return ""; } return source.substr(min_start, min_width); } }; <commit_msg>Update minimum-window-substring.cpp<commit_after>// Time: O(n) // Space: O(1) class Solution { public: /** * @param source: A string * @param target: A string * @return: A string denote the minimum window * Return "" if there is no such a string */ string minWindow(string &source, string &target) { if (source.empty() || source.length() < target.length()) { return ""; } const int ASCII_MAX = 256; vector<int> expCnt(ASCII_MAX, 0); vector<int> curCnt(ASCII_MAX, 0); int cnt = 0; int start = 0; int min_width = INT_MAX; int min_start = 0; for (const auto& c : T) { ++expCnt[c]; } for (int i = 0; i < source.length(); ++i) { if (expCnt[S[i]] > 0) { ++curCnt[S[i]]; if (curCnt[S[i]] <= expCnt[S[i]]) { // Counting expected elements. ++cnt; } } if (cnt == target.size()) { // If window meets the requirement. while (expCnt[S[start]] == 0 || // Adjust left bound of window. curCnt[S[start]] > expCnt[S[start]]) { --curCnt[S[start]]; ++start; } if (min_width > i - start + 1) { // Update minimum window. min_width = i - start + 1; min_start = start; } } } if (min_width == INT_MAX) { return ""; } return source.substr(min_start, min_width); } }; <|endoftext|>
<commit_before>#include "framework/serialization/serialize.h" #include "dependencies/pugixml/src/pugixml.hpp" #include "framework/filesystem.h" #include "framework/logger.h" #include "framework/serialization/providers/filedataprovider.h" #include "framework/serialization/providers/providerwithchecksum.h" #include "framework/serialization/providers/zipdataprovider.h" #include "framework/trace.h" #include "library/sp.h" #include "library/strings.h" #include "library/strings_format.h" #include <map> #include <sstream> namespace OpenApoc { SerializationNode *SerializationNode::getNodeReq(const char *name) { auto node = this->getNodeOpt(name); if (!node) { throw SerializationException(format("Missing node \"%s\"", name), this); } return node; } SerializationNode *SerializationNode::getSectionReq(const char *name) { auto node = this->getSectionOpt(name); if (!node) { throw SerializationException(format("Missing section \"%s\"", name), this); } return node; } SerializationNode *SerializationNode::getNextSiblingReq(const char *name) { auto node = this->getNextSiblingOpt(name); if (!node) { throw SerializationException(format("Missing sibling of \"%s\"", name), this); } return node; } using namespace pugi; class XMLSerializationNode; class XMLSerializationArchive final : public SerializationArchive { private: up<SerializationDataProvider> dataProvider; std::map<UString, xml_document> docRoots; std::vector<up<SerializationNode>> nodes; friend class SerializationArchive; friend class XMLSerializationNode; public: SerializationNode *newRoot(const UString &prefix, const char *name) override; SerializationNode *getRoot(const UString &prefix, const char *name) override; bool write(const UString &path, bool pack, bool pretty) override; XMLSerializationArchive() : dataProvider(nullptr), docRoots(){}; XMLSerializationArchive(up<SerializationDataProvider> dataProvider) : dataProvider(std::move(dataProvider)){}; ~XMLSerializationArchive() override = default; }; class XMLSerializationNode final : public SerializationNode { private: SerializationDataProvider *dataProvider; XMLSerializationArchive *archive; xml_node node; XMLSerializationNode *parent; UString prefix; public: XMLSerializationNode(XMLSerializationArchive *archive, xml_node node, XMLSerializationNode *parent) : archive(archive), node(node), parent(parent) { } XMLSerializationNode(XMLSerializationArchive *archive, xml_node node, const UString &prefix) : archive(archive), node(node), parent(nullptr), prefix(prefix) { } SerializationNode *addNode(const char *name, const UString &value = "") override; SerializationNode *addSection(const char *name) override; SerializationNode *getNodeOpt(const char *name) override; SerializationNode *getNextSiblingOpt(const char *name) override; SerializationNode *getSectionOpt(const char *name) override; UString getName() override; void setName(const UString &str) override; UString getValue() override; void setValue(const UString &str) override; unsigned int getValueUInt() override; void setValueUInt(unsigned int i) override; unsigned char getValueUChar() override; void setValueUChar(unsigned char i) override; int getValueInt() override; void setValueInt(int i) override; unsigned long long getValueUInt64() override; void setValueUInt64(unsigned long long i) override; long long getValueInt64() override; void setValueInt64(long long i) override; float getValueFloat() override; void setValueFloat(float f) override; bool getValueBool() override; void setValueBool(bool b) override; std::vector<bool> getValueBoolVector() override; void setValueBoolVector(const std::vector<bool> &vec) override; UString getFullPath() override; const UString &getPrefix() const override { if (this->parent) return this->parent->getPrefix(); else return this->prefix; } ~XMLSerializationNode() override = default; }; up<SerializationArchive> SerializationArchive::createArchive() { return mkup<XMLSerializationArchive>(); } up<SerializationDataProvider> getProvider(bool pack) { if (!pack) { // directory loader return mkup<ProviderWithChecksum>(mkup<FileDataProvider>()); } else { // zip loader return mkup<ProviderWithChecksum>(mkup<ZipDataProvider>()); } } up<SerializationArchive> SerializationArchive::readArchive(const UString &path) { up<SerializationDataProvider> dataProvider = getProvider(!fs::is_directory(path.str())); if (!dataProvider->openArchive(path, false)) { LogWarning("Failed to open archive at \"%s\"", path); return nullptr; } LogInfo("Opened archive \"%s\"", path); return mkup<XMLSerializationArchive>(std::move(dataProvider)); } SerializationNode *XMLSerializationArchive::newRoot(const UString &prefix, const char *name) { auto path = prefix + name + ".xml"; auto root = this->docRoots[path].root().append_child(); auto decl = this->docRoots[path].prepend_child(pugi::node_declaration); decl.append_attribute("version") = "1.0"; decl.append_attribute("encoding") = "UTF-8"; root.set_name(name); this->nodes.push_back(mkup<XMLSerializationNode>(this, root, prefix + name + "/")); return this->nodes.back().get(); } SerializationNode *XMLSerializationArchive::getRoot(const UString &prefix, const char *name) { auto path = prefix + name + ".xml"; if (dataProvider == nullptr) { LogWarning("Reading from not opened archive: %s!", path); return nullptr; } auto it = this->docRoots.find(path); if (it == this->docRoots.end()) { TraceObj trace("Reading archive", {{"path", path}}); UString content; if (dataProvider->readDocument(path, content)) { // FIXME: Make this actually read from the root and load the xinclude tags properly? auto &doc = this->docRoots[path]; TraceObj traceParse("Parsing archive", {{"path", path}}); auto parse_result = doc.load_string(content.cStr()); if (!parse_result) { LogInfo("Failed to parse \"%s\" : \"%s\" at \"%llu\"", path, parse_result.description(), (unsigned long long)parse_result.offset); return nullptr; } it = this->docRoots.find(path); LogInfo("Parsed \"%s\"", path); } } if (it == this->docRoots.end()) { return nullptr; } auto root = it->second.child(name); if (!root) { LogWarning("Failed to find root with name \"%s\" in \"%s\"", name, path); return nullptr; } this->nodes.push_back(mkup<XMLSerializationNode>(this, root, prefix + name + "/")); return this->nodes.back().get(); } bool XMLSerializationArchive::write(const UString &path, bool pack, bool pretty) { TraceObj trace("Writing archive", {{"path", path}}); // warning! data provider must be freed when this method ends, // so code calling this method may override archive auto dataProvider = getProvider(pack); if (!dataProvider->openArchive(path, true)) { LogWarning("Failed to open archive at \"%s\"", path); return false; } for (auto &root : this->docRoots) { TraceObj traceSave("Saving root", {{"root", root.first}}); std::stringstream ss; unsigned int flags = pugi::format_default; if (pretty == false) { flags = pugi::format_raw; } root.second.save(ss, "", flags); TraceObj traceSaveData("Saving root data", {{"root", root.first}}); if (!dataProvider->saveDocument(root.first, ss.str())) { return false; } } return dataProvider->finalizeSave(); } SerializationNode *XMLSerializationNode::addNode(const char *name, const UString &value) { auto newNode = this->node.append_child(); newNode.set_name(name); newNode.text().set(value.cStr()); this->archive->nodes.push_back(mkup<XMLSerializationNode>(this->archive, newNode, this)); return this->archive->nodes.back().get(); } SerializationNode *XMLSerializationNode::getNodeOpt(const char *name) { auto newNode = this->node.child(name); if (!newNode) { return nullptr; } this->archive->nodes.push_back(mkup<XMLSerializationNode>(this->archive, newNode, this)); return this->archive->nodes.back().get(); } SerializationNode *XMLSerializationNode::getNextSiblingOpt(const char *name) { auto newNode = this->node.next_sibling(name); if (!newNode) { return nullptr; } this->archive->nodes.push_back(mkup<XMLSerializationNode>(this->archive, newNode, this)); return this->archive->nodes.back().get(); } SerializationNode *XMLSerializationNode::addSection(const char *name) { auto includeNode = static_cast<XMLSerializationNode *>(this->addNode("xi:include")); auto path = UString(name) + ".xml"; auto nsAttribute = includeNode->node.append_attribute("xmlns:xi"); nsAttribute.set_value("http://www.w3.org/2001/XInclude"); auto attribute = includeNode->node.append_attribute("href"); attribute.set_value(path.cStr()); return this->archive->newRoot(this->getPrefix(), name); } SerializationNode *XMLSerializationNode::getSectionOpt(const char *name) { return archive->getRoot(this->getPrefix(), name); } UString XMLSerializationNode::getName() { return node.name(); } void XMLSerializationNode::setName(const UString &str) { node.set_name(str.cStr()); } UString XMLSerializationNode::getValue() { return node.text().get(); } void XMLSerializationNode::setValue(const UString &str) { node.text().set(str.cStr()); } unsigned int XMLSerializationNode::getValueUInt() { return node.text().as_uint(); } void XMLSerializationNode::setValueUInt(unsigned int i) { node.text().set(i); } unsigned char XMLSerializationNode::getValueUChar() { auto uint = node.text().as_uint(); if (uint > std::numeric_limits<unsigned char>::max()) { throw SerializationException(format("Value %u is out of range of unsigned char type", uint), this); } return static_cast<unsigned char>(uint); } void XMLSerializationNode::setValueUChar(unsigned char c) { node.text().set((unsigned int)c); } int XMLSerializationNode::getValueInt() { return node.text().as_int(); } void XMLSerializationNode::setValueInt(int i) { node.text().set(i); } unsigned long long XMLSerializationNode::getValueUInt64() { return node.text().as_ullong(); } void XMLSerializationNode::setValueUInt64(unsigned long long i) { node.text().set(i); } long long XMLSerializationNode::getValueInt64() { return node.text().as_llong(); } void XMLSerializationNode::setValueInt64(long long i) { node.text().set(i); } float XMLSerializationNode::getValueFloat() { return node.text().as_float(); } void XMLSerializationNode::setValueFloat(float f) { node.text().set(f); } bool XMLSerializationNode::getValueBool() { return node.text().as_bool(); } void XMLSerializationNode::setValueBool(bool b) { node.text().set(b); } std::vector<bool> XMLSerializationNode::getValueBoolVector() { std::vector<bool> vec; auto string = this->getValue().str(); vec.resize(string.length()); for (size_t i = 0; i < string.length(); i++) { auto c = string[i]; if (c == '1') vec[i] = true; else if (c == '0') vec[i] = false; else throw SerializationException(format("Unknown char '%c' in bool vector", c), this); } return vec; } void XMLSerializationNode::setValueBoolVector(const std::vector<bool> &vec) { std::string str(vec.size(), ' '); for (size_t i = 0; i < vec.size(); i++) { auto b = vec[i]; if (b) str[i] = '1'; else str[i] = '0'; } this->setValue(str); } UString XMLSerializationNode::getFullPath() { UString str; if (this->parent) { str = this->parent->getFullPath(); } else { str += node.name(); str += ".xml:"; } str += "/"; str += node.name(); return str; } } // namespace OpenApoc <commit_msg>Store XMLSerializationNodes in a deque instead a vector<up<>><commit_after>#include "framework/serialization/serialize.h" #include "dependencies/pugixml/src/pugixml.hpp" #include "framework/filesystem.h" #include "framework/logger.h" #include "framework/serialization/providers/filedataprovider.h" #include "framework/serialization/providers/providerwithchecksum.h" #include "framework/serialization/providers/zipdataprovider.h" #include "framework/trace.h" #include "library/sp.h" #include "library/strings.h" #include "library/strings_format.h" #include <deque> #include <map> #include <sstream> namespace OpenApoc { SerializationNode *SerializationNode::getNodeReq(const char *name) { auto node = this->getNodeOpt(name); if (!node) { throw SerializationException(format("Missing node \"%s\"", name), this); } return node; } SerializationNode *SerializationNode::getSectionReq(const char *name) { auto node = this->getSectionOpt(name); if (!node) { throw SerializationException(format("Missing section \"%s\"", name), this); } return node; } SerializationNode *SerializationNode::getNextSiblingReq(const char *name) { auto node = this->getNextSiblingOpt(name); if (!node) { throw SerializationException(format("Missing sibling of \"%s\"", name), this); } return node; } using namespace pugi; class XMLSerializationArchive; class XMLSerializationNode final : public SerializationNode { private: SerializationDataProvider *dataProvider; XMLSerializationArchive *archive; xml_node node; XMLSerializationNode *parent; UString prefix; public: XMLSerializationNode(XMLSerializationArchive *archive, xml_node node, XMLSerializationNode *parent) : archive(archive), node(node), parent(parent) { } XMLSerializationNode(XMLSerializationArchive *archive, xml_node node, const UString &prefix) : archive(archive), node(node), parent(nullptr), prefix(prefix) { } SerializationNode *addNode(const char *name, const UString &value = "") override; SerializationNode *addSection(const char *name) override; SerializationNode *getNodeOpt(const char *name) override; SerializationNode *getNextSiblingOpt(const char *name) override; SerializationNode *getSectionOpt(const char *name) override; UString getName() override; void setName(const UString &str) override; UString getValue() override; void setValue(const UString &str) override; unsigned int getValueUInt() override; void setValueUInt(unsigned int i) override; unsigned char getValueUChar() override; void setValueUChar(unsigned char i) override; int getValueInt() override; void setValueInt(int i) override; unsigned long long getValueUInt64() override; void setValueUInt64(unsigned long long i) override; long long getValueInt64() override; void setValueInt64(long long i) override; float getValueFloat() override; void setValueFloat(float f) override; bool getValueBool() override; void setValueBool(bool b) override; std::vector<bool> getValueBoolVector() override; void setValueBoolVector(const std::vector<bool> &vec) override; UString getFullPath() override; const UString &getPrefix() const override { if (this->parent) return this->parent->getPrefix(); else return this->prefix; } ~XMLSerializationNode() override = default; }; class XMLSerializationArchive final : public SerializationArchive { private: up<SerializationDataProvider> dataProvider; std::map<UString, xml_document> docRoots; std::deque<XMLSerializationNode> nodes; friend class SerializationArchive; friend class XMLSerializationNode; public: SerializationNode *newRoot(const UString &prefix, const char *name) override; SerializationNode *getRoot(const UString &prefix, const char *name) override; bool write(const UString &path, bool pack, bool pretty) override; XMLSerializationArchive() : dataProvider(nullptr), docRoots(){}; XMLSerializationArchive(up<SerializationDataProvider> dataProvider) : dataProvider(std::move(dataProvider)){}; ~XMLSerializationArchive() override = default; }; up<SerializationArchive> SerializationArchive::createArchive() { return mkup<XMLSerializationArchive>(); } up<SerializationDataProvider> getProvider(bool pack) { if (!pack) { // directory loader return mkup<ProviderWithChecksum>(mkup<FileDataProvider>()); } else { // zip loader return mkup<ProviderWithChecksum>(mkup<ZipDataProvider>()); } } up<SerializationArchive> SerializationArchive::readArchive(const UString &path) { up<SerializationDataProvider> dataProvider = getProvider(!fs::is_directory(path.str())); if (!dataProvider->openArchive(path, false)) { LogWarning("Failed to open archive at \"%s\"", path); return nullptr; } LogInfo("Opened archive \"%s\"", path); return mkup<XMLSerializationArchive>(std::move(dataProvider)); } SerializationNode *XMLSerializationArchive::newRoot(const UString &prefix, const char *name) { auto path = prefix + name + ".xml"; auto root = this->docRoots[path].root().append_child(); auto decl = this->docRoots[path].prepend_child(pugi::node_declaration); decl.append_attribute("version") = "1.0"; decl.append_attribute("encoding") = "UTF-8"; root.set_name(name); return &this->nodes.emplace_back(this, root, prefix + name + "/"); } SerializationNode *XMLSerializationArchive::getRoot(const UString &prefix, const char *name) { auto path = prefix + name + ".xml"; if (dataProvider == nullptr) { LogWarning("Reading from not opened archive: %s!", path); return nullptr; } auto it = this->docRoots.find(path); if (it == this->docRoots.end()) { TraceObj trace("Reading archive", {{"path", path}}); UString content; if (dataProvider->readDocument(path, content)) { // FIXME: Make this actually read from the root and load the xinclude tags properly? auto &doc = this->docRoots[path]; TraceObj traceParse("Parsing archive", {{"path", path}}); auto parse_result = doc.load_string(content.cStr()); if (!parse_result) { LogInfo("Failed to parse \"%s\" : \"%s\" at \"%llu\"", path, parse_result.description(), (unsigned long long)parse_result.offset); return nullptr; } it = this->docRoots.find(path); LogInfo("Parsed \"%s\"", path); } } if (it == this->docRoots.end()) { return nullptr; } auto root = it->second.child(name); if (!root) { LogWarning("Failed to find root with name \"%s\" in \"%s\"", name, path); return nullptr; } return &this->nodes.emplace_back(this, root, prefix + name + "/"); } bool XMLSerializationArchive::write(const UString &path, bool pack, bool pretty) { TraceObj trace("Writing archive", {{"path", path}}); // warning! data provider must be freed when this method ends, // so code calling this method may override archive auto dataProvider = getProvider(pack); if (!dataProvider->openArchive(path, true)) { LogWarning("Failed to open archive at \"%s\"", path); return false; } for (auto &root : this->docRoots) { TraceObj traceSave("Saving root", {{"root", root.first}}); std::stringstream ss; unsigned int flags = pugi::format_default; if (pretty == false) { flags = pugi::format_raw; } root.second.save(ss, "", flags); TraceObj traceSaveData("Saving root data", {{"root", root.first}}); if (!dataProvider->saveDocument(root.first, ss.str())) { return false; } } return dataProvider->finalizeSave(); } SerializationNode *XMLSerializationNode::addNode(const char *name, const UString &value) { auto newNode = this->node.append_child(); newNode.set_name(name); newNode.text().set(value.cStr()); return &this->archive->nodes.emplace_back(this->archive, newNode, this); } SerializationNode *XMLSerializationNode::getNodeOpt(const char *name) { auto newNode = this->node.child(name); if (!newNode) { return nullptr; } return &this->archive->nodes.emplace_back(this->archive, newNode, this); } SerializationNode *XMLSerializationNode::getNextSiblingOpt(const char *name) { auto newNode = this->node.next_sibling(name); if (!newNode) { return nullptr; } return &this->archive->nodes.emplace_back(this->archive, newNode, this); } SerializationNode *XMLSerializationNode::addSection(const char *name) { auto includeNode = static_cast<XMLSerializationNode *>(this->addNode("xi:include")); auto path = UString(name) + ".xml"; auto nsAttribute = includeNode->node.append_attribute("xmlns:xi"); nsAttribute.set_value("http://www.w3.org/2001/XInclude"); auto attribute = includeNode->node.append_attribute("href"); attribute.set_value(path.cStr()); return this->archive->newRoot(this->getPrefix(), name); } SerializationNode *XMLSerializationNode::getSectionOpt(const char *name) { return archive->getRoot(this->getPrefix(), name); } UString XMLSerializationNode::getName() { return node.name(); } void XMLSerializationNode::setName(const UString &str) { node.set_name(str.cStr()); } UString XMLSerializationNode::getValue() { return node.text().get(); } void XMLSerializationNode::setValue(const UString &str) { node.text().set(str.cStr()); } unsigned int XMLSerializationNode::getValueUInt() { return node.text().as_uint(); } void XMLSerializationNode::setValueUInt(unsigned int i) { node.text().set(i); } unsigned char XMLSerializationNode::getValueUChar() { auto uint = node.text().as_uint(); if (uint > std::numeric_limits<unsigned char>::max()) { throw SerializationException(format("Value %u is out of range of unsigned char type", uint), this); } return static_cast<unsigned char>(uint); } void XMLSerializationNode::setValueUChar(unsigned char c) { node.text().set((unsigned int)c); } int XMLSerializationNode::getValueInt() { return node.text().as_int(); } void XMLSerializationNode::setValueInt(int i) { node.text().set(i); } unsigned long long XMLSerializationNode::getValueUInt64() { return node.text().as_ullong(); } void XMLSerializationNode::setValueUInt64(unsigned long long i) { node.text().set(i); } long long XMLSerializationNode::getValueInt64() { return node.text().as_llong(); } void XMLSerializationNode::setValueInt64(long long i) { node.text().set(i); } float XMLSerializationNode::getValueFloat() { return node.text().as_float(); } void XMLSerializationNode::setValueFloat(float f) { node.text().set(f); } bool XMLSerializationNode::getValueBool() { return node.text().as_bool(); } void XMLSerializationNode::setValueBool(bool b) { node.text().set(b); } std::vector<bool> XMLSerializationNode::getValueBoolVector() { std::vector<bool> vec; auto string = this->getValue().str(); vec.resize(string.length()); for (size_t i = 0; i < string.length(); i++) { auto c = string[i]; if (c == '1') vec[i] = true; else if (c == '0') vec[i] = false; else throw SerializationException(format("Unknown char '%c' in bool vector", c), this); } return vec; } void XMLSerializationNode::setValueBoolVector(const std::vector<bool> &vec) { std::string str(vec.size(), ' '); for (size_t i = 0; i < vec.size(); i++) { auto b = vec[i]; if (b) str[i] = '1'; else str[i] = '0'; } this->setValue(str); } UString XMLSerializationNode::getFullPath() { UString str; if (this->parent) { str = this->parent->getFullPath(); } else { str += node.name(); str += ".xml:"; } str += "/"; str += node.name(); return str; } } // namespace OpenApoc <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_CORE_BEHAVIOR_MASS_INL #define SOFA_CORE_BEHAVIOR_MASS_INL #include <sofa/core/behavior/Mass.h> #include <sofa/core/behavior/BaseConstraint.h> #include <sofa/core/behavior/ForceField.inl> #include <sofa/defaulttype/DataTypeInfo.h> namespace sofa { namespace core { namespace behavior { template<class DataTypes> Mass<DataTypes>::Mass(MechanicalState<DataTypes> *mm) : ForceField<DataTypes>(mm) , m_gnuplotFileEnergy(NULL) { } template<class DataTypes> Mass<DataTypes>::~Mass() { } template<class DataTypes> void Mass<DataTypes>::init() { ForceField<DataTypes>::init(); } #ifdef SOFA_SMP template<class DataTypes> struct ParallelMassAccFromF { void operator()( const MechanicalParams* mparams /* PARAMS FIRST */, Mass< DataTypes >*m,Shared_rw< objectmodel::Data< typename DataTypes::VecDeriv> > _a,Shared_r< objectmodel::Data< typename DataTypes::VecDeriv> > _f) { m->accFromF(mparams /* PARAMS FIRST */, _a.access(),_f.read()); } }; template<class DataTypes> struct ParallelMassAddMDx { public: void operator()(const MechanicalParams* mparams /* PARAMS FIRST */, Mass< DataTypes >*m,Shared_rw< objectmodel::Data< typename DataTypes::VecDeriv> > _res,Shared_r< objectmodel::Data< typename DataTypes::VecDeriv> > _dx,double factor) { m->addMDx(mparams /* PARAMS FIRST */, _res.access(),_dx.read(),factor); } }; // template<class DataTypes> // void Mass<DataTypes>::addMBKv(double mFactor, double bFactor, double kFactor) // { // this->ForceField<DataTypes>::addMBKv(mFactor, bFactor, kFactor); // if (mFactor != 0.0) // { // if (this->mstate) // Task<ParallelMassAddMDx < DataTypes > >(this,**this->mstate->getF(), *this->mstate->read(core::ConstVecCoordId::velocity())->getValue(),mFactor); // } // } #endif /* SOFA_SMP */ template<class DataTypes> void Mass<DataTypes>::addMDx(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId fid, double factor) { if (mparams) { #ifdef SOFA_SMP if (mparams->execMode() == ExecParams::EXEC_KAAPI) Task<ParallelMassAddMDx< DataTypes > >(mparams /* PARAMS FIRST */, this, **defaulttype::getShared(*fid[this->mstate.get(mparams)].write()), **defaulttype::getShared(*mparams->readDx(this->mstate)), factor); else #endif /* SOFA_SMP */ addMDx(mparams /* PARAMS FIRST */, *fid[this->mstate.get(mparams)].write(), *mparams->readDx(this->mstate), factor); } } template<class DataTypes> void Mass<DataTypes>::addMDx(const MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& f, const DataVecDeriv& dx , double factor ) { serr << "ERROR("<<getClassName()<< "): addMDx(const MechanicalParams* , DataVecDeriv& , const DataVecDeriv& , double ) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::accFromF(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId aid) { if(mparams) { #ifdef SOFA_SMP if (mparams->execMode() == ExecParams::EXEC_KAAPI) Task<ParallelMassAccFromF< DataTypes > >(mparams /* PARAMS FIRST */, this, **defaulttype::getShared(*aid[this->mstate.get(mparams)].write()), **defaulttype::getShared(*mparams->readF(this->mstate))); else #endif /* SOFA_SMP */ accFromF(mparams /* PARAMS FIRST */, *aid[this->mstate.get(mparams)].write(), *mparams->readF(this->mstate)); } else serr <<"Mass<DataTypes>::accFromF(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId aid) receives no mparam" << sendl; } template<class DataTypes> void Mass<DataTypes>::accFromF(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecDeriv& /*a*/, const DataVecDeriv& /*f*/) { serr << "ERROR("<<getClassName()<<"): accFromF(const MechanicalParams* , DataVecDeriv& , const DataVecDeriv& ) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::addDForce(const MechanicalParams* #ifndef NDEBUG mparams #endif , DataVecDeriv & /*df*/, const DataVecDeriv & /*dx*/) { #ifndef NDEBUG // @TODO Remove // Hack to disable warning message mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue()); #endif } template<class DataTypes> void Mass<DataTypes>::addMBKdx(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId dfId) { this->ForceField<DataTypes>::addMBKdx(mparams /* PARAMS FIRST */, dfId); if (mparams->mFactorIncludingRayleighDamping(rayleighMass.getValue()) != 0.0) { addMDx(mparams /* PARAMS FIRST */, *dfId[this->mstate.get(mparams)].write(), *mparams->readDx(this->mstate), mparams->mFactorIncludingRayleighDamping(rayleighMass.getValue())); } } template<class DataTypes> double Mass<DataTypes>::getKineticEnergy(const MechanicalParams* /*mparams*/) const { serr << "ERROR("<<getClassName()<<"): getKineticEnergy(const MechanicalParams*) not implemented." << sendl; return 0.0; } template<class DataTypes> double Mass<DataTypes>::getKineticEnergy(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const DataVecDeriv& /*v*/) const { serr << "ERROR("<<getClassName()<<"): getKineticEnergy(const MechanicalParams*, const DataVecDeriv& ) not implemented." << sendl; return 0.0; } template<class DataTypes> double Mass<DataTypes>::getPotentialEnergy(const MechanicalParams*) const { serr << "ERROR("<<getClassName()<<"): getPotentialEnergy( const MechanicalParams* ) not implemented." << sendl; return 0.0; } template<class DataTypes> double Mass<DataTypes>::getPotentialEnergy(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const DataVecCoord& /*x*/) const { serr << "ERROR("<<getClassName()<<"): getPotentialEnergy( const MechanicalParams*, const DataVecCoord& ) not implemented." << sendl; return 0.0; } template<class DataTypes> defaulttype::Vec6d Mass<DataTypes>::getMomentum( const MechanicalParams* mparams ) const { if (this->mstate) return getMomentum(mparams /* PARAMS FIRST */, *mparams->readX(this->mstate), *mparams->readV(this->mstate)); return defaulttype::Vec6d(); } template<class DataTypes> defaulttype::Vec6d Mass<DataTypes>::getMomentum( const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const DataVecCoord& /*x*/, const DataVecDeriv& /*v*/ ) const { serr << "ERROR("<<getClassName()<<"): getMomentum( const MechanicalParams*, const DataVecCoord&, const DataVecDeriv& ) not implemented." << sendl; return defaulttype::Vec6d(); } template<class DataTypes> void Mass<DataTypes>::addKToMatrix(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* /*matrix*/) { serr << "ERROR("<<getClassName()<<"): addKToMatrix(const MechanicalParams*, const sofa::core::behavior::MultiMatrixAccessor*) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::addBToMatrix(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* /*matrix*/) { serr << "ERROR("<<getClassName()<<"): addBToMatrix(const MechanicalParams*, const sofa::core::behavior::MultiMatrixAccessor*) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::addMToMatrix(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* /*matrix*/) { serr << "ERROR("<<getClassName()<<"): addMToMatrix(const MechanicalParams*, const sofa::core::behavior::MultiMatrixAccessor*) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::addMBKToMatrix(const MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix) { this->ForceField<DataTypes>::addMBKToMatrix(mparams /* PARAMS FIRST */, matrix); if (mparams->mFactorIncludingRayleighDamping(rayleighMass.getValue()) != 0.0) addMToMatrix(mparams /* PARAMS FIRST */, matrix); } template<class DataTypes> void Mass<DataTypes>::addSubMBKToMatrix(const MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix, const helper::vector<unsigned> /*subMatrixIndex*/) { addMBKToMatrix(mparams,matrix); // default implementation use full addMFunction } template<class DataTypes> void Mass<DataTypes>::addGravityToV(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId vid) { if(this->mstate) { DataVecDeriv& v = *vid[this->mstate.get(mparams)].write(); addGravityToV(mparams /* PARAMS FIRST */, v); } } template<class DataTypes> void Mass<DataTypes>::initGnuplot(const std::string path) { if (!this->getName().empty()) { if (m_gnuplotFileEnergy != NULL) delete m_gnuplotFileEnergy; m_gnuplotFileEnergy = new std::ofstream( (path+this->getName()+"_Energy.txt").c_str() ); } } template<class DataTypes> void Mass<DataTypes>::exportGnuplot(const MechanicalParams* mparams /* PARAMS FIRST */, double time) { if (m_gnuplotFileEnergy!=NULL) { (*m_gnuplotFileEnergy) << time <<"\t"<< this->getKineticEnergy(mparams) <<"\t"<< this->getPotentialEnergy(mparams) <<"\t"<< this->getPotentialEnergy(mparams) +this->getKineticEnergy(mparams)<< std::endl; } } template <class DataTypes> double Mass<DataTypes>::getElementMass(unsigned int ) const { serr << "ERROR("<<getClassName()<<"): getElementMass with Scalar not implemented" << sendl; return 0.0; } template <class DataTypes> void Mass<DataTypes>::getElementMass(unsigned int , defaulttype::BaseMatrix *m) const { static const defaulttype::BaseMatrix::Index dimension = (defaulttype::BaseMatrix::Index) defaulttype::DataTypeInfo<Coord>::size(); if (m->rowSize() != dimension || m->colSize() != dimension) m->resize(dimension,dimension); m->clear(); serr << "ERROR("<<getClassName()<<"): getElementMass with Matrix not implemented" << sendl; } } // namespace behavior } // namespace core } // namespace sofa #endif <commit_msg>framework: limit the number of errors printed for unimplemented methods<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_CORE_BEHAVIOR_MASS_INL #define SOFA_CORE_BEHAVIOR_MASS_INL #include <sofa/core/behavior/Mass.h> #include <sofa/core/behavior/BaseConstraint.h> #include <sofa/core/behavior/ForceField.inl> #include <sofa/defaulttype/DataTypeInfo.h> namespace sofa { namespace core { namespace behavior { template<class DataTypes> Mass<DataTypes>::Mass(MechanicalState<DataTypes> *mm) : ForceField<DataTypes>(mm) , m_gnuplotFileEnergy(NULL) { } template<class DataTypes> Mass<DataTypes>::~Mass() { } template<class DataTypes> void Mass<DataTypes>::init() { ForceField<DataTypes>::init(); } #ifdef SOFA_SMP template<class DataTypes> struct ParallelMassAccFromF { void operator()( const MechanicalParams* mparams /* PARAMS FIRST */, Mass< DataTypes >*m,Shared_rw< objectmodel::Data< typename DataTypes::VecDeriv> > _a,Shared_r< objectmodel::Data< typename DataTypes::VecDeriv> > _f) { m->accFromF(mparams /* PARAMS FIRST */, _a.access(),_f.read()); } }; template<class DataTypes> struct ParallelMassAddMDx { public: void operator()(const MechanicalParams* mparams /* PARAMS FIRST */, Mass< DataTypes >*m,Shared_rw< objectmodel::Data< typename DataTypes::VecDeriv> > _res,Shared_r< objectmodel::Data< typename DataTypes::VecDeriv> > _dx,double factor) { m->addMDx(mparams /* PARAMS FIRST */, _res.access(),_dx.read(),factor); } }; // template<class DataTypes> // void Mass<DataTypes>::addMBKv(double mFactor, double bFactor, double kFactor) // { // this->ForceField<DataTypes>::addMBKv(mFactor, bFactor, kFactor); // if (mFactor != 0.0) // { // if (this->mstate) // Task<ParallelMassAddMDx < DataTypes > >(this,**this->mstate->getF(), *this->mstate->read(core::ConstVecCoordId::velocity())->getValue(),mFactor); // } // } #endif /* SOFA_SMP */ template<class DataTypes> void Mass<DataTypes>::addMDx(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId fid, double factor) { if (mparams) { #ifdef SOFA_SMP if (mparams->execMode() == ExecParams::EXEC_KAAPI) Task<ParallelMassAddMDx< DataTypes > >(mparams /* PARAMS FIRST */, this, **defaulttype::getShared(*fid[this->mstate.get(mparams)].write()), **defaulttype::getShared(*mparams->readDx(this->mstate)), factor); else #endif /* SOFA_SMP */ addMDx(mparams /* PARAMS FIRST */, *fid[this->mstate.get(mparams)].write(), *mparams->readDx(this->mstate), factor); } } template<class DataTypes> void Mass<DataTypes>::addMDx(const MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& f, const DataVecDeriv& dx , double factor ) { serr << "ERROR("<<getClassName()<< "): addMDx(const MechanicalParams* , DataVecDeriv& , const DataVecDeriv& , double ) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::accFromF(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId aid) { if(mparams) { #ifdef SOFA_SMP if (mparams->execMode() == ExecParams::EXEC_KAAPI) Task<ParallelMassAccFromF< DataTypes > >(mparams /* PARAMS FIRST */, this, **defaulttype::getShared(*aid[this->mstate.get(mparams)].write()), **defaulttype::getShared(*mparams->readF(this->mstate))); else #endif /* SOFA_SMP */ accFromF(mparams /* PARAMS FIRST */, *aid[this->mstate.get(mparams)].write(), *mparams->readF(this->mstate)); } else serr <<"Mass<DataTypes>::accFromF(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId aid) receives no mparam" << sendl; } template<class DataTypes> void Mass<DataTypes>::accFromF(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, DataVecDeriv& /*a*/, const DataVecDeriv& /*f*/) { serr << "ERROR("<<getClassName()<<"): accFromF(const MechanicalParams* , DataVecDeriv& , const DataVecDeriv& ) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::addDForce(const MechanicalParams* #ifndef NDEBUG mparams #endif , DataVecDeriv & /*df*/, const DataVecDeriv & /*dx*/) { #ifndef NDEBUG // @TODO Remove // Hack to disable warning message mparams->kFactorIncludingRayleighDamping(this->rayleighStiffness.getValue()); #endif } template<class DataTypes> void Mass<DataTypes>::addMBKdx(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId dfId) { this->ForceField<DataTypes>::addMBKdx(mparams /* PARAMS FIRST */, dfId); if (mparams->mFactorIncludingRayleighDamping(rayleighMass.getValue()) != 0.0) { addMDx(mparams /* PARAMS FIRST */, *dfId[this->mstate.get(mparams)].write(), *mparams->readDx(this->mstate), mparams->mFactorIncludingRayleighDamping(rayleighMass.getValue())); } } template<class DataTypes> double Mass<DataTypes>::getKineticEnergy(const MechanicalParams* /*mparams*/) const { serr << "ERROR("<<getClassName()<<"): getKineticEnergy(const MechanicalParams*) not implemented." << sendl; return 0.0; } template<class DataTypes> double Mass<DataTypes>::getKineticEnergy(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const DataVecDeriv& /*v*/) const { serr << "ERROR("<<getClassName()<<"): getKineticEnergy(const MechanicalParams*, const DataVecDeriv& ) not implemented." << sendl; return 0.0; } template<class DataTypes> double Mass<DataTypes>::getPotentialEnergy(const MechanicalParams*) const { serr << "ERROR("<<getClassName()<<"): getPotentialEnergy( const MechanicalParams* ) not implemented." << sendl; return 0.0; } template<class DataTypes> double Mass<DataTypes>::getPotentialEnergy(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const DataVecCoord& /*x*/) const { serr << "ERROR("<<getClassName()<<"): getPotentialEnergy( const MechanicalParams*, const DataVecCoord& ) not implemented." << sendl; return 0.0; } template<class DataTypes> defaulttype::Vec6d Mass<DataTypes>::getMomentum( const MechanicalParams* mparams ) const { if (this->mstate) return getMomentum(mparams /* PARAMS FIRST */, *mparams->readX(this->mstate), *mparams->readV(this->mstate)); return defaulttype::Vec6d(); } template<class DataTypes> defaulttype::Vec6d Mass<DataTypes>::getMomentum( const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const DataVecCoord& /*x*/, const DataVecDeriv& /*v*/ ) const { serr << "ERROR("<<getClassName()<<"): getMomentum( const MechanicalParams*, const DataVecCoord&, const DataVecDeriv& ) not implemented." << sendl; return defaulttype::Vec6d(); } template<class DataTypes> void Mass<DataTypes>::addKToMatrix(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* /*matrix*/) { static int i=0; if (i < 10) { serr << "ERROR("<<getClassName()<<"): addKToMatrix(const MechanicalParams*, const sofa::core::behavior::MultiMatrixAccessor*) not implemented." << sendl; i++; } } template<class DataTypes> void Mass<DataTypes>::addBToMatrix(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* /*matrix*/) { static int i=0; if (i < 10) { serr << "ERROR("<<getClassName()<<"): addBToMatrix(const MechanicalParams*, const sofa::core::behavior::MultiMatrixAccessor*) not implemented." << sendl; i++; } } template<class DataTypes> void Mass<DataTypes>::addMToMatrix(const MechanicalParams* /*mparams*/ /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* /*matrix*/) { serr << "ERROR("<<getClassName()<<"): addMToMatrix(const MechanicalParams*, const sofa::core::behavior::MultiMatrixAccessor*) not implemented." << sendl; } template<class DataTypes> void Mass<DataTypes>::addMBKToMatrix(const MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix) { this->ForceField<DataTypes>::addMBKToMatrix(mparams /* PARAMS FIRST */, matrix); if (mparams->mFactorIncludingRayleighDamping(rayleighMass.getValue()) != 0.0) addMToMatrix(mparams /* PARAMS FIRST */, matrix); } template<class DataTypes> void Mass<DataTypes>::addSubMBKToMatrix(const MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix, const helper::vector<unsigned> /*subMatrixIndex*/) { addMBKToMatrix(mparams,matrix); // default implementation use full addMFunction } template<class DataTypes> void Mass<DataTypes>::addGravityToV(const MechanicalParams* mparams /* PARAMS FIRST */, MultiVecDerivId vid) { if(this->mstate) { DataVecDeriv& v = *vid[this->mstate.get(mparams)].write(); addGravityToV(mparams /* PARAMS FIRST */, v); } } template<class DataTypes> void Mass<DataTypes>::initGnuplot(const std::string path) { if (!this->getName().empty()) { if (m_gnuplotFileEnergy != NULL) delete m_gnuplotFileEnergy; m_gnuplotFileEnergy = new std::ofstream( (path+this->getName()+"_Energy.txt").c_str() ); } } template<class DataTypes> void Mass<DataTypes>::exportGnuplot(const MechanicalParams* mparams /* PARAMS FIRST */, double time) { if (m_gnuplotFileEnergy!=NULL) { (*m_gnuplotFileEnergy) << time <<"\t"<< this->getKineticEnergy(mparams) <<"\t"<< this->getPotentialEnergy(mparams) <<"\t"<< this->getPotentialEnergy(mparams) +this->getKineticEnergy(mparams)<< std::endl; } } template <class DataTypes> double Mass<DataTypes>::getElementMass(unsigned int ) const { serr << "ERROR("<<getClassName()<<"): getElementMass with Scalar not implemented" << sendl; return 0.0; } template <class DataTypes> void Mass<DataTypes>::getElementMass(unsigned int , defaulttype::BaseMatrix *m) const { static const defaulttype::BaseMatrix::Index dimension = (defaulttype::BaseMatrix::Index) defaulttype::DataTypeInfo<Coord>::size(); if (m->rowSize() != dimension || m->colSize() != dimension) m->resize(dimension,dimension); m->clear(); serr << "ERROR("<<getClassName()<<"): getElementMass with Matrix not implemented" << sendl; } } // namespace behavior } // namespace core } // namespace sofa #endif <|endoftext|>
<commit_before><commit_msg>Drop unused inline function<commit_after><|endoftext|>
<commit_before>// Copyright 2020 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "edf/edf_reader.h" #include <algorithm> #include <cmath> #include <iterator> #include <tuple> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "edf/base/canonical_errors.h" #include "edf/base/status.h" #include "edf/base/status_macros.h" #include "edf/base/time_proto_util.h" #include "edf/edf.h" #include "edf/edf_util.h" #include "edf/parse_edf_lib.h" namespace eeg_modelling { namespace { constexpr char kEdfAnnotationsLabel[] = "EDF Annotations"; constexpr int kBytesPerSample = 2; // Contains index to a specific sample in EDF. struct SampleIndex { int data_record_index; int sample_index; bool operator<(const SampleIndex& other) const { if (data_record_index < other.data_record_index) { return true; } else if (data_record_index == other.data_record_index) { return sample_index < other.sample_index; } else { return false; } } bool operator==(const SampleIndex& other) const { return data_record_index == other.data_record_index && sample_index == other.sample_index; } bool operator>(const SampleIndex& other) const { return other < *this; } }; // A range of samples specified by [start sample index, end sample index). struct SampleRange { SampleIndex start; SampleIndex end; }; // Returns the start index for the given start offset seconds. SampleIndex GetStartSampleIndex(double num_seconds_per_data_record, double num_samples_per_data_record, double start_offset_secs) { SampleIndex sample_index; sample_index.data_record_index = std::floor(start_offset_secs / num_seconds_per_data_record); sample_index.sample_index = std::floor(std::fmod(start_offset_secs, num_seconds_per_data_record) * num_samples_per_data_record / num_seconds_per_data_record); return sample_index; } // Returns the end index for the given end offset seconds. SampleIndex GetEndSampleIndex(double num_seconds_per_data_record, double num_samples_per_data_record, double end_offset_secs) { // This is similar to start index except that if the end_offset_secs does not // correspond exactly to the beginning of a sample, we have to advance it to // the next sample. SampleIndex sample_index; sample_index.data_record_index = std::floor(end_offset_secs / num_seconds_per_data_record); double index_in_data_record = std::fmod(end_offset_secs, num_seconds_per_data_record) * num_samples_per_data_record / num_seconds_per_data_record; sample_index.sample_index = std::floor(index_in_data_record); if (std::fmod(index_in_data_record, 1.0) != 0.0) { // It is okay if sample_index == num_samples_per_data_record. ++sample_index.sample_index; } return sample_index; } // Returns sample range corresponding to the given interval. SampleRange GetSampleRange(double num_seconds_per_data_record, double num_samples_per_data_record, double start_offset_secs, double end_offset_secs) { SampleRange sample_range; sample_range.start = GetStartSampleIndex(num_seconds_per_data_record, num_samples_per_data_record, start_offset_secs); sample_range.end = GetEndSampleIndex(num_seconds_per_data_record, num_samples_per_data_record, end_offset_secs); return sample_range; } // Returns sample ranges for all channels. template <typename SignalHeaderContainer> std::vector<SampleRange> GetAllSampleRanges( double num_seconds_per_data_record, const SignalHeaderContainer& signal_headers, double start_offset_secs, double end_offset_secs) { std::vector<SampleRange> sample_ranges; for (const auto& signal_header : signal_headers) { sample_ranges.push_back( GetSampleRange(num_seconds_per_data_record, signal_header.num_samples_per_data_record(), start_offset_secs, end_offset_secs)); } return sample_ranges; } // Helper to decode samples for signal. class SignalHandler { public: SignalHandler() = default; explicit SignalHandler(const EdfHeader::SignalHeader& signal_header) { auto physical_min = std::stod(signal_header.physical_min().c_str()); auto physical_max = std::stod(signal_header.physical_max().c_str()); auto digital_min = std::stod(signal_header.digital_min().c_str()); auto digital_max = std::stod(signal_header.digital_max().c_str()); scale_ = (physical_max - physical_min) / (digital_max - digital_min); offset_ = physical_max / scale_ - digital_max; } // Decodes samples from the given index range, and insert the values to the // result. void DecodeRange(const IntegerSignal& integer_signal, const int start, const int end, std::vector<double>* result) { for (int i = start; i < end; ++i) { result->push_back(Decode(integer_signal.samples(i))); } } private: double Decode(int64_t sample) const { return (sample + offset_) * scale_; } double offset_; double scale_; }; // Move all timestamped annotations from the input to the output. void MoveAnnotations(AnnotationSignal* input, AnnotationSignal* output) { for (TimeStampedAnnotationList& tal : *input->mutable_tals()) { output->add_tals()->Swap(&tal); } } } // namespace void EdfReader::SeekToDataRecord(int index, const EdfHeader& edf_header) { int num_bytes_per_data_record = 0; for (const auto& signal_header : edf_header.signal_headers()) { num_bytes_per_data_record += signal_header.num_samples_per_data_record() * kBytesPerSample; } if (edf_file_->SeekFromBegin(edf_header.num_header_bytes() + num_bytes_per_data_record * index) != OkStatus()) { ABSL_RAW_LOG(FATAL, "File seek failed"); } } StatusOr<std::unique_ptr<EdfReader>> EdfReader::Create(const string& edf_path, EdfFile* edf_file) { auto edf_header = absl::make_unique<EdfHeader>(); RETURN_IF_ERROR(ParseEdfHeader(edf_file, edf_header.get())); std::vector<EdfHeader::SignalHeader> signal_headers; ASSIGN_OR_RETURN(signal_headers, ParseEdfSignalHeaders(edf_file, edf_header->num_signals())); for (const auto& it : signal_headers) { *(edf_header->add_signal_headers()) = it; } double num_seconds_per_data_record; ASSIGN_OR_RETURN(num_seconds_per_data_record, GetNumSecondsPerDataRecord(*edf_header)); absl::Time absolute_start_time; ASSIGN_OR_RETURN(absolute_start_time, ParseEdfStartTime(*edf_header)); google::protobuf::Timestamp start_timestamp; ASSIGN_OR_RETURN(start_timestamp, EncodeGoogleApiProto(absolute_start_time)); return absl::make_unique<EdfReader>(edf_path, edf_file, std::move(edf_header), num_seconds_per_data_record, start_timestamp); } EdfReader::EdfReader(const string& edf_path, EdfFile* edf_file, std::unique_ptr<EdfHeader> edf_header, double num_seconds_per_data_record, const google::protobuf::Timestamp& start_timestamp) : edf_path_(edf_path), edf_file_(edf_file), edf_header_(std::move(edf_header)), num_seconds_per_data_record_(num_seconds_per_data_record), start_timestamp_(start_timestamp), annotation_index_(-1) { for (int annotation_index = 0; annotation_index < edf_header_->signal_headers().size(); ++annotation_index) { if (edf_header_->signal_headers(annotation_index).label() == kEdfAnnotationsLabel) { annotation_index_ = annotation_index; break; } } } StatusOr<AnnotationSignal> EdfReader::ReadAnnotations(double start_offset_secs, double end_offset_secs) { AnnotationSignal annotations; if (annotation_index_ < 0) { return annotations; } // Find the sample ranges. std::vector<SampleRange> sample_ranges = GetAllSampleRanges( num_seconds_per_data_record_, edf_header_->signal_headers(), start_offset_secs, end_offset_secs); const SampleRange& annotation_range = sample_ranges[annotation_index_]; // Seek to the first data record. SeekToDataRecord(annotation_range.start.data_record_index, *edf_header_); for (int data_record_index = annotation_range.start.data_record_index; data_record_index <= std::min(annotation_range.end.data_record_index, static_cast<int>(edf_header_->num_data_records() - 1)); ++data_record_index) { for (int signal_index = 0; signal_index < edf_header_->signal_headers().size(); ++signal_index) { const auto& signal_header = edf_header_->signal_headers(signal_index); const SampleRange& sample_range = sample_ranges[signal_index]; int num_samples = signal_header.num_samples_per_data_record(); int channel_bytes = num_samples * kBytesPerSample; int start_sample_index = data_record_index == sample_range.start.data_record_index ? sample_range.start.sample_index : 0; int end_sample_index = data_record_index == sample_range.end.data_record_index ? sample_range.end.sample_index : num_samples; if (signal_index == annotation_index_ && start_sample_index < end_sample_index) { AnnotationSignal annotation_signal; ASSIGN_OR_RETURN( annotation_signal, ParseEdfAnnotationSignal(edf_file_, channel_bytes, false)); MoveAnnotations(&annotation_signal, &annotations); } else { if (edf_file_->SeekFromBegin(edf_file_->Tell() + channel_bytes) != OkStatus()) { ABSL_RAW_LOG(FATAL, "File seek failed"); } } } } return annotations; } StatusOr<std::unordered_map<string, std::vector<double>>> EdfReader::ReadSignals(double start_offset_secs, double end_offset_secs) { // Prepare output. std::unordered_map<string, std::vector<double>> signals; for (const auto& signal_header : edf_header_->signal_headers()) { if (signal_header.label() != kEdfAnnotationsLabel) { signals[signal_header.label()]; } } if (signals.empty()) { return signals; } // Find the sample ranges. std::vector<SampleRange> sample_ranges = GetAllSampleRanges( num_seconds_per_data_record_, edf_header_->signal_headers(), start_offset_secs, end_offset_secs); // Verify that all occupy the same data record range. int start_data_record = sample_ranges[0].start.data_record_index; int end_data_record = sample_ranges[0].end.data_record_index; for (size_t i = 1; i < sample_ranges.size(); ++i) { if (start_data_record != sample_ranges[i].start.data_record_index) { return InternalError(absl::StrCat( "Inconsistent start data record indices: ", start_data_record, " != ", sample_ranges[i].start.data_record_index)); } if (end_data_record != sample_ranges[i].end.data_record_index) { return InternalError(absl::StrCat( "Inconsistent end data record indices: ", end_data_record, " != ", sample_ranges[i].end.data_record_index)); } } // Prepare signal handlers. std::vector<SignalHandler> signal_handlers; for (const auto& signal_header : edf_header_->signal_headers()) { signal_handlers.emplace_back(signal_header); } // Seek to the first data record. SeekToDataRecord(start_data_record, *edf_header_); for (int data_record_index = start_data_record; data_record_index <= std::min(end_data_record, static_cast<int>(edf_header_->num_data_records() - 1)); ++data_record_index) { for (int signal_index = 0; signal_index < edf_header_->signal_headers().size(); ++signal_index) { const SampleRange& sample_range = sample_ranges[signal_index]; const auto& signal_header = edf_header_->signal_headers(signal_index); int num_samples = signal_header.num_samples_per_data_record(); int channel_bytes = num_samples * kBytesPerSample; int start_sample_index = data_record_index == start_data_record ? sample_range.start.sample_index : 0; int end_sample_index = data_record_index == end_data_record ? sample_range.end.sample_index : num_samples; if (signal_header.label() != kEdfAnnotationsLabel && start_sample_index < end_sample_index) { IntegerSignal integer_signal; ASSIGN_OR_RETURN(integer_signal, ParseEdfIntegerSignal(edf_file_, num_samples, signal_header.label(), true)); signal_handlers[signal_index].DecodeRange( integer_signal, start_sample_index, end_sample_index, &signals[signal_header.label()]); } else { if (edf_file_->SeekFromBegin(edf_file_->Tell() + channel_bytes) != OkStatus()) { ABSL_RAW_LOG(FATAL, "File seek failed"); } } } } return signals; } } // namespace eeg_modelling <commit_msg>Internal change<commit_after>// Copyright 2020 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "edf/edf_reader.h" #include <algorithm> #include <cmath> #include <iterator> #include <tuple> #include "absl/container/node_hash_map.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/time/time.h" #include "edf/base/canonical_errors.h" #include "edf/base/status.h" #include "edf/base/status_macros.h" #include "edf/base/time_proto_util.h" #include "edf/edf.h" #include "edf/edf_util.h" #include "edf/parse_edf_lib.h" namespace eeg_modelling { namespace { constexpr char kEdfAnnotationsLabel[] = "EDF Annotations"; constexpr int kBytesPerSample = 2; // Contains index to a specific sample in EDF. struct SampleIndex { int data_record_index; int sample_index; bool operator<(const SampleIndex& other) const { if (data_record_index < other.data_record_index) { return true; } else if (data_record_index == other.data_record_index) { return sample_index < other.sample_index; } else { return false; } } bool operator==(const SampleIndex& other) const { return data_record_index == other.data_record_index && sample_index == other.sample_index; } bool operator>(const SampleIndex& other) const { return other < *this; } }; // A range of samples specified by [start sample index, end sample index). struct SampleRange { SampleIndex start; SampleIndex end; }; // Returns the start index for the given start offset seconds. SampleIndex GetStartSampleIndex(double num_seconds_per_data_record, double num_samples_per_data_record, double start_offset_secs) { SampleIndex sample_index; sample_index.data_record_index = std::floor(start_offset_secs / num_seconds_per_data_record); sample_index.sample_index = std::floor(std::fmod(start_offset_secs, num_seconds_per_data_record) * num_samples_per_data_record / num_seconds_per_data_record); return sample_index; } // Returns the end index for the given end offset seconds. SampleIndex GetEndSampleIndex(double num_seconds_per_data_record, double num_samples_per_data_record, double end_offset_secs) { // This is similar to start index except that if the end_offset_secs does not // correspond exactly to the beginning of a sample, we have to advance it to // the next sample. SampleIndex sample_index; sample_index.data_record_index = std::floor(end_offset_secs / num_seconds_per_data_record); double index_in_data_record = std::fmod(end_offset_secs, num_seconds_per_data_record) * num_samples_per_data_record / num_seconds_per_data_record; sample_index.sample_index = std::floor(index_in_data_record); if (std::fmod(index_in_data_record, 1.0) != 0.0) { // It is okay if sample_index == num_samples_per_data_record. ++sample_index.sample_index; } return sample_index; } // Returns sample range corresponding to the given interval. SampleRange GetSampleRange(double num_seconds_per_data_record, double num_samples_per_data_record, double start_offset_secs, double end_offset_secs) { SampleRange sample_range; sample_range.start = GetStartSampleIndex(num_seconds_per_data_record, num_samples_per_data_record, start_offset_secs); sample_range.end = GetEndSampleIndex(num_seconds_per_data_record, num_samples_per_data_record, end_offset_secs); return sample_range; } // Returns sample ranges for all channels. template <typename SignalHeaderContainer> std::vector<SampleRange> GetAllSampleRanges( double num_seconds_per_data_record, const SignalHeaderContainer& signal_headers, double start_offset_secs, double end_offset_secs) { std::vector<SampleRange> sample_ranges; for (const auto& signal_header : signal_headers) { sample_ranges.push_back( GetSampleRange(num_seconds_per_data_record, signal_header.num_samples_per_data_record(), start_offset_secs, end_offset_secs)); } return sample_ranges; } // Helper to decode samples for signal. class SignalHandler { public: SignalHandler() = default; explicit SignalHandler(const EdfHeader::SignalHeader& signal_header) { auto physical_min = std::stod(signal_header.physical_min().c_str()); auto physical_max = std::stod(signal_header.physical_max().c_str()); auto digital_min = std::stod(signal_header.digital_min().c_str()); auto digital_max = std::stod(signal_header.digital_max().c_str()); scale_ = (physical_max - physical_min) / (digital_max - digital_min); offset_ = physical_max / scale_ - digital_max; } // Decodes samples from the given index range, and insert the values to the // result. void DecodeRange(const IntegerSignal& integer_signal, const int start, const int end, std::vector<double>* result) { for (int i = start; i < end; ++i) { result->push_back(Decode(integer_signal.samples(i))); } } private: double Decode(int64_t sample) const { return (sample + offset_) * scale_; } double offset_; double scale_; }; // Move all timestamped annotations from the input to the output. void MoveAnnotations(AnnotationSignal* input, AnnotationSignal* output) { for (TimeStampedAnnotationList& tal : *input->mutable_tals()) { output->add_tals()->Swap(&tal); } } } // namespace void EdfReader::SeekToDataRecord(int index, const EdfHeader& edf_header) { int num_bytes_per_data_record = 0; for (const auto& signal_header : edf_header.signal_headers()) { num_bytes_per_data_record += signal_header.num_samples_per_data_record() * kBytesPerSample; } if (edf_file_->SeekFromBegin(edf_header.num_header_bytes() + num_bytes_per_data_record * index) != OkStatus()) { ABSL_RAW_LOG(FATAL, "File seek failed"); } } StatusOr<std::unique_ptr<EdfReader>> EdfReader::Create(const string& edf_path, EdfFile* edf_file) { auto edf_header = absl::make_unique<EdfHeader>(); RETURN_IF_ERROR(ParseEdfHeader(edf_file, edf_header.get())); std::vector<EdfHeader::SignalHeader> signal_headers; ASSIGN_OR_RETURN(signal_headers, ParseEdfSignalHeaders(edf_file, edf_header->num_signals())); for (const auto& it : signal_headers) { *(edf_header->add_signal_headers()) = it; } double num_seconds_per_data_record; ASSIGN_OR_RETURN(num_seconds_per_data_record, GetNumSecondsPerDataRecord(*edf_header)); absl::Time absolute_start_time; ASSIGN_OR_RETURN(absolute_start_time, ParseEdfStartTime(*edf_header)); google::protobuf::Timestamp start_timestamp; ASSIGN_OR_RETURN(start_timestamp, EncodeGoogleApiProto(absolute_start_time)); return absl::make_unique<EdfReader>(edf_path, edf_file, std::move(edf_header), num_seconds_per_data_record, start_timestamp); } EdfReader::EdfReader(const string& edf_path, EdfFile* edf_file, std::unique_ptr<EdfHeader> edf_header, double num_seconds_per_data_record, const google::protobuf::Timestamp& start_timestamp) : edf_path_(edf_path), edf_file_(edf_file), edf_header_(std::move(edf_header)), num_seconds_per_data_record_(num_seconds_per_data_record), start_timestamp_(start_timestamp), annotation_index_(-1) { for (int annotation_index = 0; annotation_index < edf_header_->signal_headers().size(); ++annotation_index) { if (edf_header_->signal_headers(annotation_index).label() == kEdfAnnotationsLabel) { annotation_index_ = annotation_index; break; } } } StatusOr<AnnotationSignal> EdfReader::ReadAnnotations(double start_offset_secs, double end_offset_secs) { AnnotationSignal annotations; if (annotation_index_ < 0) { return annotations; } // Find the sample ranges. std::vector<SampleRange> sample_ranges = GetAllSampleRanges( num_seconds_per_data_record_, edf_header_->signal_headers(), start_offset_secs, end_offset_secs); const SampleRange& annotation_range = sample_ranges[annotation_index_]; // Seek to the first data record. SeekToDataRecord(annotation_range.start.data_record_index, *edf_header_); for (int data_record_index = annotation_range.start.data_record_index; data_record_index <= std::min(annotation_range.end.data_record_index, static_cast<int>(edf_header_->num_data_records() - 1)); ++data_record_index) { for (int signal_index = 0; signal_index < edf_header_->signal_headers().size(); ++signal_index) { const auto& signal_header = edf_header_->signal_headers(signal_index); const SampleRange& sample_range = sample_ranges[signal_index]; int num_samples = signal_header.num_samples_per_data_record(); int channel_bytes = num_samples * kBytesPerSample; int start_sample_index = data_record_index == sample_range.start.data_record_index ? sample_range.start.sample_index : 0; int end_sample_index = data_record_index == sample_range.end.data_record_index ? sample_range.end.sample_index : num_samples; if (signal_index == annotation_index_ && start_sample_index < end_sample_index) { AnnotationSignal annotation_signal; ASSIGN_OR_RETURN( annotation_signal, ParseEdfAnnotationSignal(edf_file_, channel_bytes, false)); MoveAnnotations(&annotation_signal, &annotations); } else { if (edf_file_->SeekFromBegin(edf_file_->Tell() + channel_bytes) != OkStatus()) { ABSL_RAW_LOG(FATAL, "File seek failed"); } } } } return annotations; } StatusOr<absl::node_hash_map<string, std::vector<double>>> EdfReader::ReadSignals(double start_offset_secs, double end_offset_secs) { // Prepare output. absl::node_hash_map<string, std::vector<double>> signals; for (const auto& signal_header : edf_header_->signal_headers()) { if (signal_header.label() != kEdfAnnotationsLabel) { signals[signal_header.label()]; } } if (signals.empty()) { return signals; } // Find the sample ranges. std::vector<SampleRange> sample_ranges = GetAllSampleRanges( num_seconds_per_data_record_, edf_header_->signal_headers(), start_offset_secs, end_offset_secs); // Verify that all occupy the same data record range. int start_data_record = sample_ranges[0].start.data_record_index; int end_data_record = sample_ranges[0].end.data_record_index; for (size_t i = 1; i < sample_ranges.size(); ++i) { if (start_data_record != sample_ranges[i].start.data_record_index) { return InternalError(absl::StrCat( "Inconsistent start data record indices: ", start_data_record, " != ", sample_ranges[i].start.data_record_index)); } if (end_data_record != sample_ranges[i].end.data_record_index) { return InternalError(absl::StrCat( "Inconsistent end data record indices: ", end_data_record, " != ", sample_ranges[i].end.data_record_index)); } } // Prepare signal handlers. std::vector<SignalHandler> signal_handlers; for (const auto& signal_header : edf_header_->signal_headers()) { signal_handlers.emplace_back(signal_header); } // Seek to the first data record. SeekToDataRecord(start_data_record, *edf_header_); for (int data_record_index = start_data_record; data_record_index <= std::min(end_data_record, static_cast<int>(edf_header_->num_data_records() - 1)); ++data_record_index) { for (int signal_index = 0; signal_index < edf_header_->signal_headers().size(); ++signal_index) { const SampleRange& sample_range = sample_ranges[signal_index]; const auto& signal_header = edf_header_->signal_headers(signal_index); int num_samples = signal_header.num_samples_per_data_record(); int channel_bytes = num_samples * kBytesPerSample; int start_sample_index = data_record_index == start_data_record ? sample_range.start.sample_index : 0; int end_sample_index = data_record_index == end_data_record ? sample_range.end.sample_index : num_samples; if (signal_header.label() != kEdfAnnotationsLabel && start_sample_index < end_sample_index) { IntegerSignal integer_signal; ASSIGN_OR_RETURN(integer_signal, ParseEdfIntegerSignal(edf_file_, num_samples, signal_header.label(), true)); signal_handlers[signal_index].DecodeRange( integer_signal, start_sample_index, end_sample_index, &signals[signal_header.label()]); } else { if (edf_file_->SeekFromBegin(edf_file_->Tell() + channel_bytes) != OkStatus()) { ABSL_RAW_LOG(FATAL, "File seek failed"); } } } } return signals; } } // namespace eeg_modelling <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_MIOPEN_ERRORS_HPP #define GUARD_MIOPEN_ERRORS_HPP #include <exception> #include <iostream> #include <miopen/miopen.h> #include <miopen/object.hpp> #include <miopen/returns.hpp> #include <string> #include <tuple> namespace miopen { struct Exception : std::exception { std::string message; miopenStatus_t status; Exception(const std::string& msg = "") : message(msg), status(miopenStatusUnknownError) {} Exception(miopenStatus_t s, const std::string& msg = "") : message(msg), status(s) {} Exception SetContext(const std::string& file, int line) { message = file + ":" + std::to_string(line) + ": " + message; return *this; } // Workaround for HIP, this must be inline const char* what() const noexcept override { return message.c_str(); } }; std::string OpenCLErrorMessage(int error, const std::string& msg = ""); std::string HIPErrorMessage(int error, const std::string& msg = ""); #define MIOPEN_THROW(...) throw miopen::Exception(__VA_ARGS__).SetContext(__FILE__, __LINE__) #define MIOPEN_THROW_CL_STATUS(...) \ MIOPEN_THROW(miopenStatusUnknownError, miopen::OpenCLErrorMessage(__VA_ARGS__)) #define MIOPEN_THROW_HIP_STATUS(...) \ MIOPEN_THROW(miopenStatusUnknownError, miopen::HIPErrorMessage(__VA_ARGS__)) // TODO(paul): Debug builds should leave the exception uncaught template <class F> miopenStatus_t try_(F f, bool output=true) { try { f(); } catch(const Exception& ex) { if (output) std::cerr << "MIOpen Error: " << ex.what() << std::endl; return ex.status; } catch(const std::exception& ex) { if (output) std::cerr << "MIOpen Error: " << ex.what() << std::endl; return miopenStatusUnknownError; } catch(...) { return miopenStatusUnknownError; } return miopenStatusSuccess; } template <class T> auto deref(T&& x, miopenStatus_t err = miopenStatusBadParm) -> decltype((x == nullptr), get_object(*x)) { if(x == nullptr) { MIOPEN_THROW(err, "Dereferencing nullptr"); } return get_object(*x); } template <class... Ts> auto tie_deref(Ts&... xs) MIOPEN_RETURNS(std::tie(miopen::deref(xs)...)); } // namespace miopen #endif <commit_msg>Formatting<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_MIOPEN_ERRORS_HPP #define GUARD_MIOPEN_ERRORS_HPP #include <exception> #include <iostream> #include <miopen/miopen.h> #include <miopen/object.hpp> #include <miopen/returns.hpp> #include <string> #include <tuple> namespace miopen { struct Exception : std::exception { std::string message; miopenStatus_t status; Exception(const std::string& msg = "") : message(msg), status(miopenStatusUnknownError) {} Exception(miopenStatus_t s, const std::string& msg = "") : message(msg), status(s) {} Exception SetContext(const std::string& file, int line) { message = file + ":" + std::to_string(line) + ": " + message; return *this; } // Workaround for HIP, this must be inline const char* what() const noexcept override { return message.c_str(); } }; std::string OpenCLErrorMessage(int error, const std::string& msg = ""); std::string HIPErrorMessage(int error, const std::string& msg = ""); #define MIOPEN_THROW(...) throw miopen::Exception(__VA_ARGS__).SetContext(__FILE__, __LINE__) #define MIOPEN_THROW_CL_STATUS(...) \ MIOPEN_THROW(miopenStatusUnknownError, miopen::OpenCLErrorMessage(__VA_ARGS__)) #define MIOPEN_THROW_HIP_STATUS(...) \ MIOPEN_THROW(miopenStatusUnknownError, miopen::HIPErrorMessage(__VA_ARGS__)) // TODO(paul): Debug builds should leave the exception uncaught template <class F> miopenStatus_t try_(F f, bool output = true) { try { f(); } catch(const Exception& ex) { if(output) std::cerr << "MIOpen Error: " << ex.what() << std::endl; return ex.status; } catch(const std::exception& ex) { if(output) std::cerr << "MIOpen Error: " << ex.what() << std::endl; return miopenStatusUnknownError; } catch(...) { return miopenStatusUnknownError; } return miopenStatusSuccess; } template <class T> auto deref(T&& x, miopenStatus_t err = miopenStatusBadParm) -> decltype((x == nullptr), get_object(*x)) { if(x == nullptr) { MIOPEN_THROW(err, "Dereferencing nullptr"); } return get_object(*x); } template <class... Ts> auto tie_deref(Ts&... xs) MIOPEN_RETURNS(std::tie(miopen::deref(xs)...)); } // namespace miopen #endif <|endoftext|>
<commit_before>/* indivudal.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for individual namespace */ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <memory> #include <tuple> #include <vector> #include "individual.hpp" #include "../options/options.hpp" #include "../random_generator/random_generator.hpp" namespace individual { using std::vector; using std::string; using namespace random_generator; // Default Size struct constructor. Size::Size(): internals{0}, leaves{0} {} // Available methods for tree creation. enum class Method {grow, full}; // List of valid functions for an expression. enum class Function {nil, prog2, prog3, iffoodahead, left, right, forward}; using F = Function; // Vectors of same-arity function enums. vector<F> nullaries {F::left, F::right, F::forward}; vector<F> binaries {F::prog2, F::iffoodahead}; vector<F> trinaries {F::prog3}; /* Vectors of available function enums. Should be moved into Options struct. */ vector<F> leaves = nullaries; vector<F> internals {F::prog2, F::prog3, F::iffoodahead}; // Returns a random function from a given set of functions. Function get_function(const vector<Function>& functions) { int_dist dist{0, static_cast<int>(functions.size()) - 1}; // closed interval return functions[dist(rg.engine)]; } // Returns bool of whether or not the item is in the set. template<typename I, typename S> bool contains(const I& item, const S& set) { return std::find(set.begin(), set.end(), item) != set.end(); } // Returns the appropriate arity for a given function. unsigned int get_arity(const Function& function) { if (contains(function, nullaries)) return 0; else if (contains(function, binaries)) return 2; else if (contains(function, trinaries)) return 3; assert(false); } // Default constructor for "empty" node Node::Node(): function{Function::nil}, arity{0} {} /* Recursively constructs a parse tree using the given method (either GROW or FULL). */ Node::Node(const Method& method, const unsigned int& max_depth) { // Create leaf node if at the max depth or randomly (if growing). real_dist dist{0, 1}; float grow_chance = static_cast<float>(leaves.size()) / (leaves.size() + internals.size()); if (max_depth == 0 or (method == Method::grow and dist(rg.engine) < grow_chance)) { function = get_function(leaves); arity = 0; // get_arity(function); leaves are always zero } // Otherwise choose an internal node. else { function = get_function(internals); arity = get_arity(function); // Recursively create subtrees. children.reserve(arity); for (unsigned int i = 0; i < arity; ++i) children.emplace_back(Node{method, max_depth - 1}); } assert(function != Function::nil); // do not create null types assert(children.size() == arity); // ensure arity } // Returns a string visually representing a particular node. string Node::represent() const { switch (function) { case F::nil: assert(false); // Never represent empty node. case F::prog2: return "prog-2"; case F::prog3: return "prog-3"; case F::iffoodahead: return "if-food-ahead"; case F::left: return "left"; case F::right: return "right"; case F::forward: return "forward"; } assert(false); // Every node should have been matched. } /* Returns string representation of expression in Polish/prefix notation using a pre-order traversal. */ string Node::print() const { if (children.empty()) return represent(); string formula = "(" + represent(); for (const Node& child : children) formula += " " + child.print(); return formula + ")"; } /* Evaluates an ant over a given map using a depth-first post-order recursive continuous evaluation of a decision tree. */ void Node::evaluate(options::Map& map) const { if (not map.active()) return; switch (function) { case F::left: map.left(); // Terminal case break; case F::right: map.right(); // Terminal case break; case F::forward: map.forward(); // Terminal case break; case F::iffoodahead: if (map.look()) // Do left or right depending on if food ahead children[0].evaluate(map); else children[1].evaluate(map); break; case F::prog2: // Falls through case F::prog3: for (const Node& child : children) child.evaluate(map); break; case F::nil: assert(false); // Never evaluate empty node } } /* Recursively count children via post-order traversal. Keep track of internals and leaves via Size struct */ const Size Node::size() const { Size size; for (const Node& child : children) { Size temp = child.size(); size.internals += temp.internals; size.leaves += temp.leaves; } if (children.empty()) ++size.leaves; else ++size.internals; return size; } // Used to represent "not-found" (similar to a NULL pointer). Node empty; /* Depth-first search for taget node. Must be seeking either internal or leaf, cannot be both. */ Node& Node::visit(const Size& i, Size& visiting) { for (Node& child : children) { // Increase relevant count. if (child.children.empty()) ++visiting.leaves; else ++visiting.internals; // Return node reference if found. if (visiting.internals == i.internals or visiting.leaves == i.leaves) return child; else { Node& temp = child.visit(i, visiting); // Recursive search. if (temp.function != Function::nil) return temp; } } return empty; } void Node::mutate_self() { if (arity == 0) { const Function old = function; while (function == old) function = get_function(leaves); } else { const Function old = function; while (function == old) function = get_function(internals); arity = get_arity(function); // Fix arity mismatches caused by mutation if (arity == 2 and children.size() == 3) children.pop_back(); else if (arity == 3 and children.size() == 2) { int_dist depth_dist{0, 4}; real_dist dist{0, 1}; unsigned int depth = depth_dist(rg.engine); Method method = (dist(rg.engine) < 0.5) ? Method::grow : Method::full; children.emplace_back(Node{method, depth}); } } assert(arity == children.size()); assert(function != Function::nil); } // Recursively mutate nodes with given probability. void Node::mutate_tree(const float& chance) { real_dist dist{0, 1}; for (Node& child : children) { if (dist(rg.engine) < chance) child.mutate_self(); child.mutate_tree(chance); } } // Default constructor for Individual Individual::Individual() {} /* Create an Individual tree by having a root node (to which the actual construction is delegated). The depth is passed by value as its creation elsewhere is temporary. */ Individual::Individual(const unsigned int depth, const float& chance, options::Map map): fitness{0}, adjusted{0} { // 50/50 chance to choose grow or full real_dist dist{0, 1}; Method method = (dist(rg.engine) < chance) ? Method::grow : Method::full; root = Node{method, depth}; /* The evaluate method updates the size and both raw and adjusted fitnesses. */ evaluate(map); } // Return string representation of a tree's size and fitness. string Individual::print() const { using std::to_string; string info = "# Size " + to_string(get_total()) + ", with " + to_string(get_internals()) + " internals, and " + to_string(get_leaves()) + " leaves.\n" + "# Raw fitness: " + to_string(score) + ", and adjusted: " + to_string(adjusted) + ".\n"; return info; } // Return string represenation of tree's expression (delegated). string Individual::print_formula() const { return "# Formula: " + root.print() + "\n"; } // Read-only "getters" for private data unsigned int Individual::get_internals() const { return size.internals; } unsigned int Individual::get_leaves() const { return size.leaves; } unsigned int Individual::get_total() const { return size.internals + size.leaves; } unsigned int Individual::get_score() const { return score; } float Individual::get_fitness() const { return fitness; } float Individual::get_adjusted() const { return adjusted; } /* Evaluate Individual for given values and calculate size. Update Individual's size and fitness accordingly. Return non-empty string if printing. */ string Individual::evaluate(options::Map map, const float& penalty, const bool& print) { // Update size on evaluation because it's incredibly convenient. size = root.size(); while (map.active()) root.evaluate(map); score = map.fitness(); // Adjusted fitness does not have size penalty. adjusted = static_cast<float>(score) / map.max(); // Apply size penalty if not printing. fitness = score - penalty * get_total(); string evaluation; if (print) evaluation = map.print(); return evaluation; } // Mutate each node with given probability. void Individual::mutate(const float& chance) { root.mutate_tree(chance); } // Safely return reference to desired node. Node& Individual::operator[](const Size& i) { assert(i.internals <= get_internals()); assert(i.leaves <= get_leaves()); Size visiting; // Return root node if that's what we're seeking. if (i.internals == 0 and i.leaves == 0) return root; else return root.visit(i, visiting); } /* Swap two random subtrees between Individuals "a" and "b", selecting an internal node with chance probability. TODO: DRY */ void crossover(const float& chance, Individual& a, Individual& b) { real_dist probability{0, 1}; Size target_a, target_b; // Guaranteed to have at least 1 leaf, but may have 0 internals. if (a.get_internals() != 0 and probability(rg.engine) < chance) { // Choose an internal node. int_dist dist{0, static_cast<int>(a.get_internals()) - 1}; target_a.internals = dist(rg.engine); } else { // Otherwise choose a leaf node. int_dist dist{0, static_cast<int>(a.get_leaves()) - 1}; target_a.leaves = dist(rg.engine); } // Totally repeating myself here for "b". if (b.get_internals() != 0 and probability(rg.engine) < chance) { int_dist dist{0, static_cast<int>(b.get_internals()) - 1}; target_b.internals = dist(rg.engine); } else { int_dist dist{0, static_cast<int>(b.get_leaves()) - 1}; target_b.leaves = dist(rg.engine); } std::swap(a[target_a], b[target_b]); } } <commit_msg>Adding Node create delegate function<commit_after>/* indivudal.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for individual namespace */ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <memory> #include <tuple> #include <vector> #include "individual.hpp" #include "../options/options.hpp" #include "../random_generator/random_generator.hpp" namespace individual { using std::vector; using std::string; using namespace random_generator; // Default Size struct constructor. Size::Size(): internals{0}, leaves{0} {} // Available methods for tree creation. enum class Method {grow, full}; // List of valid functions for an expression. enum class Function {nil, prog2, prog3, iffoodahead, left, right, forward}; using F = Function; // Vectors of same-arity function enums. vector<F> nullaries {F::left, F::right, F::forward}; vector<F> binaries {F::prog2, F::iffoodahead}; vector<F> trinaries {F::prog3}; /* Vectors of available function enums. Should be moved into Options struct. */ vector<F> leaves = nullaries; vector<F> internals {F::prog2, F::prog3, F::iffoodahead}; // Returns a random function from a given set of functions. Function get_function(const vector<Function>& functions) { int_dist dist{0, static_cast<int>(functions.size()) - 1}; // closed interval return functions[dist(rg.engine)]; } // Returns bool of whether or not the item is in the set. template<typename I, typename S> bool contains(const I& item, const S& set) { return std::find(set.begin(), set.end(), item) != set.end(); } // Returns the appropriate arity for a given function. unsigned int get_arity(const Function& function) { if (contains(function, nullaries)) return 0; else if (contains(function, binaries)) return 2; else if (contains(function, trinaries)) return 3; assert(false); } // Default constructor for "empty" node Node::Node(): function{Function::nil}, arity{0} {} /* Recursively constructs a parse tree using the given method (either GROW or FULL). */ Node::Node(const Method& method, const unsigned int& max_depth) { // Create leaf node if at the max depth or randomly (if growing). real_dist dist{0, 1}; float grow_chance = static_cast<float>(leaves.size()) / (leaves.size() + internals.size()); if (max_depth == 0 or (method == Method::grow and dist(rg.engine) < grow_chance)) { function = get_function(leaves); arity = 0; // get_arity(function); leaves are always zero } // Otherwise choose an internal node. else { function = get_function(internals); arity = get_arity(function); // Recursively create subtrees. children.reserve(arity); for (unsigned int i = 0; i < arity; ++i) children.emplace_back(Node{method, max_depth - 1}); } assert(function != Function::nil); // do not create null types assert(children.size() == arity); // ensure arity } Node create(const unsigned int& max_depth, const float& chance) { int_dist depth_dist{0, static_cast<int>(max_depth)}; unsigned int depth = depth_dist(rg.engine); real_dist method_dist{0, 1}; Method method = (method_dist(rg.engine) < chance) ? Method::grow : Method::full; return Node{method, depth}; } // Returns a string visually representing a particular node. string Node::represent() const { switch (function) { case F::nil: assert(false); // Never represent empty node. case F::prog2: return "prog-2"; case F::prog3: return "prog-3"; case F::iffoodahead: return "if-food-ahead"; case F::left: return "left"; case F::right: return "right"; case F::forward: return "forward"; } assert(false); // Every node should have been matched. } /* Returns string representation of expression in Polish/prefix notation using a pre-order traversal. */ string Node::print() const { if (children.empty()) return represent(); string formula = "(" + represent(); for (const Node& child : children) formula += " " + child.print(); return formula + ")"; } /* Evaluates an ant over a given map using a depth-first post-order recursive continuous evaluation of a decision tree. */ void Node::evaluate(options::Map& map) const { if (not map.active()) return; switch (function) { case F::left: map.left(); // Terminal case break; case F::right: map.right(); // Terminal case break; case F::forward: map.forward(); // Terminal case break; case F::iffoodahead: if (map.look()) // Do left or right depending on if food ahead children[0].evaluate(map); else children[1].evaluate(map); break; case F::prog2: // Falls through case F::prog3: for (const Node& child : children) child.evaluate(map); break; case F::nil: assert(false); // Never evaluate empty node } } /* Recursively count children via post-order traversal. Keep track of internals and leaves via Size struct */ const Size Node::size() const { Size size; for (const Node& child : children) { Size temp = child.size(); size.internals += temp.internals; size.leaves += temp.leaves; } if (children.empty()) ++size.leaves; else ++size.internals; return size; } // Used to represent "not-found" (similar to a NULL pointer). Node empty; /* Depth-first search for taget node. Must be seeking either internal or leaf, cannot be both. */ Node& Node::visit(const Size& i, Size& visiting) { for (Node& child : children) { // Increase relevant count. if (child.children.empty()) ++visiting.leaves; else ++visiting.internals; // Return node reference if found. if (visiting.internals == i.internals or visiting.leaves == i.leaves) return child; else { Node& temp = child.visit(i, visiting); // Recursive search. if (temp.function != Function::nil) return temp; } } return empty; } void Node::mutate_self() { if (arity == 0) { const Function old = function; while (function == old) function = get_function(leaves); } else { const Function old = function; while (function == old) function = get_function(internals); arity = get_arity(function); // Fix arity mismatches caused by mutation if (arity == 2 and children.size() == 3) children.pop_back(); else if (arity == 3 and children.size() == 2) children.emplace_back(create(4, 0.5)); } assert(arity == children.size()); assert(function != Function::nil); } // Recursively mutate nodes with given probability. void Node::mutate_tree(const float& chance) { real_dist dist{0, 1}; for (Node& child : children) { if (dist(rg.engine) < chance) child.mutate_self(); child.mutate_tree(chance); } } // Default constructor for Individual Individual::Individual() {} /* Create an Individual tree by having a root node (to which the actual construction is delegated). The depth is passed by value as its creation elsewhere is temporary. */ Individual::Individual(const unsigned int depth, const float& chance, options::Map map): fitness{0}, adjusted{0} { root = create(depth, chance); /* The evaluate method updates the size and both raw and adjusted fitnesses. */ evaluate(map); } // Return string representation of a tree's size and fitness. string Individual::print() const { using std::to_string; string info = "# Size " + to_string(get_total()) + ", with " + to_string(get_internals()) + " internals, and " + to_string(get_leaves()) + " leaves.\n" + "# Raw fitness: " + to_string(score) + ", and adjusted: " + to_string(adjusted) + ".\n"; return info; } // Return string represenation of tree's expression (delegated). string Individual::print_formula() const { return "# Formula: " + root.print() + "\n"; } // Read-only "getters" for private data unsigned int Individual::get_internals() const { return size.internals; } unsigned int Individual::get_leaves() const { return size.leaves; } unsigned int Individual::get_total() const { return size.internals + size.leaves; } unsigned int Individual::get_score() const { return score; } float Individual::get_fitness() const { return fitness; } float Individual::get_adjusted() const { return adjusted; } /* Evaluate Individual for given values and calculate size. Update Individual's size and fitness accordingly. Return non-empty string if printing. */ string Individual::evaluate(options::Map map, const float& penalty, const bool& print) { // Update size on evaluation because it's incredibly convenient. size = root.size(); while (map.active()) root.evaluate(map); score = map.fitness(); // Adjusted fitness does not have size penalty. adjusted = static_cast<float>(score) / map.max(); // Apply size penalty if not printing. fitness = score - penalty * get_total(); string evaluation; if (print) evaluation = map.print(); return evaluation; } // Mutate each node with given probability. void Individual::mutate(const float& chance) { root.mutate_tree(chance); } // Safely return reference to desired node. Node& Individual::operator[](const Size& i) { assert(i.internals <= get_internals()); assert(i.leaves <= get_leaves()); Size visiting; // Return root node if that's what we're seeking. if (i.internals == 0 and i.leaves == 0) return root; else return root.visit(i, visiting); } /* Swap two random subtrees between Individuals "a" and "b", selecting an internal node with chance probability. TODO: DRY */ void crossover(const float& chance, Individual& a, Individual& b) { real_dist probability{0, 1}; Size target_a, target_b; // Guaranteed to have at least 1 leaf, but may have 0 internals. if (a.get_internals() != 0 and probability(rg.engine) < chance) { // Choose an internal node. int_dist dist{0, static_cast<int>(a.get_internals()) - 1}; target_a.internals = dist(rg.engine); } else { // Otherwise choose a leaf node. int_dist dist{0, static_cast<int>(a.get_leaves()) - 1}; target_a.leaves = dist(rg.engine); } // Totally repeating myself here for "b". if (b.get_internals() != 0 and probability(rg.engine) < chance) { int_dist dist{0, static_cast<int>(b.get_internals()) - 1}; target_b.internals = dist(rg.engine); } else { int_dist dist{0, static_cast<int>(b.get_leaves()) - 1}; target_b.leaves = dist(rg.engine); } std::swap(a[target_a], b[target_b]); } } <|endoftext|>
<commit_before>#include "ControlResponseTE.h" #include <APL/Logger.h> #include <APL/Exception.h> #include <APL/Parsing.h> namespace apl { CommandResponder :: CommandResponder(Logger* apLogger, bool aLinkStatuses, IDataObserver* apObs) : Loggable(apLogger), mpObs(apObs), mLinkStatuses(aLinkStatuses) { } void CommandResponder :: AcceptCommand(const BinaryOutput& ctrl, size_t i, int aSequence, IResponseAcceptor* apRspAcceptor) { CriticalSection c(&mLock); CommandResponse cr; cr.mResult = this->HandleControl(ctrl, i); apRspAcceptor->AcceptResponse(cr, aSequence); } void CommandResponder :: AcceptCommand(const Setpoint& ctrl, size_t i, int aSequence, IResponseAcceptor* apRspAcceptor) { CriticalSection c(&mLock); CommandResponse cr; cr.mResult = this->HandleControl(ctrl, i); apRspAcceptor->AcceptResponse(cr, aSequence); } CommandStatus CommandResponder :: HandleControl(const BinaryOutput& aControl, size_t aIndex) { CommandStatus cs = CS_TOO_MANY_OPS; if ( mLinkStatuses && (aControl.GetCode() == CC_LATCH_ON || aControl.GetCode() == CC_LATCH_OFF)) { try { Transaction t(mpObs); bool val = aControl.GetCode() == CC_LATCH_ON ? true : false; mpObs->Update(ControlStatus(val, ControlStatus::ONLINE), aIndex); cs = CS_SUCCESS; LOG_BLOCK(LEV_INFO, "Updated ControlStatus " << aIndex << " with " << val << "." ); } catch (Exception& ex) { LOG_BLOCK(LEV_WARNING, "Failure trying to update point in response to control. " << ex.GetErrorString()); cs = CS_NOT_SUPPORTED; } } else { cs = GetResponseCode(true, aIndex); } LOG_BLOCK(LEV_INFO, "[" << aIndex << "] - " << aControl.ToString() << " returning " << ToString(cs)); return cs; } CommandStatus CommandResponder :: HandleControl(const Setpoint& aControl, size_t aIndex) { CommandStatus cs = CS_TOO_MANY_OPS; if ( mLinkStatuses ) { try { Transaction t(mpObs); mpObs->Update(SetpointStatus(aControl.GetValue(), SetpointStatus::ONLINE), aIndex); cs = CS_SUCCESS; LOG_BLOCK(LEV_INFO, "Updated SetpointStatus " << aIndex << " with " << aControl.GetValue() << "." ); } catch (Exception& ex) { LOG_BLOCK(LEV_WARNING, "Failure trying to update point in response to control. " << ex.GetErrorString()); cs = CS_NOT_SUPPORTED; } } else { cs = GetResponseCode(false, aIndex); } LOG_BLOCK(LEV_INFO, "[" << aIndex << "] - " << aControl.ToString() << " returning " << ToString(cs)); return cs; } void CommandResponder :: SetResponseCode(bool aType, size_t aIndex, CommandStatus aCode) { CriticalSection c(&mLock); CommandMap& m = (aType) ? mBinaryResponses : mSetpointResponses; CommandMap::iterator iter = m.find(aIndex); if(iter != m.end()) iter->second = aCode; else m[aIndex] = aCode; } CommandStatus CommandResponder :: GetResponseCode(bool aType, size_t aIndex) { CommandMap& m = (aType) ? mBinaryResponses : mSetpointResponses; // check for specific return code for this index. CommandMap::iterator iter = m.find(aIndex); if(iter != m.end()) return iter->second; return CS_NOT_SUPPORTED; //return default } ControlResponseTE :: ControlResponseTE(Logger* apLogger, bool aLinkStatuses, IDataObserver* apObs) : mHandler(apLogger, aLinkStatuses, apObs) { } void ControlResponseTE :: _BindToTerminal(ITerminal* apTerminal) { CommandNode cmd; cmd.mName = "response"; cmd.mUsage = "response [bo|st|all] [all|#] [code]"; cmd.mDesc = "Sets the response code we will use to respond to the incoming commands.\nYou can use return code name or index: SUCCESS, TIMEOUT, NO_SELECT, FORMAT_ERROR, NOT_SUPPORTED, ALREADY_ACTIVE, HARDWARE_ERROR, LOCAL, TOO_MANY_OPS, NOT_AUTHORIZED."; cmd.mHandler = boost::bind(&ControlResponseTE::HandleSetResponse, this, _1); apTerminal->BindCommand(cmd, cmd.mName); } bool LookupCommandStatus(const std::string& arArg, CommandStatus& arStatus) { #define MACRO_CHECK_STRING(name) if(arArg == #name) {arStatus = CS_##name; return true;} //this one can't be used in the macro because of a naming collision with the //terminal macro SUCCESS. if(arArg == "SUCCESS") { arStatus = CS_SUCCESS; return true; } MACRO_CHECK_STRING(TIMEOUT); MACRO_CHECK_STRING(NO_SELECT); MACRO_CHECK_STRING(FORMAT_ERROR); MACRO_CHECK_STRING(NOT_SUPPORTED); MACRO_CHECK_STRING(ALREADY_ACTIVE); MACRO_CHECK_STRING(HARDWARE_ERROR); MACRO_CHECK_STRING(LOCAL); MACRO_CHECK_STRING(TOO_MANY_OPS); MACRO_CHECK_STRING(NOT_AUTHORIZED); return false; } retcode ControlResponseTE :: HandleSetResponse(std::vector<std::string>& arArgs) { if(arArgs.size() != 3) return BAD_ARGUMENTS; int type; if(arArgs[0] == "all") type = 2; else if(arArgs[0] == "bo") type = 0; else if(arArgs[0] == "st") type = 1; else return BAD_ARGUMENTS; int index; if(arArgs[1] == "all") index = -1; else if(!Parsing::Get(arArgs[1], index)) return BAD_ARGUMENTS; CommandStatus response; int temp; if(Parsing::Get(arArgs[2], temp)) { response = static_cast<CommandStatus>(temp); } else if(!LookupCommandStatus(arArgs[2], response)) return BAD_ARGUMENTS; if(type == 0 || type == 2) mHandler.SetResponseCode(true, index, response); if(type == 1 || type == 2) mHandler.SetResponseCode(false, index, response); return SUCCESS; } } <commit_msg>Fix for issue 12<commit_after>#include "ControlResponseTE.h" #include <APL/Logger.h> #include <APL/Exception.h> #include <APL/Parsing.h> namespace apl { CommandResponder :: CommandResponder(Logger* apLogger, bool aLinkStatuses, IDataObserver* apObs) : Loggable(apLogger), mpObs(apObs), mLinkStatuses(aLinkStatuses) { } void CommandResponder :: AcceptCommand(const BinaryOutput& ctrl, size_t i, int aSequence, IResponseAcceptor* apRspAcceptor) { CriticalSection c(&mLock); CommandResponse cr; cr.mResult = this->HandleControl(ctrl, i); apRspAcceptor->AcceptResponse(cr, aSequence); } void CommandResponder :: AcceptCommand(const Setpoint& ctrl, size_t i, int aSequence, IResponseAcceptor* apRspAcceptor) { CriticalSection c(&mLock); CommandResponse cr; cr.mResult = this->HandleControl(ctrl, i); apRspAcceptor->AcceptResponse(cr, aSequence); } CommandStatus CommandResponder :: HandleControl(const BinaryOutput& aControl, size_t aIndex) { CommandStatus cs = CS_TOO_MANY_OPS; if ( mLinkStatuses && (aControl.GetCode() == CC_LATCH_ON || aControl.GetCode() == CC_LATCH_OFF)) { try { Transaction t(mpObs); bool val = aControl.GetCode() == CC_LATCH_ON ? true : false; mpObs->Update(ControlStatus(val, ControlStatus::ONLINE), aIndex); cs = CS_SUCCESS; LOG_BLOCK(LEV_INFO, "Updated ControlStatus " << aIndex << " with " << val << "." ); } catch (Exception& ex) { LOG_BLOCK(LEV_WARNING, "Failure trying to update point in response to control. " << ex.GetErrorString()); cs = CS_NOT_SUPPORTED; } } else { cs = GetResponseCode(true, aIndex); } LOG_BLOCK(LEV_INFO, "[" << aIndex << "] - " << aControl.ToString() << " returning " << ToString(cs)); return cs; } CommandStatus CommandResponder :: HandleControl(const Setpoint& aControl, size_t aIndex) { CommandStatus cs = CS_TOO_MANY_OPS; if ( mLinkStatuses ) { try { Transaction t(mpObs); mpObs->Update(SetpointStatus(aControl.GetValue(), SetpointStatus::ONLINE), aIndex); cs = CS_SUCCESS; LOG_BLOCK(LEV_INFO, "Updated SetpointStatus " << aIndex << " with " << aControl.GetValue() << "." ); } catch (Exception& ex) { LOG_BLOCK(LEV_WARNING, "Failure trying to update point in response to control. " << ex.GetErrorString()); cs = CS_NOT_SUPPORTED; } } else { cs = GetResponseCode(false, aIndex); } LOG_BLOCK(LEV_INFO, "[" << aIndex << "] - " << aControl.ToString() << " returning " << ToString(cs)); return cs; } void CommandResponder :: SetResponseCode(bool aType, size_t aIndex, CommandStatus aCode) { CriticalSection c(&mLock); CommandMap& m = (aType) ? mBinaryResponses : mSetpointResponses; CommandMap::iterator iter = m.find(aIndex); if(iter != m.end()) iter->second = aCode; else m[aIndex] = aCode; } CommandStatus CommandResponder :: GetResponseCode(bool aType, size_t aIndex) { CommandMap& m = (aType) ? mBinaryResponses : mSetpointResponses; // check for specific return code for this index. CommandMap::iterator iter = m.find(aIndex); if(iter != m.end()) return iter->second; return CS_SUCCESS; //return default } ControlResponseTE :: ControlResponseTE(Logger* apLogger, bool aLinkStatuses, IDataObserver* apObs) : mHandler(apLogger, aLinkStatuses, apObs) { } void ControlResponseTE :: _BindToTerminal(ITerminal* apTerminal) { CommandNode cmd; cmd.mName = "response"; cmd.mUsage = "response [bo|st|all] [all|#] [code]"; cmd.mDesc = "Sets the response code we will use to respond to the incoming commands.\nYou can use return code name or index: SUCCESS, TIMEOUT, NO_SELECT, FORMAT_ERROR, NOT_SUPPORTED, ALREADY_ACTIVE, HARDWARE_ERROR, LOCAL, TOO_MANY_OPS, NOT_AUTHORIZED."; cmd.mHandler = boost::bind(&ControlResponseTE::HandleSetResponse, this, _1); apTerminal->BindCommand(cmd, cmd.mName); } bool LookupCommandStatus(const std::string& arArg, CommandStatus& arStatus) { #define MACRO_CHECK_STRING(name) if(arArg == #name) {arStatus = CS_##name; return true;} //this one can't be used in the macro because of a naming collision with the //terminal macro SUCCESS. if(arArg == "SUCCESS") { arStatus = CS_SUCCESS; return true; } MACRO_CHECK_STRING(TIMEOUT); MACRO_CHECK_STRING(NO_SELECT); MACRO_CHECK_STRING(FORMAT_ERROR); MACRO_CHECK_STRING(NOT_SUPPORTED); MACRO_CHECK_STRING(ALREADY_ACTIVE); MACRO_CHECK_STRING(HARDWARE_ERROR); MACRO_CHECK_STRING(LOCAL); MACRO_CHECK_STRING(TOO_MANY_OPS); MACRO_CHECK_STRING(NOT_AUTHORIZED); return false; } retcode ControlResponseTE :: HandleSetResponse(std::vector<std::string>& arArgs) { if(arArgs.size() != 3) return BAD_ARGUMENTS; int type; if(arArgs[0] == "all") type = 2; else if(arArgs[0] == "bo") type = 0; else if(arArgs[0] == "st") type = 1; else return BAD_ARGUMENTS; int index; if(arArgs[1] == "all") index = -1; else if(!Parsing::Get(arArgs[1], index)) return BAD_ARGUMENTS; CommandStatus response; int temp; if(Parsing::Get(arArgs[2], temp)) { response = static_cast<CommandStatus>(temp); } else if(!LookupCommandStatus(arArgs[2], response)) return BAD_ARGUMENTS; if(type == 0 || type == 2) mHandler.SetResponseCode(true, index, response); if(type == 1 || type == 2) mHandler.SetResponseCode(false, index, response); return SUCCESS; } } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief ルネサス RX 選択 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/byte_order.h" #include "common/vect.h" #include "common/delay.hpp" #include "common/device.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #if defined(SIG_RX63T) #include "RX600/cmt.hpp" #include "RX63T/system.hpp" #include "RX63T/sci.hpp" #include "RX63T/power_cfg.hpp" #elif defined(SIG_RX24T) #include "RX24T/system.hpp" #include "RX24T/system_io.hpp" #include "RX24T/dtc.hpp" #include "RX24T/mtu3.hpp" #include "RX24T/poe3.hpp" #include "RX24T/gpt.hpp" #include "RX24T/tmr.hpp" #include "RX600/cmt.hpp" #include "RX24T/sci.hpp" #include "RX24T/riic.hpp" #include "RX24T/rspi.hpp" #include "RX24T/crc.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/adc_io.hpp" #include "RX24T/da.hpp" #include "RX600/cmpc.hpp" #include "RX24T/flash.hpp" #include "RX24T/flash_io.hpp" #elif defined(SIG_RX64M) || defined(SIG_RX71M) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/cmtw.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX65N) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/cmtw.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX65x/s12adf.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX65x/glcdc.hpp" #include "RX65x/glcdc_io.hpp" #include "RX65x/drw2d.hpp" #include "RX65x/drw2d_mgr.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX66T) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/mpc.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" // #include "RX65x/s12adf.hpp" // #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/usb.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/cmpc.hpp" #else # error "renesas.hpp: Requires SIG_XXX to be defined" #endif #include "RX600/doc.hpp" <commit_msg>update: mpu.hpp include path<commit_after>#pragma once //=====================================================================// /*! @file @brief ルネサス RX 選択 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/byte_order.h" #include "common/vect.h" #include "common/delay.hpp" #include "common/device.hpp" #include "RX600/port.hpp" #include "RX600/bus.hpp" #if defined(SIG_RX63T) #include "RX600/cmt.hpp" #include "RX63T/system.hpp" #include "RX63T/sci.hpp" #include "RX63T/power_cfg.hpp" #elif defined(SIG_RX24T) #include "RX24T/system.hpp" #include "RX24T/system_io.hpp" #include "RX24T/dtc.hpp" #include "RX24T/mtu3.hpp" #include "RX24T/poe3.hpp" #include "RX24T/gpt.hpp" #include "RX24T/tmr.hpp" #include "RX600/cmt.hpp" #include "RX24T/sci.hpp" #include "RX24T/riic.hpp" #include "RX24T/rspi.hpp" #include "RX24T/crc.hpp" #include "RX24T/s12ad.hpp" #include "RX24T/adc_io.hpp" #include "RX24T/da.hpp" #include "RX600/cmpc.hpp" #include "RX24T/flash.hpp" #include "RX24T/flash_io.hpp" #elif defined(SIG_RX64M) || defined(SIG_RX71M) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/cmtw.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX600/s12adc.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/ssi.hpp" #include "RX600/src.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX600/ssi_io.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX65N) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/exdmac.hpp" #include "RX600/mpc.hpp" #include "RX600/tpu.hpp" #include "RX600/cmt.hpp" #include "RX600/cmtw.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/scif.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" #include "RX600/qspi.hpp" #include "RX65x/s12adf.hpp" #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/dac_out.hpp" #include "RX600/sdram.hpp" #include "RX600/etherc.hpp" #include "RX600/edmac.hpp" #include "RX600/usb.hpp" #include "RX600/rtc.hpp" #include "RX600/rtc_io.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/ether_io.hpp" #include "RX600/sdhi.hpp" #include "RX600/sdhi_io.hpp" #include "RX600/standby_ram.hpp" #include "RX65x/glcdc.hpp" #include "RX65x/glcdc_io.hpp" #include "RX65x/drw2d.hpp" #include "RX65x/drw2d_mgr.hpp" #include "RX600/dmac_mgr.hpp" #elif defined(SIG_RX66T) #include "RX600/system.hpp" #include "RX600/system_io.hpp" #include "RX600/dmac.hpp" #include "RX600/mpc.hpp" #include "RX600/cmt.hpp" #include "RX600/mtu3.hpp" #include "RX600/sci.hpp" #include "RX600/riic.hpp" #include "RX600/can.hpp" #include "RX600/rspi.hpp" // #include "RX65x/s12adf.hpp" // #include "RX600/adc_io.hpp" #include "RX600/r12da.hpp" #include "RX600/usb.hpp" #include "RX600/wdta.hpp" #include "RX600/flash.hpp" #include "RX600/flash_io.hpp" #include "RX600/cmpc.hpp" #else # error "renesas.hpp: Requires SIG_XXX to be defined" #endif #include "RX600/mpu.hpp" #include "RX600/doc.hpp" <|endoftext|>
<commit_before>#ifndef XGBOOST_IO_SIMPLE_DMATRIX_INL_HPP_ #define XGBOOST_IO_SIMPLE_DMATRIX_INL_HPP_ /*! * \file simple_dmatrix-inl.hpp * \brief simple implementation of DMatrixS that can be used * the data format of xgboost is templatized, which means it can accept * any data structure that implements the function defined by FMatrix * this file is a specific implementation of input data structure that can be used by BoostLearner * \author Tianqi Chen */ #include <string> #include <cstring> #include <vector> #include <algorithm> #include "../data.h" #include "../utils/utils.h" #include "../learner/dmatrix.h" #include "./io.h" #include "./simple_fmatrix-inl.hpp" namespace xgboost { namespace io { /*! \brief implementation of DataMatrix, in CSR format */ class DMatrixSimple : public DataMatrix { public: // constructor DMatrixSimple(void) : DataMatrix(kMagic) { fmat_ = new FMatrixS(new OneBatchIter(this)); this->Clear(); } // virtual destructor virtual ~DMatrixSimple(void) { delete fmat_; } virtual IFMatrix *fmat(void) const { return fmat_; } /*! \brief clear the storage */ inline void Clear(void) { row_ptr_.clear(); row_ptr_.push_back(0); row_data_.clear(); info.Clear(); } /*! \brief copy content data from source matrix */ inline void CopyFrom(const DataMatrix &src) { this->info = src.info; this->Clear(); // clone data content in thos matrix utils::IIterator<RowBatch> *iter = src.fmat()->RowIterator(); iter->BeforeFirst(); while (iter->Next()) { const RowBatch &batch = iter->Value(); for (size_t i = 0; i < batch.size; ++i) { RowBatch::Inst inst = batch[i]; row_data_.resize(row_data_.size() + inst.length); memcpy(&row_data_[row_ptr_.back()], inst.data, sizeof(RowBatch::Entry) * inst.length); row_ptr_.push_back(row_ptr_.back() + inst.length); } } } /*! * \brief add a row to the matrix * \param feats features * \return the index of added row */ inline size_t AddRow(const std::vector<RowBatch::Entry> &feats) { for (size_t i = 0; i < feats.size(); ++i) { row_data_.push_back(feats[i]); info.info.num_col = std::max(info.info.num_col, static_cast<size_t>(feats[i].index+1)); } row_ptr_.push_back(row_ptr_.back() + feats.size()); info.info.num_row += 1; return row_ptr_.size() - 2; } /*! * \brief load from text file * \param fname name of text data * \param silent whether print information or not */ inline void LoadText(const char* fname, bool silent = false) { this->Clear(); FILE* file = utils::FopenCheck(fname, "r"); float label; bool init = true; char tmp[1024]; std::vector<RowBatch::Entry> feats; while (fscanf(file, "%s", tmp) == 1) { RowBatch::Entry e; if (sscanf(tmp, "%u:%f", &e.index, &e.fvalue) == 2) { feats.push_back(e); } else { if (!init) { info.labels.push_back(label); this->AddRow(feats); } feats.clear(); utils::Check(sscanf(tmp, "%f", &label) == 1, "invalid LibSVM format"); init = false; } } info.labels.push_back(label); this->AddRow(feats); if (!silent) { printf("%lux%lu matrix with %lu entries is loaded from %s\n", static_cast<unsigned long>(info.num_row()), static_cast<unsigned long>(info.num_col()), static_cast<unsigned long>(row_data_.size()), fname); } fclose(file); // try to load in additional file std::string name = fname; std::string gname = name + ".group"; if (info.TryLoadGroup(gname.c_str(), silent)) { utils::Check(info.group_ptr.back() == info.num_row(), "DMatrix: group data does not match the number of rows in features"); } std::string wname = name + ".weight"; if (info.TryLoadFloatInfo("weight", wname.c_str(), silent)) { utils::Check(info.weights.size() == info.num_row(), "DMatrix: weight data does not match the number of rows in features"); } std::string mname = name + ".base_margin"; if (info.TryLoadFloatInfo("base_margin", mname.c_str(), silent)) { } } /*! * \brief load from binary file * \param fname name of binary data * \param silent whether print information or not * \return whether loading is success */ inline bool LoadBinary(const char* fname, bool silent = false) { FILE *fp = fopen64(fname, "rb"); if (fp == NULL) return false; utils::FileStream fs(fp); this->LoadBinary(fs, silent, fname); fs.Close(); return true; } /*! * \brief load from binary stream * \param fs input file stream * \param silent whether print information during loading * \param fname file name, used to print message */ inline void LoadBinary(utils::IStream &fs, bool silent = false, const char *fname = NULL) { int magic; utils::Check(fs.Read(&magic, sizeof(magic)) != 0, "invalid input file format"); utils::Check(magic == kMagic, "invalid format,magic number mismatch"); info.LoadBinary(fs); FMatrixS::LoadBinary(fs, &row_ptr_, &row_data_); fmat_->LoadColAccess(fs); if (!silent) { printf("%lux%lu matrix with %lu entries is loaded", static_cast<unsigned long>(info.num_row()), static_cast<unsigned long>(info.num_col()), static_cast<unsigned long>(row_data_.size())); if (fname != NULL) { printf(" from %s\n", fname); } else { printf("\n"); } if (info.group_ptr.size() != 0) { printf("data contains %u groups\n", (unsigned)info.group_ptr.size()-1); } } } /*! * \brief save to binary file * \param fname name of binary data * \param silent whether print information or not */ inline void SaveBinary(const char* fname, bool silent = false) const { utils::FileStream fs(utils::FopenCheck(fname, "wb")); int magic = kMagic; fs.Write(&magic, sizeof(magic)); info.SaveBinary(fs); FMatrixS::SaveBinary(fs, row_ptr_, row_data_); fmat_->SaveColAccess(fs); fs.Close(); if (!silent) { printf("%lux%lu matrix with %lu entries is saved to %s\n", static_cast<unsigned long>(info.num_row()), static_cast<unsigned long>(info.num_col()), static_cast<unsigned long>(row_data_.size()), fname); if (info.group_ptr.size() != 0) { printf("data contains %u groups\n", static_cast<unsigned>(info.group_ptr.size()-1)); } } } /*! * \brief cache load data given a file name, if filename ends with .buffer, direct load binary * otherwise the function will first check if fname + '.buffer' exists, * if binary buffer exists, it will reads from binary buffer, otherwise, it will load from text file, * and try to create a buffer file * \param fname name of binary data * \param silent whether print information or not * \param savebuffer whether do save binary buffer if it is text */ inline void CacheLoad(const char *fname, bool silent = false, bool savebuffer = true) { size_t len = strlen(fname); if (len > 8 && !strcmp(fname + len - 7, ".buffer")) { if (!this->LoadBinary(fname, silent)) { utils::Error("can not open file \"%s\"", fname); } return; } char bname[1024]; snprintf(bname, sizeof(bname), "%s.buffer", fname); if (!this->LoadBinary(bname, silent)) { this->LoadText(fname, silent); if (savebuffer) this->SaveBinary(bname, silent); } } // data fields /*! \brief row pointer of CSR sparse storage */ std::vector<size_t> row_ptr_; /*! \brief data in the row */ std::vector<RowBatch::Entry> row_data_; /*! \brief the real fmatrix */ FMatrixS *fmat_; /*! \brief magic number used to identify DMatrix */ static const int kMagic = 0xffffab01; protected: // one batch iterator that return content in the matrix struct OneBatchIter: utils::IIterator<RowBatch> { explicit OneBatchIter(DMatrixSimple *parent) : at_first_(true), parent_(parent) {} virtual ~OneBatchIter(void) {} virtual void BeforeFirst(void) { at_first_ = true; } virtual bool Next(void) { if (!at_first_) return false; at_first_ = false; batch_.size = parent_->row_ptr_.size() - 1; batch_.base_rowid = 0; batch_.ind_ptr = &parent_->row_ptr_[0]; batch_.data_ptr = &parent_->row_data_[0]; return true; } virtual const RowBatch &Value(void) const { return batch_; } private: // whether is at first bool at_first_; // pointer to parient DMatrixSimple *parent_; // temporal space for batch RowBatch batch_; }; }; } // namespace io } // namespace xgboost #endif // namespace XGBOOST_IO_SIMPLE_DMATRIX_INL_HPP_ <commit_msg>fix indent<commit_after>#ifndef XGBOOST_IO_SIMPLE_DMATRIX_INL_HPP_ #define XGBOOST_IO_SIMPLE_DMATRIX_INL_HPP_ /*! * \file simple_dmatrix-inl.hpp * \brief simple implementation of DMatrixS that can be used * the data format of xgboost is templatized, which means it can accept * any data structure that implements the function defined by FMatrix * this file is a specific implementation of input data structure that can be used by BoostLearner * \author Tianqi Chen */ #include <string> #include <cstring> #include <vector> #include <algorithm> #include "../data.h" #include "../utils/utils.h" #include "../learner/dmatrix.h" #include "./io.h" #include "./simple_fmatrix-inl.hpp" namespace xgboost { namespace io { /*! \brief implementation of DataMatrix, in CSR format */ class DMatrixSimple : public DataMatrix { public: // constructor DMatrixSimple(void) : DataMatrix(kMagic) { fmat_ = new FMatrixS(new OneBatchIter(this)); this->Clear(); } // virtual destructor virtual ~DMatrixSimple(void) { delete fmat_; } virtual IFMatrix *fmat(void) const { return fmat_; } /*! \brief clear the storage */ inline void Clear(void) { row_ptr_.clear(); row_ptr_.push_back(0); row_data_.clear(); info.Clear(); } /*! \brief copy content data from source matrix */ inline void CopyFrom(const DataMatrix &src) { this->info = src.info; this->Clear(); // clone data content in thos matrix utils::IIterator<RowBatch> *iter = src.fmat()->RowIterator(); iter->BeforeFirst(); while (iter->Next()) { const RowBatch &batch = iter->Value(); for (size_t i = 0; i < batch.size; ++i) { RowBatch::Inst inst = batch[i]; row_data_.resize(row_data_.size() + inst.length); memcpy(&row_data_[row_ptr_.back()], inst.data, sizeof(RowBatch::Entry) * inst.length); row_ptr_.push_back(row_ptr_.back() + inst.length); } } } /*! * \brief add a row to the matrix * \param feats features * \return the index of added row */ inline size_t AddRow(const std::vector<RowBatch::Entry> &feats) { for (size_t i = 0; i < feats.size(); ++i) { row_data_.push_back(feats[i]); info.info.num_col = std::max(info.info.num_col, static_cast<size_t>(feats[i].index+1)); } row_ptr_.push_back(row_ptr_.back() + feats.size()); info.info.num_row += 1; return row_ptr_.size() - 2; } /*! * \brief load from text file * \param fname name of text data * \param silent whether print information or not */ inline void LoadText(const char* fname, bool silent = false) { this->Clear(); FILE* file = utils::FopenCheck(fname, "r"); float label; bool init = true; char tmp[1024]; std::vector<RowBatch::Entry> feats; while (fscanf(file, "%s", tmp) == 1) { RowBatch::Entry e; if (sscanf(tmp, "%u:%f", &e.index, &e.fvalue) == 2) { feats.push_back(e); } else { if (!init) { info.labels.push_back(label); this->AddRow(feats); } feats.clear(); utils::Check(sscanf(tmp, "%f", &label) == 1, "invalid LibSVM format"); init = false; } } info.labels.push_back(label); this->AddRow(feats); if (!silent) { printf("%lux%lu matrix with %lu entries is loaded from %s\n", static_cast<unsigned long>(info.num_row()), static_cast<unsigned long>(info.num_col()), static_cast<unsigned long>(row_data_.size()), fname); } fclose(file); // try to load in additional file std::string name = fname; std::string gname = name + ".group"; if (info.TryLoadGroup(gname.c_str(), silent)) { utils::Check(info.group_ptr.back() == info.num_row(), "DMatrix: group data does not match the number of rows in features"); } std::string wname = name + ".weight"; if (info.TryLoadFloatInfo("weight", wname.c_str(), silent)) { utils::Check(info.weights.size() == info.num_row(), "DMatrix: weight data does not match the number of rows in features"); } std::string mname = name + ".base_margin"; if (info.TryLoadFloatInfo("base_margin", mname.c_str(), silent)) { } } /*! * \brief load from binary file * \param fname name of binary data * \param silent whether print information or not * \return whether loading is success */ inline bool LoadBinary(const char* fname, bool silent = false) { FILE *fp = fopen64(fname, "rb"); if (fp == NULL) return false; utils::FileStream fs(fp); this->LoadBinary(fs, silent, fname); fs.Close(); return true; } /*! * \brief load from binary stream * \param fs input file stream * \param silent whether print information during loading * \param fname file name, used to print message */ inline void LoadBinary(utils::IStream &fs, bool silent = false, const char *fname = NULL) { int magic; utils::Check(fs.Read(&magic, sizeof(magic)) != 0, "invalid input file format"); utils::Check(magic == kMagic, "invalid format,magic number mismatch"); info.LoadBinary(fs); FMatrixS::LoadBinary(fs, &row_ptr_, &row_data_); fmat_->LoadColAccess(fs); if (!silent) { printf("%lux%lu matrix with %lu entries is loaded", static_cast<unsigned long>(info.num_row()), static_cast<unsigned long>(info.num_col()), static_cast<unsigned long>(row_data_.size())); if (fname != NULL) { printf(" from %s\n", fname); } else { printf("\n"); } if (info.group_ptr.size() != 0) { printf("data contains %u groups\n", (unsigned)info.group_ptr.size()-1); } } } /*! * \brief save to binary file * \param fname name of binary data * \param silent whether print information or not */ inline void SaveBinary(const char* fname, bool silent = false) const { utils::FileStream fs(utils::FopenCheck(fname, "wb")); int magic = kMagic; fs.Write(&magic, sizeof(magic)); info.SaveBinary(fs); FMatrixS::SaveBinary(fs, row_ptr_, row_data_); fmat_->SaveColAccess(fs); fs.Close(); if (!silent) { printf("%lux%lu matrix with %lu entries is saved to %s\n", static_cast<unsigned long>(info.num_row()), static_cast<unsigned long>(info.num_col()), static_cast<unsigned long>(row_data_.size()), fname); if (info.group_ptr.size() != 0) { printf("data contains %u groups\n", static_cast<unsigned>(info.group_ptr.size()-1)); } } } /*! * \brief cache load data given a file name, if filename ends with .buffer, direct load binary * otherwise the function will first check if fname + '.buffer' exists, * if binary buffer exists, it will reads from binary buffer, otherwise, it will load from text file, * and try to create a buffer file * \param fname name of binary data * \param silent whether print information or not * \param savebuffer whether do save binary buffer if it is text */ inline void CacheLoad(const char *fname, bool silent = false, bool savebuffer = true) { size_t len = strlen(fname); if (len > 8 && !strcmp(fname + len - 7, ".buffer")) { if (!this->LoadBinary(fname, silent)) { utils::Error("can not open file \"%s\"", fname); } return; } char bname[1024]; snprintf(bname, sizeof(bname), "%s.buffer", fname); if (!this->LoadBinary(bname, silent)) { this->LoadText(fname, silent); if (savebuffer) this->SaveBinary(bname, silent); } } // data fields /*! \brief row pointer of CSR sparse storage */ std::vector<size_t> row_ptr_; /*! \brief data in the row */ std::vector<RowBatch::Entry> row_data_; /*! \brief the real fmatrix */ FMatrixS *fmat_; /*! \brief magic number used to identify DMatrix */ static const int kMagic = 0xffffab01; protected: // one batch iterator that return content in the matrix struct OneBatchIter: utils::IIterator<RowBatch> { explicit OneBatchIter(DMatrixSimple *parent) : at_first_(true), parent_(parent) {} virtual ~OneBatchIter(void) {} virtual void BeforeFirst(void) { at_first_ = true; } virtual bool Next(void) { if (!at_first_) return false; at_first_ = false; batch_.size = parent_->row_ptr_.size() - 1; batch_.base_rowid = 0; batch_.ind_ptr = &parent_->row_ptr_[0]; batch_.data_ptr = &parent_->row_data_[0]; return true; } virtual const RowBatch &Value(void) const { return batch_; } private: // whether is at first bool at_first_; // pointer to parient DMatrixSimple *parent_; // temporal space for batch RowBatch batch_; }; }; } // namespace io } // namespace xgboost #endif // namespace XGBOOST_IO_SIMPLE_DMATRIX_INL_HPP_ <|endoftext|>
<commit_before>/* ************************************************************************ * Copyright 2016 Advanced Micro Devices, Inc. * ************************************************************************ */ #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include <limits> // std::numeric_limits<T>::epsilon(); #include <cmath> // std::abs #include "rocblas.hpp" #include "arg_check.h" #include "rocblas_test_unique_ptr.hpp" #include "utility.h" #include "cblas_interface.h" #include "norm.h" #include "unit.h" #include "flops.h" #define ERROR_EPS_MULTIPLIER 40 #define RESIDUAL_EPS_MULTIPLIER 20 using namespace std; template <typename T> void printMatrix(const char* name, T* A, rocblas_int m, rocblas_int n, rocblas_int lda) { printf("---------- %s ----------\n", name); for( int i = 0; i < m; i++) { for( int j = 0; j < n; j++) { printf("%f ",A[i + j * lda]); } printf("\n"); } } template<typename T> rocblas_status testing_trsm(Arguments argus) { rocblas_int M = argus.M; rocblas_int N = argus.N; rocblas_int lda = argus.lda; rocblas_int ldb = argus.ldb; char char_side = argus.side_option; char char_uplo = argus.uplo_option; char char_transA = argus.transA_option; char char_diag = argus.diag_option; T alpha = argus.alpha; rocblas_int safe_size = 100; // arbitrarily set to 100 rocblas_side side = char2rocblas_side(char_side); rocblas_fill uplo = char2rocblas_fill(char_uplo); rocblas_operation transA = char2rocblas_operation(char_transA); rocblas_diagonal diag = char2rocblas_diagonal(char_diag); rocblas_int K = side == rocblas_side_left ? M : N; rocblas_int size_A = lda * K; rocblas_int size_B = ldb * N; rocblas_status status; std::unique_ptr<rocblas_test::handle_struct> unique_ptr_handle(new rocblas_test::handle_struct); rocblas_handle handle = unique_ptr_handle->handle; //check here to prevent undefined memory allocation error if( M < 0 || N < 0 || lda < K || ldb < M) { auto dA_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * safe_size),rocblas_test::device_free}; auto dXorB_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * safe_size),rocblas_test::device_free}; T* dA = (T*) dA_managed.get(); T* dXorB = (T*) dXorB_managed.get(); if (!dA || !dXorB) { PRINT_IF_HIP_ERROR(hipErrorOutOfMemory); return rocblas_status_memory_error; } status = rocblas_trsm<T>(handle, side, uplo, transA, diag, M, N, &alpha, dA,lda, dXorB,ldb); trsm_arg_check(status, M, N, lda, ldb); return status; } //Naming: dK is in GPU (device) memory. hK is in CPU (host) memory vector<T> hA(size_A); vector<T> AAT(size_A); vector<T> hB(size_B); vector<T> hX(size_B); vector<T> hXorB(size_B); vector<T> cpuXorB(size_B); double gpu_time_used, cpu_time_used; double rocblas_gflops, cblas_gflops; double rocblas_error; T error_eps_multiplier = ERROR_EPS_MULTIPLIER; T residual_eps_multiplier = RESIDUAL_EPS_MULTIPLIER; T eps = std::numeric_limits<T>::epsilon(); //allocate memory on device auto dA_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * size_A),rocblas_test::device_free}; auto dXorB_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * size_B),rocblas_test::device_free}; T* dA = (T*) dA_managed.get(); T* dXorB = (T*) dXorB_managed.get(); if (!dA || !dXorB) { PRINT_IF_HIP_ERROR(hipErrorOutOfMemory); return rocblas_status_memory_error; } // Random lower triangular matrices have condition number // that grows exponentially with matrix size. Random full // matrices have condition that grows linearly with // matrix size. // // We want a triangular matrix with condition number that grows // lineary with matrix size. We start with full random matrix A. // Calculate symmetric AAT <- A A^T. Make AAT strictly diagonal // dominant. A strictly diagonal dominant matrix is SPD so we // can use Cholesky to calculate L L^T = AAT. These L factors // should have condition number approximately equal to // the condition number of the original matrix A. // initialize full random matrix hA with all entries in [1, 10] rocblas_init<T>(hA, K, K, lda); // pad untouched area into zero for(int i = K; i < lda; i++) { for(int j = 0; j < K; j++) { hA[i+j*lda] = 0.0; } } // calculate AAT = hA * hA ^ T cblas_gemm(rocblas_operation_none, rocblas_operation_transpose, K, K, K, (T)1.0, hA.data(), lda, hA.data(), lda, (T)0.0, AAT.data(), lda); // copy AAT into hA, make hA strictly diagonal dominant, and therefore SPD for(int i = 0; i < K; i++) { T t = 0.0; for(int j = 0; j < K; j++) { hA[i + j * lda] = AAT[i + j * lda]; t += AAT[i + j * lda] > 0 ? AAT[i + j * lda] : -AAT[i + j * lda]; } hA[i+i*lda] = t; } // calculate Cholesky factorization of SPD matrix hA cblas_potrf(char_uplo, K, hA.data(), lda); // make hA unit diagonal if diag == rocblas_diagonal_unit if(char_diag == 'U' || char_diag == 'u') { if('L' == char_uplo || 'l' == char_uplo) { for(int i = 0; i < K; i++) { T diag = hA[i + i * lda]; for(int j = 0; j <= i; j++) { hA[i+j*lda] = hA[i+j*lda] / diag; } } } else { for(int j = 0; j < K; j++) { T diag = hA[j + j * lda]; for(int i = 0; i <= j; i++) { hA[i+j*lda] = hA[i+j*lda] / diag; } } } } //Initial hX rocblas_init<T>(hX, M, N, ldb); //pad untouched area into zero for(int i=M;i<ldb;i++) { for(int j=0;j<N;j++) { hX[i+j*ldb] = 0.0; } } hB = hX; // Calculate hB = hA*hX; cblas_trmm<T>( side, uplo, transA, diag, M, N, 1.0/alpha, (const T*)hA.data(), lda, hB.data(), ldb); hXorB = hB; // hXorB <- B cpuXorB = hB; // cpuXorB <- B //copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dA, hA.data(), sizeof(T)*size_A, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dXorB, hXorB.data(), sizeof(T)*size_B, hipMemcpyHostToDevice)); /* ===================================================================== ROCBLAS =================================================================== */ gpu_time_used = get_time_us();// in microseconds // calculate dXorB <- A^(-1) B CHECK_ROCBLAS_ERROR(rocblas_trsm<T>(handle, side, uplo, transA, diag, M, N, &alpha, dA,lda, dXorB,ldb)); gpu_time_used = get_time_us() - gpu_time_used; rocblas_gflops = trsm_gflop_count<T> (M, N, K) / gpu_time_used * 1e6 ; //copy output from device to CPU CHECK_HIP_ERROR(hipMemcpy(hXorB.data(), dXorB, sizeof(T)*size_B, hipMemcpyDeviceToHost)); T max_err = 0.0; T max_res = 0.0; if(argus.unit_check || argus.norm_check) { // Error Check // hXorB contains calculated X, so error is hX - hXorB // err is the one norm of the scaled error for a single column // max_err is the maximum of err for all columns for (int i = 0; i < N; i++) { T err = 0.0; for (int j = 0; j < M; j++) { if(hX[j + i*ldb] != 0) { err += std::abs((hX[j + i*ldb] - hXorB[j + i*ldb]) / hX[j + i*ldb]); } else { err += std::abs(hXorB[j + i*ldb]); } } max_err = max_err > err ? max_err : err; } trsm_err_res_check<T>(max_err, M, error_eps_multiplier, eps); // Residual Check cblas_trmm<T>( side, uplo, transA, diag, M, N, 1.0/alpha, (const T*)hA.data(), lda, hXorB.data(), ldb); // hXorB <- hA * (A^(-1) B) ; // hXorB contains A * (calculated X), so residual = A * (calculated X) - B // = hXorB - hB // res is the one norm of the scaled residual for each column for (int i = 0; i < N; i++) { T res = 0.0; for (int j = 0; j < M; j++) { if(hB[j + i*ldb] != 0) { res += std::abs((hXorB[j + i*ldb] - hB[j + i*ldb]) / hB[j + i*ldb]); } else { res += std::abs(hXorB[j + i*ldb]); } } max_res = max_res > res ? max_res : res; } trsm_err_res_check<T>(max_res, M, residual_eps_multiplier, eps); } if(argus.timing) { cpu_time_used = get_time_us(); cblas_trsm<T>( side, uplo, transA, diag, M, N, alpha, (const T*)hA.data(), lda, cpuXorB.data(), ldb); cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = trsm_gflop_count<T>(M, N, K) / cpu_time_used * 1e6; //only norm_check return an norm error, unit check won't return anything cout << "M,N,lda,ldb,side,uplo,transA,diag,rocblas-Gflops,us"; if(argus.norm_check) cout << ",CPU-Gflops,us,norm-error" ; cout << endl; cout << M << ',' << N <<',' << lda <<','<< ldb <<',' << char_side << ',' << char_uplo << ',' << char_transA << ',' << char_diag << ',' << rocblas_gflops << "," << gpu_time_used; if(argus.norm_check) cout << "," << cblas_gflops << "," << cpu_time_used << "," << max_err; cout << endl; } return rocblas_status_success; } <commit_msg>trmm rocblas_pointer_mode_device<commit_after>/* ************************************************************************ * Copyright 2016 Advanced Micro Devices, Inc. * ************************************************************************ */ #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include <limits> // std::numeric_limits<T>::epsilon(); #include <cmath> // std::abs #include "rocblas.hpp" #include "arg_check.h" #include "rocblas_test_unique_ptr.hpp" #include "utility.h" #include "cblas_interface.h" #include "norm.h" #include "unit.h" #include "flops.h" #define ERROR_EPS_MULTIPLIER 40 #define RESIDUAL_EPS_MULTIPLIER 20 using namespace std; template <typename T> void printMatrix(const char* name, T* A, rocblas_int m, rocblas_int n, rocblas_int lda) { printf("---------- %s ----------\n", name); for( int i = 0; i < m; i++) { for( int j = 0; j < n; j++) { printf("%f ",A[i + j * lda]); } printf("\n"); } } template<typename T> rocblas_status testing_trsm(Arguments argus) { rocblas_int M = argus.M; rocblas_int N = argus.N; rocblas_int lda = argus.lda; rocblas_int ldb = argus.ldb; char char_side = argus.side_option; char char_uplo = argus.uplo_option; char char_transA = argus.transA_option; char char_diag = argus.diag_option; T alpha_h = argus.alpha; rocblas_int safe_size = 100; // arbitrarily set to 100 rocblas_side side = char2rocblas_side(char_side); rocblas_fill uplo = char2rocblas_fill(char_uplo); rocblas_operation transA = char2rocblas_operation(char_transA); rocblas_diagonal diag = char2rocblas_diagonal(char_diag); rocblas_int K = side == rocblas_side_left ? M : N; rocblas_int size_A = lda * K; rocblas_int size_B = ldb * N; rocblas_status status; std::unique_ptr<rocblas_test::handle_struct> unique_ptr_handle(new rocblas_test::handle_struct); rocblas_handle handle = unique_ptr_handle->handle; //check here to prevent undefined memory allocation error if( M < 0 || N < 0 || lda < K || ldb < M) { auto dA_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * safe_size),rocblas_test::device_free}; auto dXorB_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * safe_size),rocblas_test::device_free}; T* dA = (T*) dA_managed.get(); T* dXorB = (T*) dXorB_managed.get(); if (!dA || !dXorB) { PRINT_IF_HIP_ERROR(hipErrorOutOfMemory); return rocblas_status_memory_error; } CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); status = rocblas_trsm<T>(handle, side, uplo, transA, diag, M, N, &alpha_h, dA,lda, dXorB,ldb); trsm_arg_check(status, M, N, lda, ldb); return status; } //Naming: dK is in GPU (device) memory. hK is in CPU (host) memory vector<T> hA(size_A); vector<T> AAT(size_A); vector<T> hB(size_B); vector<T> hX(size_B); vector<T> hXorB_1(size_B); vector<T> hXorB_2(size_B); vector<T> cpuXorB(size_B); double gpu_time_used, cpu_time_used; double rocblas_gflops, cblas_gflops; double rocblas_error; T error_eps_multiplier = ERROR_EPS_MULTIPLIER; T residual_eps_multiplier = RESIDUAL_EPS_MULTIPLIER; T eps = std::numeric_limits<T>::epsilon(); //allocate memory on device auto dA_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * size_A),rocblas_test::device_free}; auto dXorB_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T) * size_B),rocblas_test::device_free}; auto alpha_d_managed = rocblas_unique_ptr{rocblas_test::device_malloc(sizeof(T)),rocblas_test::device_free}; T* dA = (T*) dA_managed.get(); T* dXorB = (T*) dXorB_managed.get(); T* alpha_d = (T*) alpha_d_managed.get(); if (!dA || !dXorB || !alpha_d) { PRINT_IF_HIP_ERROR(hipErrorOutOfMemory); return rocblas_status_memory_error; } // Random lower triangular matrices have condition number // that grows exponentially with matrix size. Random full // matrices have condition that grows linearly with // matrix size. // // We want a triangular matrix with condition number that grows // lineary with matrix size. We start with full random matrix A. // Calculate symmetric AAT <- A A^T. Make AAT strictly diagonal // dominant. A strictly diagonal dominant matrix is SPD so we // can use Cholesky to calculate L L^T = AAT. These L factors // should have condition number approximately equal to // the condition number of the original matrix A. // initialize full random matrix hA with all entries in [1, 10] rocblas_init<T>(hA, K, K, lda); // pad untouched area into zero for(int i = K; i < lda; i++) { for(int j = 0; j < K; j++) { hA[i+j*lda] = 0.0; } } // calculate AAT = hA * hA ^ T cblas_gemm(rocblas_operation_none, rocblas_operation_transpose, K, K, K, (T)1.0, hA.data(), lda, hA.data(), lda, (T)0.0, AAT.data(), lda); // copy AAT into hA, make hA strictly diagonal dominant, and therefore SPD for(int i = 0; i < K; i++) { T t = 0.0; for(int j = 0; j < K; j++) { hA[i + j * lda] = AAT[i + j * lda]; t += AAT[i + j * lda] > 0 ? AAT[i + j * lda] : -AAT[i + j * lda]; } hA[i+i*lda] = t; } // calculate Cholesky factorization of SPD matrix hA cblas_potrf(char_uplo, K, hA.data(), lda); // make hA unit diagonal if diag == rocblas_diagonal_unit if(char_diag == 'U' || char_diag == 'u') { if('L' == char_uplo || 'l' == char_uplo) { for(int i = 0; i < K; i++) { T diag = hA[i + i * lda]; for(int j = 0; j <= i; j++) { hA[i+j*lda] = hA[i+j*lda] / diag; } } } else { for(int j = 0; j < K; j++) { T diag = hA[j + j * lda]; for(int i = 0; i <= j; i++) { hA[i+j*lda] = hA[i+j*lda] / diag; } } } } //Initial hX rocblas_init<T>(hX, M, N, ldb); //pad untouched area into zero for(int i=M;i<ldb;i++) { for(int j=0;j<N;j++) { hX[i+j*ldb] = 0.0; } } hB = hX; // Calculate hB = hA*hX; cblas_trmm<T>( side, uplo, transA, diag, M, N, 1.0/alpha_h, (const T*)hA.data(), lda, hB.data(), ldb); hXorB_1 = hB; // hXorB <- B hXorB_2 = hB; // hXorB <- B cpuXorB = hB; // cpuXorB <- B //copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dA, hA.data(), sizeof(T)*size_A, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dXorB, hXorB_1.data(), sizeof(T)*size_B, hipMemcpyHostToDevice)); T max_err_1 = 0.0; T max_err_2 = 0.0; T max_res_1 = 0.0; T max_res_2 = 0.0; if(argus.unit_check || argus.norm_check) { // calculate dXorB <- A^(-1) B rocblas_device_pointer_host CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); CHECK_HIP_ERROR(hipMemcpy(dXorB, hXorB_1.data(), sizeof(T)*size_B, hipMemcpyHostToDevice)); CHECK_ROCBLAS_ERROR(rocblas_trsm<T>(handle, side, uplo, transA, diag, M, N, &alpha_h, dA,lda, dXorB, ldb)); CHECK_HIP_ERROR(hipMemcpy(hXorB_1.data(), dXorB, sizeof(T)*size_B, hipMemcpyDeviceToHost)); // calculate dXorB <- A^(-1) B rocblas_device_pointer_device CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_device)); CHECK_HIP_ERROR(hipMemcpy(dXorB, hXorB_2.data(), sizeof(T)*size_B, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(alpha_d, &alpha_h, sizeof(T), hipMemcpyHostToDevice)); CHECK_ROCBLAS_ERROR(rocblas_trsm<T>(handle, side, uplo, transA, diag, M, N, alpha_d, dA,lda, dXorB, ldb)); CHECK_HIP_ERROR(hipMemcpy(hXorB_2.data(), dXorB, sizeof(T)*size_B, hipMemcpyDeviceToHost)); // Error Check // hXorB contains calculated X, so error is hX - hXorB // err is the one norm of the scaled error for a single column // max_err is the maximum of err for all columns for (int i = 0; i < N; i++) { T err_1 = 0.0; T err_2 = 0.0; for (int j = 0; j < M; j++) { if(hX[j + i*ldb] != 0) { err_1 += std::abs((hX[j + i*ldb] - hXorB_1[j + i*ldb]) / hX[j + i*ldb]); err_2 += std::abs((hX[j + i*ldb] - hXorB_2[j + i*ldb]) / hX[j + i*ldb]); } else { err_1 += std::abs(hXorB_1[j + i*ldb]); err_2 += std::abs(hXorB_2[j + i*ldb]); } } max_err_1 = max_err_1 > err_1 ? max_err_1 : err_1; max_err_2 = max_err_2 > err_2 ? max_err_2 : err_2; } trsm_err_res_check<T>(max_err_1, M, error_eps_multiplier, eps); trsm_err_res_check<T>(max_err_2, M, error_eps_multiplier, eps); // Residual Check // hXorB <- hA * (A^(-1) B) ; cblas_trmm<T>( side, uplo, transA, diag, M, N, 1.0/alpha_h, (const T*)hA.data(), lda, hXorB_1.data(), ldb); cblas_trmm<T>( side, uplo, transA, diag, M, N, 1.0/alpha_h, (const T*)hA.data(), lda, hXorB_2.data(), ldb); // hXorB contains A * (calculated X), so residual = A * (calculated X) - B // = hXorB - hB // res is the one norm of the scaled residual for each column for (int i = 0; i < N; i++) { T res_1 = 0.0; T res_2 = 0.0; for (int j = 0; j < M; j++) { if(hB[j + i*ldb] != 0) { res_1 += std::abs((hXorB_1[j + i*ldb] - hB[j + i*ldb]) / hB[j + i*ldb]); res_2 += std::abs((hXorB_2[j + i*ldb] - hB[j + i*ldb]) / hB[j + i*ldb]); } else { res_1 += std::abs(hXorB_1[j + i*ldb]); res_2 += std::abs(hXorB_2[j + i*ldb]); } } max_res_1 = max_res_1 > res_1 ? max_res_1 : res_1; max_res_2 = max_res_2 > res_2 ? max_res_2 : res_2; } trsm_err_res_check<T>(max_res_1, M, residual_eps_multiplier, eps); trsm_err_res_check<T>(max_res_2, M, residual_eps_multiplier, eps); } if(argus.timing) { // GPU rocBLAS CHECK_HIP_ERROR(hipMemcpy(dXorB, hXorB_1.data(), sizeof(T)*size_B, hipMemcpyHostToDevice)); gpu_time_used = get_time_us();// in microseconds CHECK_ROCBLAS_ERROR(rocblas_set_pointer_mode(handle, rocblas_pointer_mode_host)); CHECK_ROCBLAS_ERROR(rocblas_trsm<T>(handle, side, uplo, transA, diag, M, N, &alpha_h, dA,lda, dXorB,ldb)); gpu_time_used = get_time_us() - gpu_time_used; rocblas_gflops = trsm_gflop_count<T> (M, N, K) / gpu_time_used * 1e6 ; // CPU cblas cpu_time_used = get_time_us(); cblas_trsm<T>(side, uplo, transA, diag, M, N, alpha_h, (const T*)hA.data(), lda, cpuXorB.data(), ldb); cpu_time_used = get_time_us() - cpu_time_used; cblas_gflops = trsm_gflop_count<T>(M, N, K) / cpu_time_used * 1e6; //only norm_check return an norm error, unit check won't return anything cout << "M,N,lda,ldb,side,uplo,transA,diag,rocblas-Gflops,us"; if(argus.norm_check) cout << ",CPU-Gflops,us,norm_error_host_ptr,norm_error_dev_ptr" ; cout << endl; cout << M << ',' << N <<',' << lda <<','<< ldb <<',' << char_side << ',' << char_uplo << ',' << char_transA << ',' << char_diag << ',' << rocblas_gflops << "," << gpu_time_used; if(argus.norm_check) cout << "," << cblas_gflops << "," << cpu_time_used << "," << max_err_1 << "," << max_err_2; cout << endl; } return rocblas_status_success; } <|endoftext|>
<commit_before>/* * Silly subclass of CTreeCtrl just to implement Drag&Drop. * * Based on MFC sample code from CMNCTRL1 */ #include "stdafx.h" #include "MyTreeCtrl.h" #include "DboxMain.h" #include "corelib/ItemData.h" #include "corelib/MyString.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static const TCHAR GROUP_SEP = TCHAR('.'); CMyTreeCtrl::CMyTreeCtrl() : m_bDragging(false), m_pimagelist(NULL) { } CMyTreeCtrl::~CMyTreeCtrl() { delete m_pimagelist; } BEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl) //{{AFX_MSG_MAP(CMyTreeCtrl) ON_NOTIFY_REFLECT(TVN_BEGINLABELEDIT, OnBeginLabelEdit) ON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndLabelEdit) ON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBeginDrag) ON_WM_MOUSEMOVE() ON_WM_DESTROY() ON_WM_LBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CMyTreeCtrl::OnDestroy() { CImageList *pimagelist; pimagelist = GetImageList(TVSIL_NORMAL); if (pimagelist != NULL) { pimagelist->DeleteImageList(); delete pimagelist; } } void CMyTreeCtrl::SetNewStyle(long lStyleMask, BOOL bSetBits) { long lStyleOld; lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE); lStyleOld &= ~lStyleMask; if (bSetBits) lStyleOld |= lStyleMask; SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld); SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); } void CMyTreeCtrl::UpdateLeafsGroup(HTREEITEM hItem, CString prefix) { // Starting with hItem, update the Group field of all of hItem's // children. Called after a label has been edited. if (IsLeafNode(hItem)) { DWORD itemData = GetItemData(hItem); ASSERT(itemData != NULL); CItemData *ci = (CItemData *)itemData; ci->SetGroup(CMyString(prefix)); } else { // update prefix with current group name and recurse if (!prefix.IsEmpty()) prefix += GROUP_SEP; prefix += GetItemText(hItem); HTREEITEM child; for(child = GetChildItem(hItem); child != NULL; child = GetNextSiblingItem(child)) { UpdateLeafsGroup(child, prefix); } } } void CMyTreeCtrl::OnBeginLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult) { TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr; // I thought m_BeginEditText was needed to restore text if desired, // but setting *pLResult to FALSE in OnEndLabelEdit suffices if (ptvinfo->item.pszText != NULL && ptvinfo->item.pszText[0] != '\0') { m_BeginEditText = ptvinfo->item.pszText; } else { m_BeginEditText = _T(""); } *pLResult = FALSE; // TRUE cancels label editing } void CMyTreeCtrl::OnEndLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult) { TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr; HTREEITEM ti = ptvinfo->item.hItem; if (ptvinfo->item.pszText != NULL && // NULL if edit cancelled, ptvinfo->item.pszText[0] != '\0') { // empty if text deleted - not allowed DboxMain *parent = (DboxMain *)GetParent(); ptvinfo->item.mask = TVIF_TEXT; SetItem(&ptvinfo->item); if (IsLeafNode(ptvinfo->item.hItem)) { // Update leaf's title DWORD itemData = GetItemData(ti); ASSERT(itemData != NULL); CItemData *ci = (CItemData *)itemData; ci->SetTitle(ptvinfo->item.pszText); // update corresponding List text DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo(); ASSERT(di != NULL); int lindex = di->list_index; parent->UpdateListItemTitle(lindex, ptvinfo->item.pszText); } else { // Update all leaf chldren with new path element // prefix is path up to and NOT including renamed node CString prefix; HTREEITEM parent, current = ti; do { parent = GetParentItem(current); if (parent == NULL) { break; } current = parent; if (!prefix.IsEmpty()) prefix = GROUP_SEP + prefix; prefix = GetItemText(current) + prefix; } while (1); UpdateLeafsGroup(ti, prefix); } // Mark database as modified parent->SetChanged(true); SortChildren(GetParentItem(ti)); *pLResult = TRUE; } else { // restore text // (not that this is documented anywhere in MS's docs...) *pLResult = FALSE; } } void CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point) { HTREEITEM hitem; UINT flags; if (m_bDragging) { ASSERT(m_pimagelist != NULL); m_pimagelist->DragMove(point); if ((hitem = HitTest(point, &flags)) != NULL) { m_pimagelist->DragLeave(this); SelectDropTarget(hitem); m_hitemDrop = hitem; m_pimagelist->DragEnter(this, point); } } CTreeCtrl::OnMouseMove(nFlags, point); } bool CMyTreeCtrl::IsChildNodeOf(HTREEITEM hitemChild, HTREEITEM hitemSuspectedParent) { do { if (hitemChild == hitemSuspectedParent) break; } while ((hitemChild = GetParentItem(hitemChild)) != NULL); return (hitemChild != NULL); } bool CMyTreeCtrl::IsLeafNode(HTREEITEM hItem) { // ItemHasChildren() won't work in the general case BOOL status; int i, dummy; status = GetItemImage(hItem, i, dummy); ASSERT(status); return (i == LEAF); } void CMyTreeCtrl::DeleteWithParents(HTREEITEM hItem) { // We don't want nodes that have no children to remain HTREEITEM p; do { p = GetParentItem(hItem); DeleteItem(hItem); if (ItemHasChildren(p)) break; hItem = p; } while (p != TVI_ROOT && p != NULL); } CString CMyTreeCtrl::GetGroup(HTREEITEM hItem) { CString retval; CString nodeText; while (hItem != NULL) { nodeText = GetItemText(hItem); if (!retval.IsEmpty()) nodeText += GROUP_SEP; retval = nodeText + retval; hItem = GetParentItem(hItem); } return retval; } static CMyString GetPathElem(CMyString &path) { // Get first path element and chop it off, i.e., if // path = "a.b.c.d" // will return "a" and path will be "b.c.d" // (assuming GROUP_SEP is '.') CMyString retval; int N = path.Find(GROUP_SEP); if (N == -1) { retval = path; path = _T(""); } else { const int Len = path.GetLength(); retval = CMyString(path.Left(N)); path = CMyString(path.Right(Len - N - 1)); } return retval; } static bool ExistsInTree(CTreeCtrl &Tree, HTREEITEM node, const CMyString &s, HTREEITEM &si) { // returns true iff s is a direct descendant of node HTREEITEM ti = Tree.GetChildItem(node); while (ti != NULL) { const CMyString itemText = Tree.GetItemText(ti); if (itemText == s) { si = ti; return true; } ti = Tree.GetNextItem(ti, TVGN_NEXT); } return false; } HTREEITEM CMyTreeCtrl::AddGroup(const CString &group) { // Add a group at the end of path HTREEITEM ti = TVI_ROOT; HTREEITEM si; if (!group.IsEmpty()) { CMyString path = group; CMyString s; do { s = GetPathElem(path); if (!ExistsInTree(*this, ti, s, si)) { ti = InsertItem(s, ti, TVI_SORT); SetItemImage(ti, CMyTreeCtrl::NODE, CMyTreeCtrl::NODE); } else ti = si; } while (!path.IsEmpty()); } return ti; } bool CMyTreeCtrl::TransferItem(HTREEITEM hitemDrag, HTREEITEM hitemDrop) { TV_INSERTSTRUCT tvstruct; TCHAR sztBuffer[128]; HTREEITEM hNewItem, hFirstChild; DWORD itemData = GetItemData(hitemDrag); // avoid an infinite recursion tvstruct.item.hItem = hitemDrag; tvstruct.item.cchTextMax = sizeof(sztBuffer)/sizeof(TCHAR) - 1; tvstruct.item.pszText = sztBuffer; tvstruct.item.mask = (TVIF_CHILDREN | TVIF_HANDLE | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT); GetItem(&tvstruct.item); // get information of the dragged element tvstruct.hParent = hitemDrop; tvstruct.hInsertAfter = TVI_SORT; tvstruct.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT; hNewItem = InsertItem(&tvstruct); if (itemData != 0) { // Non-NULL itemData implies Leaf CItemData *ci = (CItemData *)itemData; // Update Group CMyString path, elem; HTREEITEM p, q = hNewItem; do { p = GetParentItem(q); if (p != NULL) { elem = CMyString(GetItemText(p)); if (!path.IsEmpty()) elem += GROUP_SEP; path = elem + path; q = p; } else break; } while (1); ci->SetGroup(path); // Mark database as modified! ((DboxMain *)GetParent())->SetChanged(true); // Update DisplayInfo record associated with ItemData DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo(); ASSERT(di != NULL); di->tree_item = hNewItem; } SetItemData(hNewItem, itemData); while ((hFirstChild = GetChildItem(hitemDrag)) != NULL) { TransferItem(hFirstChild, hNewItem); // recursively transfer all the items DeleteItem(hFirstChild); } return true; } void CMyTreeCtrl::OnButtonUp() { if (m_bDragging) { ASSERT(m_pimagelist != NULL); m_pimagelist->DragLeave(this); m_pimagelist->EndDrag(); delete m_pimagelist; m_pimagelist = NULL; HTREEITEM parent = GetParentItem(m_hitemDrag); if (m_hitemDrag != m_hitemDrop && !IsLeafNode(m_hitemDrop) && !IsChildNodeOf(m_hitemDrop, m_hitemDrag) && parent != m_hitemDrop) { TransferItem(m_hitemDrag, m_hitemDrop); DeleteItem(m_hitemDrag); while (parent != NULL && !ItemHasChildren(parent)) { HTREEITEM grandParent = GetParentItem(parent); DeleteItem(parent); parent = grandParent; } } ReleaseCapture(); m_bDragging = FALSE; SelectDropTarget(NULL); } } void CMyTreeCtrl::OnLButtonUp(UINT nFlags, CPoint point) { OnButtonUp(); CTreeCtrl::OnLButtonUp(nFlags, point); } void CMyTreeCtrl::OnBeginDrag(LPNMHDR , LRESULT *) { CPoint ptAction; UINT nFlags; GetCursorPos(&ptAction); ScreenToClient(&ptAction); ASSERT(!m_bDragging); m_bDragging = TRUE; m_hitemDrag = HitTest(ptAction, &nFlags); m_hitemDrop = NULL; ASSERT(m_pimagelist == NULL); m_pimagelist = CreateDragImage(m_hitemDrag); m_pimagelist->DragShowNolock(TRUE); m_pimagelist->SetDragCursorImage(0, CPoint(0, 0)); m_pimagelist->BeginDrag(0, CPoint(0,0)); m_pimagelist->DragMove(ptAction); m_pimagelist->DragEnter(this, ptAction); SetCapture(); } <commit_msg>Fix selection handling o be more intuitive.<commit_after>/* * Silly subclass of CTreeCtrl just to implement Drag&Drop. * * Based on MFC sample code from CMNCTRL1 */ #include "stdafx.h" #include "MyTreeCtrl.h" #include "DboxMain.h" #include "corelib/ItemData.h" #include "corelib/MyString.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static const TCHAR GROUP_SEP = TCHAR('.'); CMyTreeCtrl::CMyTreeCtrl() : m_bDragging(false), m_pimagelist(NULL) { } CMyTreeCtrl::~CMyTreeCtrl() { delete m_pimagelist; } BEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl) //{{AFX_MSG_MAP(CMyTreeCtrl) ON_NOTIFY_REFLECT(TVN_BEGINLABELEDIT, OnBeginLabelEdit) ON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndLabelEdit) ON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBeginDrag) ON_WM_MOUSEMOVE() ON_WM_DESTROY() ON_WM_LBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() void CMyTreeCtrl::OnDestroy() { CImageList *pimagelist; pimagelist = GetImageList(TVSIL_NORMAL); if (pimagelist != NULL) { pimagelist->DeleteImageList(); delete pimagelist; } } void CMyTreeCtrl::SetNewStyle(long lStyleMask, BOOL bSetBits) { long lStyleOld; lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE); lStyleOld &= ~lStyleMask; if (bSetBits) lStyleOld |= lStyleMask; SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld); SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); } void CMyTreeCtrl::UpdateLeafsGroup(HTREEITEM hItem, CString prefix) { // Starting with hItem, update the Group field of all of hItem's // children. Called after a label has been edited. if (IsLeafNode(hItem)) { DWORD itemData = GetItemData(hItem); ASSERT(itemData != NULL); CItemData *ci = (CItemData *)itemData; ci->SetGroup(CMyString(prefix)); } else { // update prefix with current group name and recurse if (!prefix.IsEmpty()) prefix += GROUP_SEP; prefix += GetItemText(hItem); HTREEITEM child; for(child = GetChildItem(hItem); child != NULL; child = GetNextSiblingItem(child)) { UpdateLeafsGroup(child, prefix); } } } void CMyTreeCtrl::OnBeginLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult) { TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr; // I thought m_BeginEditText was needed to restore text if desired, // but setting *pLResult to FALSE in OnEndLabelEdit suffices if (ptvinfo->item.pszText != NULL && ptvinfo->item.pszText[0] != '\0') { m_BeginEditText = ptvinfo->item.pszText; } else { m_BeginEditText = _T(""); } *pLResult = FALSE; // TRUE cancels label editing } void CMyTreeCtrl::OnEndLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult) { TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr; HTREEITEM ti = ptvinfo->item.hItem; if (ptvinfo->item.pszText != NULL && // NULL if edit cancelled, ptvinfo->item.pszText[0] != '\0') { // empty if text deleted - not allowed DboxMain *parent = (DboxMain *)GetParent(); ptvinfo->item.mask = TVIF_TEXT; SetItem(&ptvinfo->item); if (IsLeafNode(ptvinfo->item.hItem)) { // Update leaf's title DWORD itemData = GetItemData(ti); ASSERT(itemData != NULL); CItemData *ci = (CItemData *)itemData; ci->SetTitle(ptvinfo->item.pszText); // update corresponding List text DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo(); ASSERT(di != NULL); int lindex = di->list_index; parent->UpdateListItemTitle(lindex, ptvinfo->item.pszText); } else { // Update all leaf chldren with new path element // prefix is path up to and NOT including renamed node CString prefix; HTREEITEM parent, current = ti; do { parent = GetParentItem(current); if (parent == NULL) { break; } current = parent; if (!prefix.IsEmpty()) prefix = GROUP_SEP + prefix; prefix = GetItemText(current) + prefix; } while (1); UpdateLeafsGroup(ti, prefix); } // Mark database as modified parent->SetChanged(true); SortChildren(GetParentItem(ti)); *pLResult = TRUE; } else { // restore text // (not that this is documented anywhere in MS's docs...) *pLResult = FALSE; } } void CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point) { if (m_bDragging) { UINT flags; ASSERT(m_pimagelist != NULL); m_pimagelist->DragMove(point); HTREEITEM hitem = HitTest(point, &flags); if (hitem != NULL) { m_pimagelist->DragLeave(this); SelectDropTarget(hitem); m_hitemDrop = hitem; m_pimagelist->DragEnter(this, point); } } CTreeCtrl::OnMouseMove(nFlags, point); } bool CMyTreeCtrl::IsChildNodeOf(HTREEITEM hitemChild, HTREEITEM hitemSuspectedParent) { do { if (hitemChild == hitemSuspectedParent) break; } while ((hitemChild = GetParentItem(hitemChild)) != NULL); return (hitemChild != NULL); } bool CMyTreeCtrl::IsLeafNode(HTREEITEM hItem) { // ItemHasChildren() won't work in the general case BOOL status; int i, dummy; status = GetItemImage(hItem, i, dummy); ASSERT(status); return (i == LEAF); } void CMyTreeCtrl::DeleteWithParents(HTREEITEM hItem) { // We don't want nodes that have no children to remain HTREEITEM p; do { p = GetParentItem(hItem); DeleteItem(hItem); if (ItemHasChildren(p)) break; hItem = p; } while (p != TVI_ROOT && p != NULL); } CString CMyTreeCtrl::GetGroup(HTREEITEM hItem) { CString retval; CString nodeText; while (hItem != NULL) { nodeText = GetItemText(hItem); if (!retval.IsEmpty()) nodeText += GROUP_SEP; retval = nodeText + retval; hItem = GetParentItem(hItem); } return retval; } static CMyString GetPathElem(CMyString &path) { // Get first path element and chop it off, i.e., if // path = "a.b.c.d" // will return "a" and path will be "b.c.d" // (assuming GROUP_SEP is '.') CMyString retval; int N = path.Find(GROUP_SEP); if (N == -1) { retval = path; path = _T(""); } else { const int Len = path.GetLength(); retval = CMyString(path.Left(N)); path = CMyString(path.Right(Len - N - 1)); } return retval; } static bool ExistsInTree(CTreeCtrl &Tree, HTREEITEM node, const CMyString &s, HTREEITEM &si) { // returns true iff s is a direct descendant of node HTREEITEM ti = Tree.GetChildItem(node); while (ti != NULL) { const CMyString itemText = Tree.GetItemText(ti); if (itemText == s) { si = ti; return true; } ti = Tree.GetNextItem(ti, TVGN_NEXT); } return false; } HTREEITEM CMyTreeCtrl::AddGroup(const CString &group) { // Add a group at the end of path HTREEITEM ti = TVI_ROOT; HTREEITEM si; if (!group.IsEmpty()) { CMyString path = group; CMyString s; do { s = GetPathElem(path); if (!ExistsInTree(*this, ti, s, si)) { ti = InsertItem(s, ti, TVI_SORT); SetItemImage(ti, CMyTreeCtrl::NODE, CMyTreeCtrl::NODE); } else ti = si; } while (!path.IsEmpty()); } return ti; } bool CMyTreeCtrl::TransferItem(HTREEITEM hitemDrag, HTREEITEM hitemDrop) { TV_INSERTSTRUCT tvstruct; TCHAR sztBuffer[128]; HTREEITEM hNewItem, hFirstChild; DWORD itemData = GetItemData(hitemDrag); // avoid an infinite recursion tvstruct.item.hItem = hitemDrag; tvstruct.item.cchTextMax = sizeof(sztBuffer)/sizeof(TCHAR) - 1; tvstruct.item.pszText = sztBuffer; tvstruct.item.mask = (TVIF_CHILDREN | TVIF_HANDLE | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT); GetItem(&tvstruct.item); // get information of the dragged element tvstruct.hParent = hitemDrop; tvstruct.hInsertAfter = TVI_SORT; tvstruct.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT; hNewItem = InsertItem(&tvstruct); if (itemData != 0) { // Non-NULL itemData implies Leaf CItemData *ci = (CItemData *)itemData; // Update Group CMyString path, elem; HTREEITEM p, q = hNewItem; do { p = GetParentItem(q); if (p != NULL) { elem = CMyString(GetItemText(p)); if (!path.IsEmpty()) elem += GROUP_SEP; path = elem + path; q = p; } else break; } while (1); ci->SetGroup(path); // Mark database as modified! ((DboxMain *)GetParent())->SetChanged(true); // Update DisplayInfo record associated with ItemData DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo(); ASSERT(di != NULL); di->tree_item = hNewItem; } SetItemData(hNewItem, itemData); while ((hFirstChild = GetChildItem(hitemDrag)) != NULL) { TransferItem(hFirstChild, hNewItem); // recursively transfer all the items DeleteItem(hFirstChild); } return true; } void CMyTreeCtrl::OnButtonUp() { if (m_bDragging) { ASSERT(m_pimagelist != NULL); m_pimagelist->DragLeave(this); m_pimagelist->EndDrag(); delete m_pimagelist; m_pimagelist = NULL; HTREEITEM parent = GetParentItem(m_hitemDrag); if (m_hitemDrag != m_hitemDrop && !IsLeafNode(m_hitemDrop) && !IsChildNodeOf(m_hitemDrop, m_hitemDrag) && parent != m_hitemDrop) { TransferItem(m_hitemDrag, m_hitemDrop); DeleteItem(m_hitemDrag); while (parent != NULL && !ItemHasChildren(parent)) { HTREEITEM grandParent = GetParentItem(parent); DeleteItem(parent); parent = grandParent; } SelectItem(m_hitemDrop); } else { // drag failed, revert to last selected SelectItem(m_hitemDrag); } ReleaseCapture(); m_bDragging = FALSE; SelectDropTarget(NULL); } } void CMyTreeCtrl::OnLButtonUp(UINT nFlags, CPoint point) { OnButtonUp(); CTreeCtrl::OnLButtonUp(nFlags, point); } void CMyTreeCtrl::OnBeginDrag(LPNMHDR , LRESULT *) { CPoint ptAction; UINT nFlags; GetCursorPos(&ptAction); ScreenToClient(&ptAction); ASSERT(!m_bDragging); m_bDragging = TRUE; m_hitemDrag = HitTest(ptAction, &nFlags); m_hitemDrop = NULL; ASSERT(m_pimagelist == NULL); m_pimagelist = CreateDragImage(m_hitemDrag); m_pimagelist->DragShowNolock(TRUE); m_pimagelist->SetDragCursorImage(0, CPoint(0, 0)); m_pimagelist->BeginDrag(0, CPoint(0,0)); m_pimagelist->DragMove(ptAction); m_pimagelist->DragEnter(this, ptAction); SetCapture(); } <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_rt_Runtime.h" #include "jnc_ct_Module.h" #include "jnc_CallSite.h" namespace jnc { namespace rt { //.............................................................................. Runtime::Runtime () { m_stackSizeLimit = RuntimeDef_StackSizeLimit; m_tlsSize = 0; m_state = State_Idle; m_userData = NULL; m_noThreadEvent.signal (); } bool Runtime::setStackSizeLimit (size_t sizeLimit) { if (sizeLimit < RuntimeDef_MinStackSizeLimit) { err::setError (err::SystemErrorCode_InvalidParameter); return false; } m_stackSizeLimit = sizeLimit; return true; } bool Runtime::startup (ct::Module* module) { shutdown (); m_tlsSize = module->m_variableMgr.getTlsStructType ()->getSize (); m_module = module; m_state = State_Running; m_noThreadEvent.signal (); ct::Function* constructor = module->getConstructor (); ASSERT (constructor); return m_gcHeap.startup (module) && callVoidFunction (this, constructor); } void Runtime::shutdown () { ASSERT (!sys::getTlsPtrSlotValue <Tls> ()); m_lock.lock (); if (m_state == State_Idle) { m_lock.unlock (); return; } ASSERT (m_state != State_ShuttingDown); // concurrent shutdowns? m_state = State_ShuttingDown; m_lock.unlock (); m_gcHeap.beginShutdown (); for (size_t i = 0; i < Shutdown_IterationCount; i++) { m_gcHeap.collect (); bool result = m_noThreadEvent.wait (Shutdown_WaitThreadTimeout); // wait for other threads if (result) break; } ASSERT (m_tlsList.isEmpty ()); m_gcHeap.finalizeShutdown (); m_state = State_Idle; } void Runtime::abort () { m_lock.lock (); if (m_state != State_Running) { m_lock.unlock (); return; } m_lock.unlock (); m_gcHeap.abort (); } void Runtime::initializeCallSite (jnc_CallSite* callSite) { // initialize dynamic GC shadow stack frame memset (callSite, 0, sizeof (jnc_CallSite)); ASSERT (sizeof (GcShadowStackFrameMapBuffer) >= sizeof (GcShadowStackFrameMap)); new (&callSite->m_gcShadowStackDynamicFrameMap) GcShadowStackFrameMap; callSite->m_gcShadowStackDynamicFrameMap.m_mapKind = ct::GcShadowStackFrameMapKind_Dynamic; callSite->m_gcShadowStackDynamicFrame.m_map = (GcShadowStackFrameMap*) &callSite->m_gcShadowStackDynamicFrameMap; Tls* prevTls = sys::getTlsPtrSlotValue <Tls> (); // try to find TLS of *this* runtime for (Tls* tls = prevTls; tls; tls = tls->m_prevTls) if (tls->m_runtime == this) // found { TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); ASSERT (tlsVariableTable->m_gcShadowStackTop > &callSite->m_gcShadowStackDynamicFrame); // save exception recovery snapshot callSite->m_initializeLevel = tls->m_initializeLevel; callSite->m_noCollectRegionLevel = tls->m_gcMutatorThread.m_noCollectRegionLevel; callSite->m_waitRegionLevel = tls->m_gcMutatorThread.m_waitRegionLevel; callSite->m_gcShadowStackDynamicFrame.m_prev = tlsVariableTable->m_gcShadowStackTop; // don't nest dynamic frames (unnecessary) -- but prev pointer must be saved anyway // also, without nesting it's often OK to skip explicit GcHeap::addBoxToDynamicFrame if (tlsVariableTable->m_gcShadowStackTop->m_map->getMapKind () != ct::GcShadowStackFrameMapKind_Dynamic) tlsVariableTable->m_gcShadowStackTop = &callSite->m_gcShadowStackDynamicFrame; tls->m_initializeLevel++; return; } // not found, create a new one Tls* tls = AXL_MEM_NEW_EXTRA (Tls, m_tlsSize); m_gcHeap.registerMutatorThread (&tls->m_gcMutatorThread); // register with GC heap first tls->m_prevTls = prevTls; tls->m_runtime = this; tls->m_initializeLevel = 1; tls->m_stackEpoch = callSite; TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); tlsVariableTable->m_gcShadowStackTop = &callSite->m_gcShadowStackDynamicFrame; sys::setTlsPtrSlotValue <Tls> (tls); m_lock.lock (); if (m_tlsList.isEmpty ()) m_noThreadEvent.reset (); m_tlsList.insertTail (tls); m_lock.unlock (); } void Runtime::uninitializeCallSite (jnc_CallSite* callSite) { Tls* tls = sys::getTlsPtrSlotValue <Tls> (); ASSERT (tls && tls->m_runtime == this); ASSERT ( callSite->m_initializeLevel == tls->m_initializeLevel - 1 && callSite->m_waitRegionLevel == tls->m_gcMutatorThread.m_waitRegionLevel ); ASSERT ( callSite->m_noCollectRegionLevel == tls->m_gcMutatorThread.m_noCollectRegionLevel || !callSite->m_result && callSite->m_noCollectRegionLevel < tls->m_gcMutatorThread.m_noCollectRegionLevel ); TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); GcShadowStackFrame* prevGcShadowStackTop = callSite->m_gcShadowStackDynamicFrame.m_prev; ASSERT ( tlsVariableTable->m_gcShadowStackTop == &callSite->m_gcShadowStackDynamicFrame || tlsVariableTable->m_gcShadowStackTop == prevGcShadowStackTop && prevGcShadowStackTop->m_map->getMapKind () == ct::GcShadowStackFrameMapKind_Dynamic || !callSite->m_result && tlsVariableTable->m_gcShadowStackTop < &callSite->m_gcShadowStackDynamicFrame ); // restore exception recovery snapshot tls->m_initializeLevel = callSite->m_initializeLevel; tls->m_gcMutatorThread.m_noCollectRegionLevel = callSite->m_noCollectRegionLevel; tls->m_gcMutatorThread.m_waitRegionLevel = callSite->m_waitRegionLevel; tlsVariableTable->m_gcShadowStackTop = prevGcShadowStackTop; ((GcShadowStackFrameMap*) &callSite->m_gcShadowStackDynamicFrameMap)->~GcShadowStackFrameMap (); if (tls->m_initializeLevel) // this thread was nested-initialized { m_gcHeap.safePoint (); return; } ASSERT ( !callSite->m_initializeLevel && !callSite->m_waitRegionLevel && !callSite->m_noCollectRegionLevel && !prevGcShadowStackTop ); m_gcHeap.unregisterMutatorThread (&tls->m_gcMutatorThread); m_lock.lock (); m_tlsList.remove (tls); if (m_tlsList.isEmpty ()) m_noThreadEvent.signal (); m_lock.unlock (); sys::setTlsPtrSlotValue <Tls> (tls->m_prevTls); AXL_MEM_DELETE (tls); } void Runtime::checkStackOverflow () { Tls* tls = sys::getTlsPtrSlotValue <Tls> (); ASSERT (tls && tls->m_runtime == this); char* p = (char*) _alloca (1); ASSERT ((char*) tls->m_stackEpoch >= p); size_t stackSize = (char*) tls->m_stackEpoch - p; if (stackSize > m_stackSizeLimit) { err::setFormatStringError ("stack overflow (%dB)", stackSize); dynamicThrow (); ASSERT (false); } } SjljFrame* Runtime::setSjljFrame (SjljFrame* frame) { Tls* tls = rt::getCurrentThreadTls (); if (!tls) { TRACE ("-- WARNING: set external SJLJ frame: %p\n", frame); return sys::setTlsPtrSlotValue <SjljFrame> (frame); } TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); ASSERT (tls); SjljFrame* prevFrame = tlsVariableTable->m_sjljFrame; tlsVariableTable->m_sjljFrame = frame; return prevFrame; } void Runtime::dynamicThrow () { Tls* tls = rt::getCurrentThreadTls (); ASSERT (tls); TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); if (tlsVariableTable->m_sjljFrame) { #if (_JNC_OS_WIN && _JNC_CPU_AMD64) _JUMP_BUFFER* pBuffer = (_JUMP_BUFFER*) tlsVariableTable->m_sjljFrame->m_jmpBuf; pBuffer->Frame = 0; // prevent unwinding -- it doesn't work with the LLVM MCJIT-generated code #endif longjmp (tlsVariableTable->m_sjljFrame->m_jmpBuf, -1); } else { SjljFrame* frame = sys::getTlsPtrSlotValue <SjljFrame> (); TRACE ("-- WARNING: jump to external SJLJ frame: %p\n", frame); ASSERT (frame); longjmp (frame->m_jmpBuf, -1); } ASSERT (false); } //.............................................................................. } // namespace rt } // namespace jnc <commit_msg>[jnc_rt] fix: Runtime::m_module was uninitialized<commit_after>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_rt_Runtime.h" #include "jnc_ct_Module.h" #include "jnc_CallSite.h" namespace jnc { namespace rt { //.............................................................................. Runtime::Runtime () { m_stackSizeLimit = RuntimeDef_StackSizeLimit; m_tlsSize = 0; m_state = State_Idle; m_module = NULL; m_userData = NULL; m_noThreadEvent.signal (); } bool Runtime::setStackSizeLimit (size_t sizeLimit) { if (sizeLimit < RuntimeDef_MinStackSizeLimit) { err::setError (err::SystemErrorCode_InvalidParameter); return false; } m_stackSizeLimit = sizeLimit; return true; } bool Runtime::startup (ct::Module* module) { shutdown (); m_tlsSize = module->m_variableMgr.getTlsStructType ()->getSize (); m_module = module; m_state = State_Running; m_noThreadEvent.signal (); ct::Function* constructor = module->getConstructor (); ASSERT (constructor); return m_gcHeap.startup (module) && callVoidFunction (this, constructor); } void Runtime::shutdown () { ASSERT (!sys::getTlsPtrSlotValue <Tls> ()); m_lock.lock (); if (m_state == State_Idle) { m_lock.unlock (); return; } ASSERT (m_state != State_ShuttingDown); // concurrent shutdowns? m_state = State_ShuttingDown; m_lock.unlock (); m_gcHeap.beginShutdown (); for (size_t i = 0; i < Shutdown_IterationCount; i++) { m_gcHeap.collect (); bool result = m_noThreadEvent.wait (Shutdown_WaitThreadTimeout); // wait for other threads if (result) break; } ASSERT (m_tlsList.isEmpty ()); m_gcHeap.finalizeShutdown (); m_state = State_Idle; } void Runtime::abort () { m_lock.lock (); if (m_state != State_Running) { m_lock.unlock (); return; } m_lock.unlock (); m_gcHeap.abort (); } void Runtime::initializeCallSite (jnc_CallSite* callSite) { // initialize dynamic GC shadow stack frame memset (callSite, 0, sizeof (jnc_CallSite)); ASSERT (sizeof (GcShadowStackFrameMapBuffer) >= sizeof (GcShadowStackFrameMap)); new (&callSite->m_gcShadowStackDynamicFrameMap) GcShadowStackFrameMap; callSite->m_gcShadowStackDynamicFrameMap.m_mapKind = ct::GcShadowStackFrameMapKind_Dynamic; callSite->m_gcShadowStackDynamicFrame.m_map = (GcShadowStackFrameMap*) &callSite->m_gcShadowStackDynamicFrameMap; Tls* prevTls = sys::getTlsPtrSlotValue <Tls> (); // try to find TLS of *this* runtime for (Tls* tls = prevTls; tls; tls = tls->m_prevTls) if (tls->m_runtime == this) // found { TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); ASSERT (tlsVariableTable->m_gcShadowStackTop > &callSite->m_gcShadowStackDynamicFrame); // save exception recovery snapshot callSite->m_initializeLevel = tls->m_initializeLevel; callSite->m_noCollectRegionLevel = tls->m_gcMutatorThread.m_noCollectRegionLevel; callSite->m_waitRegionLevel = tls->m_gcMutatorThread.m_waitRegionLevel; callSite->m_gcShadowStackDynamicFrame.m_prev = tlsVariableTable->m_gcShadowStackTop; // don't nest dynamic frames (unnecessary) -- but prev pointer must be saved anyway // also, without nesting it's often OK to skip explicit GcHeap::addBoxToDynamicFrame if (tlsVariableTable->m_gcShadowStackTop->m_map->getMapKind () != ct::GcShadowStackFrameMapKind_Dynamic) tlsVariableTable->m_gcShadowStackTop = &callSite->m_gcShadowStackDynamicFrame; tls->m_initializeLevel++; return; } // not found, create a new one Tls* tls = AXL_MEM_NEW_EXTRA (Tls, m_tlsSize); m_gcHeap.registerMutatorThread (&tls->m_gcMutatorThread); // register with GC heap first tls->m_prevTls = prevTls; tls->m_runtime = this; tls->m_initializeLevel = 1; tls->m_stackEpoch = callSite; TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); tlsVariableTable->m_gcShadowStackTop = &callSite->m_gcShadowStackDynamicFrame; sys::setTlsPtrSlotValue <Tls> (tls); m_lock.lock (); if (m_tlsList.isEmpty ()) m_noThreadEvent.reset (); m_tlsList.insertTail (tls); m_lock.unlock (); } void Runtime::uninitializeCallSite (jnc_CallSite* callSite) { Tls* tls = sys::getTlsPtrSlotValue <Tls> (); ASSERT (tls && tls->m_runtime == this); ASSERT ( callSite->m_initializeLevel == tls->m_initializeLevel - 1 && callSite->m_waitRegionLevel == tls->m_gcMutatorThread.m_waitRegionLevel ); ASSERT ( callSite->m_noCollectRegionLevel == tls->m_gcMutatorThread.m_noCollectRegionLevel || !callSite->m_result && callSite->m_noCollectRegionLevel < tls->m_gcMutatorThread.m_noCollectRegionLevel ); TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); GcShadowStackFrame* prevGcShadowStackTop = callSite->m_gcShadowStackDynamicFrame.m_prev; ASSERT ( tlsVariableTable->m_gcShadowStackTop == &callSite->m_gcShadowStackDynamicFrame || tlsVariableTable->m_gcShadowStackTop == prevGcShadowStackTop && prevGcShadowStackTop->m_map->getMapKind () == ct::GcShadowStackFrameMapKind_Dynamic || !callSite->m_result && tlsVariableTable->m_gcShadowStackTop < &callSite->m_gcShadowStackDynamicFrame ); // restore exception recovery snapshot tls->m_initializeLevel = callSite->m_initializeLevel; tls->m_gcMutatorThread.m_noCollectRegionLevel = callSite->m_noCollectRegionLevel; tls->m_gcMutatorThread.m_waitRegionLevel = callSite->m_waitRegionLevel; tlsVariableTable->m_gcShadowStackTop = prevGcShadowStackTop; ((GcShadowStackFrameMap*) &callSite->m_gcShadowStackDynamicFrameMap)->~GcShadowStackFrameMap (); if (tls->m_initializeLevel) // this thread was nested-initialized { m_gcHeap.safePoint (); return; } ASSERT ( !callSite->m_initializeLevel && !callSite->m_waitRegionLevel && !callSite->m_noCollectRegionLevel && !prevGcShadowStackTop ); m_gcHeap.unregisterMutatorThread (&tls->m_gcMutatorThread); m_lock.lock (); m_tlsList.remove (tls); if (m_tlsList.isEmpty ()) m_noThreadEvent.signal (); m_lock.unlock (); sys::setTlsPtrSlotValue <Tls> (tls->m_prevTls); AXL_MEM_DELETE (tls); } void Runtime::checkStackOverflow () { Tls* tls = sys::getTlsPtrSlotValue <Tls> (); ASSERT (tls && tls->m_runtime == this); char* p = (char*) _alloca (1); ASSERT ((char*) tls->m_stackEpoch >= p); size_t stackSize = (char*) tls->m_stackEpoch - p; if (stackSize > m_stackSizeLimit) { err::setFormatStringError ("stack overflow (%dB)", stackSize); dynamicThrow (); ASSERT (false); } } SjljFrame* Runtime::setSjljFrame (SjljFrame* frame) { Tls* tls = rt::getCurrentThreadTls (); if (!tls) { TRACE ("-- WARNING: set external SJLJ frame: %p\n", frame); return sys::setTlsPtrSlotValue <SjljFrame> (frame); } TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); ASSERT (tls); SjljFrame* prevFrame = tlsVariableTable->m_sjljFrame; tlsVariableTable->m_sjljFrame = frame; return prevFrame; } void Runtime::dynamicThrow () { Tls* tls = rt::getCurrentThreadTls (); ASSERT (tls); TlsVariableTable* tlsVariableTable = (TlsVariableTable*) (tls + 1); if (tlsVariableTable->m_sjljFrame) { #if (_JNC_OS_WIN && _JNC_CPU_AMD64) _JUMP_BUFFER* pBuffer = (_JUMP_BUFFER*) tlsVariableTable->m_sjljFrame->m_jmpBuf; pBuffer->Frame = 0; // prevent unwinding -- it doesn't work with the LLVM MCJIT-generated code #endif longjmp (tlsVariableTable->m_sjljFrame->m_jmpBuf, -1); } else { SjljFrame* frame = sys::getTlsPtrSlotValue <SjljFrame> (); TRACE ("-- WARNING: jump to external SJLJ frame: %p\n", frame); ASSERT (frame); longjmp (frame->m_jmpBuf, -1); } ASSERT (false); } //.............................................................................. } // namespace rt } // namespace jnc <|endoftext|>
<commit_before>#include "BluPrivatePCH.h" UBluEye::UBluEye(const class FObjectInitializer& PCIP) : Super(PCIP) { Width = 800; Height = 600; bIsTransparent = false; } void UBluEye::init() { /** * We don't want this running in editor unless it's PIE * If we don't check this, CEF will spawn infinit processes with widget components **/ if (GEngine) { if (GEngine->IsEditor() && !GWorld->IsPlayInEditor()) { UE_LOG(LogBlu, Log, TEXT("Notice: not playing - Component Will Not Initialize")); return; } } browserSettings.universal_access_from_file_urls = STATE_ENABLED; browserSettings.file_access_from_file_urls = STATE_ENABLED; info.width = Width; info.height = Height; // Set transparant option info.SetAsWindowless(NULL, bIsTransparent); renderer = new RenderHandler(Width, Height, this); g_handler = new BrowserClient(renderer); browser = CefBrowserHost::CreateBrowserSync(info, g_handler.get(), "about:blank", browserSettings, NULL); // Setup JS event emitter g_handler->SetEventEmitter(&ScriptEventEmitter); UE_LOG(LogBlu, Log, TEXT("Component Initialized")); CefString str = *DefaultURL; UE_LOG(LogBlu, Log, TEXT("Loading URL: %s"), *DefaultURL); // Load the default URL LoadURL(DefaultURL); ResetTexture(); } void UBluEye::ResetTexture() { // Here we init the texture to its initial state DestroyTexture(); // init the new Texture2D Texture = UTexture2D::CreateTransient(Width, Height); Texture->Filter = TF_MAX; Texture->AddToRoot(); Texture->UpdateResource(); ResetMatInstance(); } void UBluEye::updateBuffer(const void* buffer) { texBuffer = buffer; } void UBluEye::DestroyTexture() { // Here we destory the texture and its resource if (Texture) { Texture->RemoveFromRoot(); if (Texture->Resource) { BeginReleaseResource(Texture->Resource); FlushRenderingCommands(); } Texture->MarkPendingKill(); Texture = nullptr; } } void UBluEye::TextureUpdate() { if (!browser || !bEnabled) { UE_LOG(LogBlu, Warning, TEXT("NO BROWSER ACCESS OR NOT ENABLED")) return; } if (Texture && Texture->Resource) { // Is our texture ready? auto ref = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI(); if (!ref) { UE_LOG(LogBlu, Warning, TEXT("NO REF")) return; } if (texBuffer == nullptr) { UE_LOG(LogBlu, Warning, TEXT("NO TEXTDATA")) return; } const size_t size = Width * Height * sizeof(uint32); // @TODO This is a bit heavy to keep reallocating/deallocating, but not a big deal. Maybe we can ping pong between buffers instead. TArray<uint32> ViewBuffer; ViewBuffer.Init(Width * Height); FMemory::Memcpy(ViewBuffer.GetData(), texBuffer, size); TextureDataPtr dataPtr = MakeShareable(new TextureData); dataPtr->SetRawData(Width, Height, sizeof(uint32), ViewBuffer); // Clean up from the per-render ViewBuffer.Empty(); //texBuffer = 0; ENQUEUE_UNIQUE_RENDER_COMMAND_THREEPARAMETER( TextureData, TextureDataPtr, ImageData, dataPtr, FTexture2DRHIRef, TargetTexture, ref, const size_t, DataSize, size, { uint32 stride = 0; void* MipData = GDynamicRHI->RHILockTexture2D(TargetTexture, 0, RLM_WriteOnly, stride, false); if (MipData) { FMemory::Memcpy(MipData, ImageData->GetRawBytesPtr(), ImageData->GetDataSize()); GDynamicRHI->RHIUnlockTexture2D(TargetTexture, 0, false); } ImageData.Reset(); }); } else { UE_LOG(LogBlu, Warning, TEXT("no Texture or Texture->resource")) } } void UBluEye::ExecuteJS(const FString& code) { CefString codeStr = *code; UE_LOG(LogBlu, Log, TEXT("Execute JS: %s"), *code) browser->GetMainFrame()->ExecuteJavaScript(codeStr, "", 0); // create an event function that can be called from JS } void UBluEye::LoadURL(const FString& newURL) { // Check if we want to load a local file if (newURL.Contains(TEXT("blui://"), ESearchCase::IgnoreCase, ESearchDir::FromStart)) { // Get the current working directory FString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir()); // We're loading a local file, so replace the proto with our game directory path FString LocalFile = newURL.Replace(TEXT("blui://"), *GameDir, ESearchCase::IgnoreCase); // Now we use the file proto LocalFile = FString(TEXT("file:///")) + LocalFile; UE_LOG(LogBlu, Log, TEXT("Load Local File: %s"), *LocalFile) // Load it up browser->GetMainFrame()->LoadURL(*LocalFile); return; } // Load as usual browser->GetMainFrame()->LoadURL(*newURL); } void UBluEye::TriggerMouseMove(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendFocusEvent(true); browser->GetHost()->SendMouseMoveEvent(mouse_event, false); } void UBluEye::TriggerLeftClick(const FVector2D& pos, const float scale) { TriggerLeftMouseDown(pos, scale); TriggerLeftMouseUp(pos, scale); } void UBluEye::TriggerRightClick(const FVector2D& pos, const float scale) { TriggerRightMouseDown(pos, scale); TriggerRightMouseUp(pos, scale); } void UBluEye::TriggerLeftMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1); } void UBluEye::TriggerRightMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 1); } void UBluEye::TriggerLeftMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1); } void UBluEye::TriggerRightMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 1); } void UBluEye::KeyDown(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyUp(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyPress(FKeyEvent InKey) { // Simply trigger down, then up key events KeyDown(InKey); KeyUp(InKey); } void UBluEye::processKeyCode(FKeyEvent InKey) { key_event.native_key_code = InKey.GetKeyCode(); key_event.windows_key_code = InKey.GetKeyCode(); } void UBluEye::CharKeyPress(FCharacterEvent CharEvent) { // Process keymods like usual processKeyMods(CharEvent); // Below char input needs some special treatment, se we can't use the normal key down/up methods key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); //key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); key_event.type = KEYEVENT_CHAR; browser->GetHost()->SendKeyEvent(key_event); key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); // bits 30 and 31 should be always 1 for WM_KEYUP key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::processKeyMods(FInputEvent InKey) { int mods = 0; // Test alt if (InKey.IsAltDown()) { mods |= cef_event_flags_t::EVENTFLAG_ALT_DOWN; } else // Test control if (InKey.IsControlDown()) { mods |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN; } else // Test shift if (InKey.IsShiftDown()) { mods |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN; } key_event.modifiers = mods; } UTexture2D* UBluEye::GetTexture() const { if (!Texture) { return UTexture2D::CreateTransient(Width, Height); } return Texture; } UMaterialInstanceDynamic* UBluEye::GetMaterialInstance() const { return MaterialInstance; } void UBluEye::ResetMatInstance() { if (!Texture || !BaseMaterial || TextureParameterName.IsNone()) { return; } // Create material instance if (!MaterialInstance) { MaterialInstance = UMaterialInstanceDynamic::Create(BaseMaterial, NULL); if (!MaterialInstance) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance can't be created")); return; } } // Check again, we must have material instance if (!MaterialInstance) { UE_LOG(LogBlu, Error, TEXT("UI Material instance wasn't created")); return; } // Check we have desired parameter UTexture* Tex = nullptr; if (!MaterialInstance->GetTextureParameterValue(TextureParameterName, Tex)) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance Texture parameter not found")); return; } MaterialInstance->SetTextureParameterValue(TextureParameterName, GetTexture()); } void UBluEye::CloseBrowser() { BeginDestroy(); } void UBluEye::BeginDestroy() { if (browser) { browser->GetHost()->CloseBrowser(false); } DestroyTexture(); Super::BeginDestroy(); } void UBluEye::RunTick() { TextureUpdate(); }<commit_msg>Minor texture property tweaks<commit_after>#include "BluPrivatePCH.h" UBluEye::UBluEye(const class FObjectInitializer& PCIP) : Super(PCIP) { Width = 800; Height = 600; bIsTransparent = false; } void UBluEye::init() { /** * We don't want this running in editor unless it's PIE * If we don't check this, CEF will spawn infinit processes with widget components **/ if (GEngine) { if (GEngine->IsEditor() && !GWorld->IsPlayInEditor()) { UE_LOG(LogBlu, Log, TEXT("Notice: not playing - Component Will Not Initialize")); return; } } browserSettings.universal_access_from_file_urls = STATE_ENABLED; browserSettings.file_access_from_file_urls = STATE_ENABLED; info.width = Width; info.height = Height; // Set transparant option info.SetAsWindowless(NULL, bIsTransparent); renderer = new RenderHandler(Width, Height, this); g_handler = new BrowserClient(renderer); browser = CefBrowserHost::CreateBrowserSync(info, g_handler.get(), "about:blank", browserSettings, NULL); // Setup JS event emitter g_handler->SetEventEmitter(&ScriptEventEmitter); UE_LOG(LogBlu, Log, TEXT("Component Initialized")); CefString str = *DefaultURL; UE_LOG(LogBlu, Log, TEXT("Loading URL: %s"), *DefaultURL); // Load the default URL LoadURL(DefaultURL); ResetTexture(); } void UBluEye::ResetTexture() { // Here we init the texture to its initial state DestroyTexture(); // init the new Texture2D Texture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8); Texture->AddToRoot(); Texture->LODGroup = TEXTUREGROUP_UI; Texture->CompressionSettings = TC_EditorIcon; Texture->Filter = TF_Default; Texture->UpdateResource(); ResetMatInstance(); } void UBluEye::updateBuffer(const void* buffer) { texBuffer = buffer; } void UBluEye::DestroyTexture() { // Here we destory the texture and its resource if (Texture) { Texture->RemoveFromRoot(); if (Texture->Resource) { BeginReleaseResource(Texture->Resource); FlushRenderingCommands(); } Texture->MarkPendingKill(); Texture = nullptr; } } void UBluEye::TextureUpdate() { if (!browser || !bEnabled) { UE_LOG(LogBlu, Warning, TEXT("NO BROWSER ACCESS OR NOT ENABLED")) return; } if (Texture && Texture->Resource) { // Is our texture ready? auto ref = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI(); if (!ref) { UE_LOG(LogBlu, Warning, TEXT("NO REF")) return; } if (texBuffer == nullptr) { UE_LOG(LogBlu, Warning, TEXT("NO TEXTDATA")) return; } const size_t size = Width * Height * sizeof(uint32); // @TODO This is a bit heavy to keep reallocating/deallocating, but not a big deal. Maybe we can ping pong between buffers instead. TArray<uint32> ViewBuffer; ViewBuffer.Init(Width * Height); FMemory::Memcpy(ViewBuffer.GetData(), texBuffer, size); TextureDataPtr dataPtr = MakeShareable(new TextureData); dataPtr->SetRawData(Width, Height, sizeof(uint32), ViewBuffer); // Clean up from the per-render ViewBuffer.Empty(); //texBuffer = 0; ENQUEUE_UNIQUE_RENDER_COMMAND_THREEPARAMETER( TextureData, TextureDataPtr, ImageData, dataPtr, FTexture2DRHIRef, TargetTexture, ref, const size_t, DataSize, size, { uint32 stride = 0; void* MipData = GDynamicRHI->RHILockTexture2D(TargetTexture, 0, RLM_WriteOnly, stride, false); if (MipData) { FMemory::Memcpy(MipData, ImageData->GetRawBytesPtr(), ImageData->GetDataSize()); GDynamicRHI->RHIUnlockTexture2D(TargetTexture, 0, false); } ImageData.Reset(); }); } else { UE_LOG(LogBlu, Warning, TEXT("no Texture or Texture->resource")) } } void UBluEye::ExecuteJS(const FString& code) { CefString codeStr = *code; UE_LOG(LogBlu, Log, TEXT("Execute JS: %s"), *code) browser->GetMainFrame()->ExecuteJavaScript(codeStr, "", 0); // create an event function that can be called from JS } void UBluEye::LoadURL(const FString& newURL) { // Check if we want to load a local file if (newURL.Contains(TEXT("blui://"), ESearchCase::IgnoreCase, ESearchDir::FromStart)) { // Get the current working directory FString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir()); // We're loading a local file, so replace the proto with our game directory path FString LocalFile = newURL.Replace(TEXT("blui://"), *GameDir, ESearchCase::IgnoreCase); // Now we use the file proto LocalFile = FString(TEXT("file:///")) + LocalFile; UE_LOG(LogBlu, Log, TEXT("Load Local File: %s"), *LocalFile) // Load it up browser->GetMainFrame()->LoadURL(*LocalFile); return; } // Load as usual browser->GetMainFrame()->LoadURL(*newURL); } void UBluEye::TriggerMouseMove(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendFocusEvent(true); browser->GetHost()->SendMouseMoveEvent(mouse_event, false); } void UBluEye::TriggerLeftClick(const FVector2D& pos, const float scale) { TriggerLeftMouseDown(pos, scale); TriggerLeftMouseUp(pos, scale); } void UBluEye::TriggerRightClick(const FVector2D& pos, const float scale) { TriggerRightMouseDown(pos, scale); TriggerRightMouseUp(pos, scale); } void UBluEye::TriggerLeftMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1); } void UBluEye::TriggerRightMouseDown(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 1); } void UBluEye::TriggerLeftMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1); } void UBluEye::TriggerRightMouseUp(const FVector2D& pos, const float scale) { mouse_event.x = pos.X / scale; mouse_event.y = pos.Y / scale; browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 1); } void UBluEye::KeyDown(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyUp(FKeyEvent InKey) { processKeyMods(InKey); processKeyCode(InKey); key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::KeyPress(FKeyEvent InKey) { // Simply trigger down, then up key events KeyDown(InKey); KeyUp(InKey); } void UBluEye::processKeyCode(FKeyEvent InKey) { key_event.native_key_code = InKey.GetKeyCode(); key_event.windows_key_code = InKey.GetKeyCode(); } void UBluEye::CharKeyPress(FCharacterEvent CharEvent) { // Process keymods like usual processKeyMods(CharEvent); // Below char input needs some special treatment, se we can't use the normal key down/up methods key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); //key_event.type = KEYEVENT_KEYDOWN; browser->GetHost()->SendKeyEvent(key_event); key_event.type = KEYEVENT_CHAR; browser->GetHost()->SendKeyEvent(key_event); key_event.windows_key_code = CharEvent.GetCharacter(); key_event.native_key_code = CharEvent.GetCharacter(); // bits 30 and 31 should be always 1 for WM_KEYUP key_event.type = KEYEVENT_KEYUP; browser->GetHost()->SendKeyEvent(key_event); } void UBluEye::processKeyMods(FInputEvent InKey) { int mods = 0; // Test alt if (InKey.IsAltDown()) { mods |= cef_event_flags_t::EVENTFLAG_ALT_DOWN; } else // Test control if (InKey.IsControlDown()) { mods |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN; } else // Test shift if (InKey.IsShiftDown()) { mods |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN; } key_event.modifiers = mods; } UTexture2D* UBluEye::GetTexture() const { if (!Texture) { return UTexture2D::CreateTransient(Width, Height); } return Texture; } UMaterialInstanceDynamic* UBluEye::GetMaterialInstance() const { return MaterialInstance; } void UBluEye::ResetMatInstance() { if (!Texture || !BaseMaterial || TextureParameterName.IsNone()) { return; } // Create material instance if (!MaterialInstance) { MaterialInstance = UMaterialInstanceDynamic::Create(BaseMaterial, NULL); if (!MaterialInstance) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance can't be created")); return; } } // Check again, we must have material instance if (!MaterialInstance) { UE_LOG(LogBlu, Error, TEXT("UI Material instance wasn't created")); return; } // Check we have desired parameter UTexture* Tex = nullptr; if (!MaterialInstance->GetTextureParameterValue(TextureParameterName, Tex)) { UE_LOG(LogBlu, Warning, TEXT("UI Material instance Texture parameter not found")); return; } MaterialInstance->SetTextureParameterValue(TextureParameterName, GetTexture()); } void UBluEye::CloseBrowser() { BeginDestroy(); } void UBluEye::BeginDestroy() { if (browser) { browser->GetHost()->CloseBrowser(false); } DestroyTexture(); Super::BeginDestroy(); } void UBluEye::RunTick() { TextureUpdate(); }<|endoftext|>
<commit_before>/** * @file common_account.cpp * @brief Manage a common account. * @author Sebastiao * @date 2015/20/06 * @copyright See LICENCE.txt */ #include <ctime> #include <cstdint> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <sstream> #include <unordered_map> using namespace std; namespace caccount { struct Record { string sys_timestamp; string rec_timestamp; uint16_t entity; double amount; }; class Account : public vector <Record> { public: Account(): vector <Record>() {}; bool LoadFromFile(const char * fname) { clear(); ifstream file (fname); if (!file.good()) return false; while(true){ string line; auto& istr = getline(file, line); istringstream iss(line); if (istr.eof()) break; Record rec; iss >> rec.sys_timestamp >> rec.rec_timestamp >> rec.entity >> rec.amount; push_back (rec); } file.close(); } bool DumpToFile(const char * fname) { ofstream file (fname, ios::trunc); bool result = DumpToStream(file); file.close(); return result; } bool DumpToStream(ostream & file, bool show_total = false) { if (!file.good()) return false; unordered_map<uint16_t, double> totals; for (const Record& rec : *this) { file << rec.sys_timestamp << m_sep << rec.rec_timestamp << m_sep << rec.entity << m_sep << rec.amount << endl; if (totals.find(rec.entity) != totals.end()){ totals[rec.entity] += rec.amount; } else { totals.insert({rec.entity, rec.amount}); } } if (show_total){ file << "entity\t\tamount\t\tbalance" << endl; for (const auto& total : totals) { double others = 0.0; for (const auto& total0 : totals) { if (total0.first != total.first) others += total0.second; } file << total.first << "\t\t" << total.second << "\t\t" << (total.second/totals.size() - others/totals.size()) << endl; } } } private: const char m_sep = '\t'; // must be whitespace }; } namespace { string SystemTimestamp(){ time_t rawtime; tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); char buff [64]; strftime(buff, 64, "%Y-%m-%d_%H:%M:%S", timeinfo); return string(buff); } const char * file_name = "account.dat"; const char * program_header = "cma: Common Account Program\n" "Crash the program (Ctrl+C) to exit\n"; } int main(int argc, char** argv) { cout << program_header << endl; caccount::Account account; account.LoadFromFile(file_name); account.DumpToStream(cout, true); while (true){ cout << "Insert record " "<entity:uint16_t> " "<amount:double> " "[timestamp:%d-%m]: " << endl; caccount::Record rec; cin >> rec.entity >> rec.amount >> rec.rec_timestamp; rec.sys_timestamp = SystemTimestamp(); account.push_back(rec); account.DumpToStream(cout, true); account.DumpToFile(file_name); } return 0; }<commit_msg>Dat reorder<commit_after>/** * @file common_account.cpp * @brief Manage a common account. * @author Sebastiao * @date 2015/20/06 * @copyright See LICENCE.txt */ #include <ctime> #include <cstdint> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <sstream> #include <unordered_map> using namespace std; namespace caccount { struct Record { string sys_timestamp; string rec_timestamp; uint16_t entity; double amount; }; class Account : public vector <Record> { public: Account(): vector <Record>() {}; bool LoadFromFile(const char * fname) { clear(); ifstream file (fname); if (!file.good()) return false; while(true){ string line; auto& istr = getline(file, line); istringstream iss(line); if (istr.eof()) break; Record rec; iss >> rec.sys_timestamp >> rec.entity >> rec.amount >> rec.rec_timestamp; push_back (rec); } file.close(); } bool DumpToFile(const char * fname) { ofstream file (fname, ios::trunc); bool result = DumpToStream(file); file.close(); return result; } bool DumpToStream(ostream & file, bool show_total = false) { if (!file.good()) return false; unordered_map<uint16_t, double> totals; for (const Record& rec : *this) { file << rec.sys_timestamp << m_sep << rec.entity << m_sep << rec.amount << m_sep << rec.rec_timestamp << endl; if (totals.find(rec.entity) != totals.end()){ totals[rec.entity] += rec.amount; } else { totals.insert({rec.entity, rec.amount}); } } if (show_total){ file << "entity\t\tamount\t\tbalance" << endl; for (const auto& total : totals) { double others = 0.0; for (const auto& total0 : totals) { if (total0.first != total.first) others += total0.second; } file << total.first << "\t\t" << total.second << "\t\t" << (total.second/totals.size() - others/totals.size()) << endl; } } } private: const char m_sep = '\t'; // must be whitespace }; } namespace { string SystemTimestamp(){ time_t rawtime; tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); char buff [64]; strftime(buff, 64, "%Y-%m-%d_%H:%M:%S", timeinfo); return string(buff); } const char * file_name = "account.dat"; const char * program_header = "cma: Common Account Program\n" "Crash the program (Ctrl+C) to exit\n"; } int main(int argc, char** argv) { cout << program_header << endl; caccount::Account account; account.LoadFromFile(file_name); account.DumpToStream(cout, true); while (true){ cout << "Insert record " "<entity:uint16_t> " "<amount:double> " "[timestamp/idstamp]: " << endl; caccount::Record rec; cin >> rec.entity >> rec.amount >> rec.rec_timestamp; rec.sys_timestamp = SystemTimestamp(); account.push_back(rec); account.DumpToStream(cout, true); account.DumpToFile(file_name); } return 0; }<|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/witness/witness.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/witness_object.hpp> #include <graphene/utilities/key_conversion.hpp> #include <fc/smart_ref_impl.hpp> #include <fc/thread/thread.hpp> #include <iostream> using namespace graphene::witness_plugin; using std::string; using std::vector; namespace bpo = boost::program_options; void new_chain_banner( const graphene::chain::database& db ) { std::cerr << "\n" "********************************\n" "* *\n" "* ------- NEW CHAIN ------ *\n" "* - Welcome to Graphene! - *\n" "* ------------------------ *\n" "* *\n" "********************************\n" "\n"; if( db.get_slot_at_time( fc::time_point::now() ) > 200 ) { std::cerr << "Your genesis seems to have an old timestamp\n" "Please consider using the --genesis-timestamp option to give your genesis a recent timestamp\n" "\n" ; } return; } void witness_plugin::plugin_set_program_options( boost::program_options::options_description& command_line_options, boost::program_options::options_description& config_file_options) { auto default_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(std::string("nathan"))); string witness_id_example = fc::json::to_string(chain::witness_id_type(5)); command_line_options.add_options() ("enable-stale-production", bpo::bool_switch()->notifier([this](bool e){_production_enabled = e;}), "Enable block production, even if the chain is stale.") ("required-participation", bpo::bool_switch()->notifier([this](int e){_required_witness_participation = uint32_t(e*GRAPHENE_1_PERCENT);}), "Percent of witnesses (0-99) that must be participating in order to produce blocks") ("witness-id,w", bpo::value<vector<string>>()->composing()->multitoken(), ("ID of witness controlled by this node (e.g. " + witness_id_example + ", quotes are required, may specify multiple times)").c_str()) ("private-key", bpo::value<vector<string>>()->composing()->multitoken()-> DEFAULT_VALUE_VECTOR(std::make_pair(chain::public_key_type(default_priv_key.get_public_key()), graphene::utilities::key_to_wif(default_priv_key))), "Tuple of [PublicKey, WIF private key] (may specify multiple times)") ; config_file_options.add(command_line_options); } std::string witness_plugin::plugin_name()const { return "witness"; } void witness_plugin::plugin_initialize(const boost::program_options::variables_map& options) { try { ilog("witness plugin: plugin_initialize() begin"); _options = &options; LOAD_VALUE_SET(options, "witness-id", _witnesses, chain::witness_id_type) if( options.count("private-key") ) { const std::vector<std::string> key_id_to_wif_pair_strings = options["private-key"].as<std::vector<std::string>>(); for (const std::string& key_id_to_wif_pair_string : key_id_to_wif_pair_strings) { auto key_id_to_wif_pair = graphene::app::dejsonify<std::pair<chain::public_key_type, std::string> >(key_id_to_wif_pair_string); //idump((key_id_to_wif_pair)); ilog("Public Key: ${public}", ("public", key_id_to_wif_pair.first)); fc::optional<fc::ecc::private_key> private_key = graphene::utilities::wif_to_key(key_id_to_wif_pair.second); if (!private_key) { // the key isn't in WIF format; see if they are still passing the old native private key format. This is // just here to ease the transition, can be removed soon try { private_key = fc::variant(key_id_to_wif_pair.second).as<fc::ecc::private_key>(); } catch (const fc::exception&) { FC_THROW("Invalid WIF-format private key ${key_string}", ("key_string", key_id_to_wif_pair.second)); } } _private_keys[key_id_to_wif_pair.first] = *private_key; } } ilog("witness plugin: plugin_initialize() end"); } FC_LOG_AND_RETHROW() } void witness_plugin::plugin_startup() { try { ilog("witness plugin: plugin_startup() begin"); chain::database& d = database(); if( !_witnesses.empty() ) { ilog("Launching block production for ${n} witnesses.", ("n", _witnesses.size())); app().set_block_production(true); if( _production_enabled ) { if( d.head_block_num() == 0 ) new_chain_banner(d); _production_skip_flags |= graphene::chain::database::skip_undo_history_check; } schedule_production_loop(); } else elog("No witnesses configured! Please add witness IDs and private keys to configuration."); ilog("witness plugin: plugin_startup() end"); } FC_CAPTURE_AND_RETHROW() } void witness_plugin::plugin_shutdown() { return; } void witness_plugin::schedule_production_loop() { //Schedule for the next second's tick regardless of chain state // If we would wait less than 50ms, wait for the whole second. fc::time_point now = fc::time_point::now(); int64_t time_to_next_second = 1000000 - (now.time_since_epoch().count() % 1000000); if( time_to_next_second < 50000 ) // we must sleep for at least 50ms time_to_next_second += 1000000; fc::time_point next_wakeup( now + fc::microseconds( time_to_next_second ) ); //wdump( (now.time_since_epoch().count())(next_wakeup.time_since_epoch().count()) ); _block_production_task = fc::schedule([this]{block_production_loop();}, next_wakeup, "Witness Block Production"); } block_production_condition::block_production_condition_enum witness_plugin::block_production_loop() { block_production_condition::block_production_condition_enum result; fc::mutable_variant_object capture; try { result = maybe_produce_block(capture); } catch( const fc::canceled_exception& ) { //We're trying to exit. Go ahead and let this one out. throw; } catch( const fc::exception& e ) { elog("Got exception while generating block:\n${e}", ("e", e.to_detail_string())); result = block_production_condition::exception_producing_block; } switch( result ) { case block_production_condition::produced: ilog("Generated block #${n} with timestamp ${t} at time ${c}", (capture)); break; case block_production_condition::not_synced: ilog("Not producing block because production is disabled until we receive a recent block (see: --enable-stale-production)"); break; case block_production_condition::not_my_turn: //ilog("Not producing block because it isn't my turn"); break; case block_production_condition::not_time_yet: //ilog("Not producing block because slot has not yet arrived"); break; case block_production_condition::no_private_key: ilog("Not producing block because I don't have the private key for ${scheduled_key}", (capture) ); break; case block_production_condition::low_participation: elog("Not producing block because node appears to be on a minority fork with only ${pct}% witness participation", (capture) ); break; case block_production_condition::lag: elog("Not producing block because node didn't wake up within 500ms of the slot time."); break; case block_production_condition::consecutive: elog("Not producing block because the last block was generated by the same witness.\nThis node is probably disconnected from the network so block production has been disabled.\nDisable this check with --allow-consecutive option."); break; case block_production_condition::exception_producing_block: elog( "exception prodcing block" ); break; } schedule_production_loop(); return result; } block_production_condition::block_production_condition_enum witness_plugin::maybe_produce_block( fc::mutable_variant_object& capture ) { chain::database& db = database(); fc::time_point now_fine = fc::time_point::now(); fc::time_point_sec now = now_fine + fc::microseconds( 500000 ); // If the next block production opportunity is in the present or future, we're synced. if( !_production_enabled ) { if( db.get_slot_time(1) >= now ) _production_enabled = true; else return block_production_condition::not_synced; } // is anyone scheduled to produce now or one second in the future? uint32_t slot = db.get_slot_at_time( now ); if( slot == 0 ) { capture("next_time", db.get_slot_time(1)); return block_production_condition::not_time_yet; } // // this assert should not fail, because now <= db.head_block_time() // should have resulted in slot == 0. // // if this assert triggers, there is a serious bug in get_slot_at_time() // which would result in allowing a later block to have a timestamp // less than or equal to the previous block // assert( now > db.head_block_time() ); graphene::chain::witness_id_type scheduled_witness = db.get_scheduled_witness( slot ); // we must control the witness scheduled to produce the next block. if( _witnesses.find( scheduled_witness ) == _witnesses.end() ) { capture("scheduled_witness", scheduled_witness); return block_production_condition::not_my_turn; } fc::time_point_sec scheduled_time = db.get_slot_time( slot ); graphene::chain::public_key_type scheduled_key = scheduled_witness( db ).signing_key; auto private_key_itr = _private_keys.find( scheduled_key ); if( private_key_itr == _private_keys.end() ) { capture("scheduled_key", scheduled_key); return block_production_condition::no_private_key; } uint32_t prate = db.witness_participation_rate(); if( prate < _required_witness_participation ) { capture("pct", uint32_t(100*uint64_t(prate) / GRAPHENE_1_PERCENT)); return block_production_condition::low_participation; } if( llabs((scheduled_time - now).count()) > fc::milliseconds( 500 ).count() ) { capture("scheduled_time", scheduled_time)("now", now); return block_production_condition::lag; } auto block = db.generate_block( scheduled_time, scheduled_witness, private_key_itr->second, _production_skip_flags ); capture("n", block.block_num())("t", block.timestamp)("c", now); fc::async( [this,block](){ p2p_node().broadcast(net::block_message(block)); } ); return block_production_condition::produced; } <commit_msg>change welcome<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <graphene/witness/witness.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/witness_object.hpp> #include <graphene/utilities/key_conversion.hpp> #include <fc/smart_ref_impl.hpp> #include <fc/thread/thread.hpp> #include <iostream> using namespace graphene::witness_plugin; using std::string; using std::vector; namespace bpo = boost::program_options; void new_chain_banner( const graphene::chain::database& db ) { std::cerr << "\n" "********************************\n" "* *\n" "* ------- NEW CHAIN ------ *\n" "* - Welcome to FinChain! - *\n" "* ------------------------ *\n" "* powered by Graphene *\n" "********************************\n" "\n"; if( db.get_slot_at_time( fc::time_point::now() ) > 200 ) { std::cerr << "Your genesis seems to have an old timestamp\n" "Please consider using the --genesis-timestamp option to give your genesis a recent timestamp\n" "\n" ; } return; } void witness_plugin::plugin_set_program_options( boost::program_options::options_description& command_line_options, boost::program_options::options_description& config_file_options) { auto default_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(std::string("nathan"))); string witness_id_example = fc::json::to_string(chain::witness_id_type(5)); command_line_options.add_options() ("enable-stale-production", bpo::bool_switch()->notifier([this](bool e){_production_enabled = e;}), "Enable block production, even if the chain is stale.") ("required-participation", bpo::bool_switch()->notifier([this](int e){_required_witness_participation = uint32_t(e*GRAPHENE_1_PERCENT);}), "Percent of witnesses (0-99) that must be participating in order to produce blocks") ("witness-id,w", bpo::value<vector<string>>()->composing()->multitoken(), ("ID of witness controlled by this node (e.g. " + witness_id_example + ", quotes are required, may specify multiple times)").c_str()) ("private-key", bpo::value<vector<string>>()->composing()->multitoken()-> DEFAULT_VALUE_VECTOR(std::make_pair(chain::public_key_type(default_priv_key.get_public_key()), graphene::utilities::key_to_wif(default_priv_key))), "Tuple of [PublicKey, WIF private key] (may specify multiple times)") ; config_file_options.add(command_line_options); } std::string witness_plugin::plugin_name()const { return "witness"; } void witness_plugin::plugin_initialize(const boost::program_options::variables_map& options) { try { ilog("witness plugin: plugin_initialize() begin"); _options = &options; LOAD_VALUE_SET(options, "witness-id", _witnesses, chain::witness_id_type) if( options.count("private-key") ) { const std::vector<std::string> key_id_to_wif_pair_strings = options["private-key"].as<std::vector<std::string>>(); for (const std::string& key_id_to_wif_pair_string : key_id_to_wif_pair_strings) { auto key_id_to_wif_pair = graphene::app::dejsonify<std::pair<chain::public_key_type, std::string> >(key_id_to_wif_pair_string); //idump((key_id_to_wif_pair)); ilog("Public Key: ${public}", ("public", key_id_to_wif_pair.first)); fc::optional<fc::ecc::private_key> private_key = graphene::utilities::wif_to_key(key_id_to_wif_pair.second); if (!private_key) { // the key isn't in WIF format; see if they are still passing the old native private key format. This is // just here to ease the transition, can be removed soon try { private_key = fc::variant(key_id_to_wif_pair.second).as<fc::ecc::private_key>(); } catch (const fc::exception&) { FC_THROW("Invalid WIF-format private key ${key_string}", ("key_string", key_id_to_wif_pair.second)); } } _private_keys[key_id_to_wif_pair.first] = *private_key; } } ilog("witness plugin: plugin_initialize() end"); } FC_LOG_AND_RETHROW() } void witness_plugin::plugin_startup() { try { ilog("witness plugin: plugin_startup() begin"); chain::database& d = database(); if( !_witnesses.empty() ) { ilog("Launching block production for ${n} witnesses.", ("n", _witnesses.size())); app().set_block_production(true); if( _production_enabled ) { if( d.head_block_num() == 0 ) new_chain_banner(d); _production_skip_flags |= graphene::chain::database::skip_undo_history_check; } schedule_production_loop(); } else elog("No witnesses configured! Please add witness IDs and private keys to configuration."); ilog("witness plugin: plugin_startup() end"); } FC_CAPTURE_AND_RETHROW() } void witness_plugin::plugin_shutdown() { return; } void witness_plugin::schedule_production_loop() { //Schedule for the next second's tick regardless of chain state // If we would wait less than 50ms, wait for the whole second. fc::time_point now = fc::time_point::now(); int64_t time_to_next_second = 1000000 - (now.time_since_epoch().count() % 1000000); if( time_to_next_second < 50000 ) // we must sleep for at least 50ms time_to_next_second += 1000000; fc::time_point next_wakeup( now + fc::microseconds( time_to_next_second ) ); //wdump( (now.time_since_epoch().count())(next_wakeup.time_since_epoch().count()) ); _block_production_task = fc::schedule([this]{block_production_loop();}, next_wakeup, "Witness Block Production"); } block_production_condition::block_production_condition_enum witness_plugin::block_production_loop() { block_production_condition::block_production_condition_enum result; fc::mutable_variant_object capture; try { result = maybe_produce_block(capture); } catch( const fc::canceled_exception& ) { //We're trying to exit. Go ahead and let this one out. throw; } catch( const fc::exception& e ) { elog("Got exception while generating block:\n${e}", ("e", e.to_detail_string())); result = block_production_condition::exception_producing_block; } switch( result ) { case block_production_condition::produced: ilog("Generated block #${n} with timestamp ${t} at time ${c}", (capture)); break; case block_production_condition::not_synced: ilog("Not producing block because production is disabled until we receive a recent block (see: --enable-stale-production)"); break; case block_production_condition::not_my_turn: //ilog("Not producing block because it isn't my turn"); break; case block_production_condition::not_time_yet: //ilog("Not producing block because slot has not yet arrived"); break; case block_production_condition::no_private_key: ilog("Not producing block because I don't have the private key for ${scheduled_key}", (capture) ); break; case block_production_condition::low_participation: elog("Not producing block because node appears to be on a minority fork with only ${pct}% witness participation", (capture) ); break; case block_production_condition::lag: elog("Not producing block because node didn't wake up within 500ms of the slot time."); break; case block_production_condition::consecutive: elog("Not producing block because the last block was generated by the same witness.\nThis node is probably disconnected from the network so block production has been disabled.\nDisable this check with --allow-consecutive option."); break; case block_production_condition::exception_producing_block: elog( "exception prodcing block" ); break; } schedule_production_loop(); return result; } block_production_condition::block_production_condition_enum witness_plugin::maybe_produce_block( fc::mutable_variant_object& capture ) { chain::database& db = database(); fc::time_point now_fine = fc::time_point::now(); fc::time_point_sec now = now_fine + fc::microseconds( 500000 ); // If the next block production opportunity is in the present or future, we're synced. if( !_production_enabled ) { if( db.get_slot_time(1) >= now ) _production_enabled = true; else return block_production_condition::not_synced; } // is anyone scheduled to produce now or one second in the future? uint32_t slot = db.get_slot_at_time( now ); if( slot == 0 ) { capture("next_time", db.get_slot_time(1)); return block_production_condition::not_time_yet; } // // this assert should not fail, because now <= db.head_block_time() // should have resulted in slot == 0. // // if this assert triggers, there is a serious bug in get_slot_at_time() // which would result in allowing a later block to have a timestamp // less than or equal to the previous block // assert( now > db.head_block_time() ); graphene::chain::witness_id_type scheduled_witness = db.get_scheduled_witness( slot ); // we must control the witness scheduled to produce the next block. if( _witnesses.find( scheduled_witness ) == _witnesses.end() ) { capture("scheduled_witness", scheduled_witness); return block_production_condition::not_my_turn; } fc::time_point_sec scheduled_time = db.get_slot_time( slot ); graphene::chain::public_key_type scheduled_key = scheduled_witness( db ).signing_key; auto private_key_itr = _private_keys.find( scheduled_key ); if( private_key_itr == _private_keys.end() ) { capture("scheduled_key", scheduled_key); return block_production_condition::no_private_key; } uint32_t prate = db.witness_participation_rate(); if( prate < _required_witness_participation ) { capture("pct", uint32_t(100*uint64_t(prate) / GRAPHENE_1_PERCENT)); return block_production_condition::low_participation; } if( llabs((scheduled_time - now).count()) > fc::milliseconds( 500 ).count() ) { capture("scheduled_time", scheduled_time)("now", now); return block_production_condition::lag; } auto block = db.generate_block( scheduled_time, scheduled_witness, private_key_itr->second, _production_skip_flags ); capture("n", block.block_num())("t", block.timestamp)("c", now); fc::async( [this,block](){ p2p_node().broadcast(net::block_message(block)); } ); return block_production_condition::produced; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // glInfo.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "glInfo.h" #include "Core/Assert.h" #include "Core/Log.h" #include "Core/String/StringBuilder.h" #include "Render/gl/gl_impl.h" namespace Oryol { namespace Render { using namespace Core; //------------------------------------------------------------------------------ void glInfo::PrintInfo() { glInfo::PrintString(GL_VERSION, "GL_VERSION", false); glInfo::PrintString(GL_SHADING_LANGUAGE_VERSION, "GL_SHADING_LANGUAGE_VERSION", false); glInfo::PrintString(GL_VENDOR, "GL_VENDOR", false); glInfo::PrintString(GL_RENDERER, "GL_RENDERER", false); #if !ORYOL_MACOS // on OSX, core profile is used, where getting the extensions string is an error glInfo::PrintString(GL_EXTENSIONS, "GL_EXTENSIONS", true); #endif } //------------------------------------------------------------------------------ void glInfo::PrintString(GLenum glEnum, const char* name, bool replaceSpaceWithNewLine) { o_assert(name); String str = (const char*) ::glGetString(glEnum); ORYOL_GL_CHECK_ERROR(); if (replaceSpaceWithNewLine) { StringBuilder strBuilder; strBuilder.Append(" "); strBuilder.Append(str); strBuilder.SubstituteAll(" ", "\n"); str = strBuilder.GetString(); } Log::Info("%s: %s\n", name, str.AsCStr()); } //------------------------------------------------------------------------------ void glInfo::PrintInt(GLenum glEnum, const char* name, int dim) { o_assert(name); o_assert_range(dim, 4); GLint value[4]; ::glGetIntegerv(glEnum, &(value[0])); ORYOL_GL_CHECK_ERROR(); if (1 == dim) Log::Info("%s: %d\n", name, value[0]); else if (2 == dim) Log::Info("%s: %d %d\n", name, value[0], value[1]); else if (3 == dim) Log::Info("%s: %d %d %d\n", name, value[0], value[1], value[2]); else if (4 == dim) Log::Info("%s: %d %d %d %d\n", name, value[0], value[1], value[2], value[3]); } } // namespace Render } // namespace Oryol <commit_msg>Minor fix for glGetString can return nullptr<commit_after>//------------------------------------------------------------------------------ // glInfo.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "glInfo.h" #include "Core/Assert.h" #include "Core/Log.h" #include "Core/String/StringBuilder.h" #include "Render/gl/gl_impl.h" namespace Oryol { namespace Render { using namespace Core; //------------------------------------------------------------------------------ void glInfo::PrintInfo() { glInfo::PrintString(GL_VERSION, "GL_VERSION", false); glInfo::PrintString(GL_SHADING_LANGUAGE_VERSION, "GL_SHADING_LANGUAGE_VERSION", false); glInfo::PrintString(GL_VENDOR, "GL_VENDOR", false); glInfo::PrintString(GL_RENDERER, "GL_RENDERER", false); #if !ORYOL_MACOS // on OSX, core profile is used, where getting the extensions string is an error glInfo::PrintString(GL_EXTENSIONS, "GL_EXTENSIONS", true); #endif } //------------------------------------------------------------------------------ void glInfo::PrintString(GLenum glEnum, const char* name, bool replaceSpaceWithNewLine) { o_assert(name); const char* rawStr = (const char*) ::glGetString(glEnum); ORYOL_GL_CHECK_ERROR(); if (rawStr) { String str(rawStr); if (replaceSpaceWithNewLine) { StringBuilder strBuilder; strBuilder.Append(" "); strBuilder.Append(str); strBuilder.SubstituteAll(" ", "\n"); str = strBuilder.GetString(); } Log::Info("%s: %s\n", name, str.AsCStr()); } else { Log::Warn("::glGetString() returned nullptr!\n"); } } //------------------------------------------------------------------------------ void glInfo::PrintInt(GLenum glEnum, const char* name, int dim) { o_assert(name); o_assert_range(dim, 4); GLint value[4]; ::glGetIntegerv(glEnum, &(value[0])); ORYOL_GL_CHECK_ERROR(); if (1 == dim) Log::Info("%s: %d\n", name, value[0]); else if (2 == dim) Log::Info("%s: %d %d\n", name, value[0], value[1]); else if (3 == dim) Log::Info("%s: %d %d %d\n", name, value[0], value[1], value[2]); else if (4 == dim) Log::Info("%s: %d %d %d %d\n", name, value[0], value[1], value[2], value[3]); } } // namespace Render } // namespace Oryol <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/source_command.hpp" #include <csignal> #include <caf/config_value.hpp> #include <caf/scoped_actor.hpp> #include <caf/typed_event_based_actor.hpp> #include "vast/detail/string.hpp" #include "vast/error.hpp" #include "vast/expression.hpp" #include "vast/filesystem.hpp" #include "vast/logger.hpp" #include "vast/schema.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/expression.hpp" #include "vast/concept/parseable/vast/schema.hpp" #include "vast/system/signal_monitor.hpp" #include "vast/system/source.hpp" #include "vast/system/tracker.hpp" namespace vast::system { source_command::source_command(command* parent, std::string_view name) : super(parent, name) { // nop } caf::expected<schema> load_schema_file(std::string& path) { if (path.empty()) return make_error(ec::filesystem_error, ""); auto str = load_contents(path); if (!str) return str.error(); return to<schema>(*str); } caf::expected<expression> parse_expression(command::argument_iterator begin, command::argument_iterator end) { auto str = detail::join(begin, end, " "); auto expr = to<expression>(str); if (expr) expr = normalize_and_validate(*expr); return expr; } int source_command::run_impl(caf::actor_system& sys, const caf::config_value_map& options, argument_iterator begin, argument_iterator end) { using namespace caf; using namespace std::chrono_literals; // Helper for blocking actor communication. scoped_actor self{sys}; // Spawn the source. auto src_opt = make_source(self, options); if (!src_opt) { VAST_ERROR(self, "was not able to spawn a source", sys.render(src_opt.error())); return EXIT_FAILURE; } auto src = std::move(*src_opt); // Supply an alternate schema, if requested. if (auto sf = caf::get_if<std::string>(&options, "schema")) { auto schema = load_schema_file(*sf); if (!schema) { VAST_ERROR(self, "had a schema error:", sys.render(schema.error())); return EXIT_FAILURE; } self->send(src, put_atom::value, std::move(*schema)); } // Attempt to parse the remainder as an expression. if (begin != end) { auto expr = parse_expression(begin, end); if (!expr) { VAST_ERROR(self, "failed to parse the remaining arguments:", sys.render(expr.error())); return EXIT_FAILURE; } self->send(src, std::move(*expr)); } // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, options); if (!node_opt) return EXIT_FAILURE; auto node = std::move(*node_opt); VAST_DEBUG(this, "got node"); /// Spawn an actor that takes care of CTRL+C and friends. auto sig_mon = self->spawn<detached>(system::signal_monitor, 750ms, actor{self}); auto guard = caf::detail::make_scope_guard([&] { self->send_exit(sig_mon, exit_reason::user_shutdown); }); // Set defaults. int rc = EXIT_FAILURE; auto stop = false; // Connect source to importers. caf::actor importer; self->request(node, infinite, get_atom::value).receive( [&](const std::string& id, system::registry& reg) { auto er = reg.components[id].equal_range("importer"); if (er.first == er.second) { VAST_ERROR(this, "did not receive any importers from node", id); stop = true; } else if (reg.components[id].count("importer") > 1) { VAST_ERROR(this, "does not support multiple IMPORTER actors yet"); stop = true; } else { VAST_DEBUG(this, "connects to importer"); importer = er.first->second.actor; self->send(src, system::sink_atom::value, importer); } }, [&](const error& e) { VAST_IGNORE_UNUSED(e); VAST_ERROR(this, self->system().render(e)); stop = true; } ); if (stop) { cleanup(node); return rc; } // Start the source. rc = EXIT_SUCCESS; self->send(src, system::run_atom::value); self->monitor(src); self->do_receive( [&](const down_msg& msg) { if (msg.source == node) { VAST_DEBUG(this, "received DOWN from node"); self->send_exit(src, exit_reason::user_shutdown); rc = EXIT_FAILURE; stop = true; } else if (msg.source == src) { VAST_DEBUG(this, "received DOWN from source"); if (caf::get_or(options, "blocking", false)) self->send(importer, subscribe_atom::value, flush_atom::value, self); else stop = true; } }, [&](flush_atom) { VAST_DEBUG(this, "received flush from IMPORTER"); stop = true; }, [&](system::signal_atom, int signal) { VAST_DEBUG(this, "got " << ::strsignal(signal)); if (signal == SIGINT || signal == SIGTERM) self->send_exit(src, exit_reason::user_shutdown); } ).until(stop); cleanup(node); return rc; } } // namespace vast::system <commit_msg>Bring back --schema option in source_command<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/source_command.hpp" #include <csignal> #include <caf/config_value.hpp> #include <caf/scoped_actor.hpp> #include <caf/typed_event_based_actor.hpp> #include "vast/detail/string.hpp" #include "vast/error.hpp" #include "vast/expression.hpp" #include "vast/filesystem.hpp" #include "vast/logger.hpp" #include "vast/schema.hpp" #include "vast/concept/parseable/to.hpp" #include "vast/concept/parseable/vast/expression.hpp" #include "vast/concept/parseable/vast/schema.hpp" #include "vast/system/signal_monitor.hpp" #include "vast/system/source.hpp" #include "vast/system/tracker.hpp" namespace vast::system { source_command::source_command(command* parent, std::string_view name) : super(parent, name) { add_opt<std::string>("schema,s", "path to alternate schema"); } caf::expected<schema> load_schema_file(std::string& path) { if (path.empty()) return make_error(ec::filesystem_error, ""); auto str = load_contents(path); if (!str) return str.error(); return to<schema>(*str); } caf::expected<expression> parse_expression(command::argument_iterator begin, command::argument_iterator end) { auto str = detail::join(begin, end, " "); auto expr = to<expression>(str); if (expr) expr = normalize_and_validate(*expr); return expr; } int source_command::run_impl(caf::actor_system& sys, const caf::config_value_map& options, argument_iterator begin, argument_iterator end) { using namespace caf; using namespace std::chrono_literals; // Helper for blocking actor communication. scoped_actor self{sys}; // Spawn the source. auto src_opt = make_source(self, options); if (!src_opt) { VAST_ERROR(self, "was not able to spawn a source", sys.render(src_opt.error())); return EXIT_FAILURE; } auto src = std::move(*src_opt); // Supply an alternate schema, if requested. if (auto sf = caf::get_if<std::string>(&options, "schema")) { auto schema = load_schema_file(*sf); if (!schema) { VAST_ERROR(self, "had a schema error:", sys.render(schema.error())); return EXIT_FAILURE; } self->send(src, put_atom::value, std::move(*schema)); } // Attempt to parse the remainder as an expression. if (begin != end) { auto expr = parse_expression(begin, end); if (!expr) { VAST_ERROR(self, "failed to parse the remaining arguments:", sys.render(expr.error())); return EXIT_FAILURE; } self->send(src, std::move(*expr)); } // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, options); if (!node_opt) return EXIT_FAILURE; auto node = std::move(*node_opt); VAST_DEBUG(this, "got node"); /// Spawn an actor that takes care of CTRL+C and friends. auto sig_mon = self->spawn<detached>(system::signal_monitor, 750ms, actor{self}); auto guard = caf::detail::make_scope_guard([&] { self->send_exit(sig_mon, exit_reason::user_shutdown); }); // Set defaults. int rc = EXIT_FAILURE; auto stop = false; // Connect source to importers. caf::actor importer; self->request(node, infinite, get_atom::value).receive( [&](const std::string& id, system::registry& reg) { auto er = reg.components[id].equal_range("importer"); if (er.first == er.second) { VAST_ERROR(this, "did not receive any importers from node", id); stop = true; } else if (reg.components[id].count("importer") > 1) { VAST_ERROR(this, "does not support multiple IMPORTER actors yet"); stop = true; } else { VAST_DEBUG(this, "connects to importer"); importer = er.first->second.actor; self->send(src, system::sink_atom::value, importer); } }, [&](const error& e) { VAST_IGNORE_UNUSED(e); VAST_ERROR(this, self->system().render(e)); stop = true; } ); if (stop) { cleanup(node); return rc; } // Start the source. rc = EXIT_SUCCESS; self->send(src, system::run_atom::value); self->monitor(src); self->do_receive( [&](const down_msg& msg) { if (msg.source == node) { VAST_DEBUG(this, "received DOWN from node"); self->send_exit(src, exit_reason::user_shutdown); rc = EXIT_FAILURE; stop = true; } else if (msg.source == src) { VAST_DEBUG(this, "received DOWN from source"); if (caf::get_or(options, "blocking", false)) self->send(importer, subscribe_atom::value, flush_atom::value, self); else stop = true; } }, [&](flush_atom) { VAST_DEBUG(this, "received flush from IMPORTER"); stop = true; }, [&](system::signal_atom, int signal) { VAST_DEBUG(this, "got " << ::strsignal(signal)); if (signal == SIGINT || signal == SIGTERM) self->send_exit(src, exit_reason::user_shutdown); } ).until(stop); cleanup(node); return rc; } } // namespace vast::system <|endoftext|>
<commit_before>#include "drake/common/text_logging.h" #include <mutex> namespace drake { #ifdef HAVE_SPDLOG namespace { // Returns a new pointer (caller-owned) to a shared_ptr to a logger. // // NOTE: This function assumes that it is mutexed, as in the initializer of // a static local. std::shared_ptr<logging::logger>* onetime_create_log() { std::shared_ptr<logging::logger>* result = new std::shared_ptr<logging::logger>(spdlog::get("console")); if (!*result) { *result = spdlog::stderr_logger_st("console"); } return result; } } // anonymous logging::logger* log() { // The following line creates a static shared_ptr to the logger; this // guarantees the underling logger object will not be dtor'ed. static const std::shared_ptr<logging::logger>* const g_logger = onetime_create_log(); return g_logger->get(); } #else // HAVE_SPDLOG // A do-nothing logger instance. namespace { const logger g_logger; } // anon namespace logging::logger* log() { return std::shared_ptr<logging::logger>(&g_logger); } #endif // HAVE_SPDLOG } // namespace drake <commit_msg>stomp another shared_ptr<commit_after>#include "drake/common/text_logging.h" #include <mutex> namespace drake { #ifdef HAVE_SPDLOG namespace { // Returns a new pointer (caller-owned) to a shared_ptr to a logger. // // NOTE: This function assumes that it is mutexed, as in the initializer of // a static local. std::shared_ptr<logging::logger>* onetime_create_log() { std::shared_ptr<logging::logger>* result = new std::shared_ptr<logging::logger>(spdlog::get("console")); if (!*result) { *result = spdlog::stderr_logger_st("console"); } return result; } } // anonymous logging::logger* log() { // The following line creates a static shared_ptr to the logger; this // guarantees the underling logger object will not be dtor'ed. static const std::shared_ptr<logging::logger>* const g_logger = onetime_create_log(); return g_logger->get(); } #else // HAVE_SPDLOG // A do-nothing logger instance. namespace { const logger g_logger; } // anon namespace logging::logger* log() { return &g_logger; } #endif // HAVE_SPDLOG } // namespace drake <|endoftext|>
<commit_before>/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory> #include <dbus/dbus.h> #include <unistd.h> #include "common/code_utils.hpp" #include "dbus/client/thread_api_dbus.hpp" #include "dbus/common/constants.hpp" using otbr::DBus::ActiveScanResult; using otbr::DBus::ClientError; using otbr::DBus::DeviceRole; using otbr::DBus::ExternalRoute; using otbr::DBus::Ip6Prefix; using otbr::DBus::LinkModeConfig; using otbr::DBus::OnMeshPrefix; using otbr::DBus::ThreadApiDBus; #define TEST_ASSERT(x) \ do \ { \ if (!(x)) \ { \ printf("Assert failed at %s:%d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } while (false) struct DBusConnectionDeleter { void operator()(DBusConnection *aConnection) { dbus_connection_unref(aConnection); } }; using UniqueDBusConnection = std::unique_ptr<DBusConnection, DBusConnectionDeleter>; static bool operator==(const otbr::DBus::Ip6Prefix &aLhs, const otbr::DBus::Ip6Prefix &aRhs) { bool prefixDataEquality = (aLhs.mPrefix.size() == aRhs.mPrefix.size()) && (memcmp(&aLhs.mPrefix[0], &aRhs.mPrefix[0], aLhs.mPrefix.size()) == 0); return prefixDataEquality && aLhs.mLength == aRhs.mLength; } static void CheckExternalRoute(ThreadApiDBus *aApi, const Ip6Prefix &aPrefix) { ExternalRoute route; std::vector<ExternalRoute> externalRouteTable; route.mPrefix = aPrefix; route.mStable = true; route.mPreference = 0; TEST_ASSERT(aApi->AddExternalRoute(route) == OTBR_ERROR_NONE); TEST_ASSERT(aApi->GetExternalRoutes(externalRouteTable) == OTBR_ERROR_NONE); TEST_ASSERT(externalRouteTable.size() == 1); TEST_ASSERT(externalRouteTable[0].mPrefix == aPrefix); TEST_ASSERT(externalRouteTable[0].mPreference == 0); TEST_ASSERT(externalRouteTable[0].mStable); TEST_ASSERT(externalRouteTable[0].mNextHopIsThisDevice); TEST_ASSERT(aApi->RemoveExternalRoute(aPrefix) == OTBR_ERROR_NONE); } int main() { DBusError error; UniqueDBusConnection connection; std::unique_ptr<ThreadApiDBus> api; uint64_t extpanid = 0xdead00beaf00cafe; std::string region; dbus_error_init(&error); connection = UniqueDBusConnection(dbus_bus_get(DBUS_BUS_SYSTEM, &error)); VerifyOrExit(connection != nullptr); VerifyOrExit(dbus_bus_register(connection.get(), &error) == true); api = std::unique_ptr<ThreadApiDBus>(new ThreadApiDBus(connection.get())); api->AddDeviceRoleHandler( [](DeviceRole aRole) { printf("Device role changed to %d\n", static_cast<uint8_t>(aRole)); }); TEST_ASSERT(api->SetRadioRegion("US") == ClientError::ERROR_NONE); TEST_ASSERT(api->GetRadioRegion(region) == ClientError::ERROR_NONE); TEST_ASSERT(region == "US"); api->Scan([&api, extpanid](const std::vector<ActiveScanResult> &aResult) { LinkModeConfig cfg = {true, false, true}; std::vector<uint8_t> networkKey = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}; uint16_t channel = 11; for (auto &&result : aResult) { printf("%s channel %d rssi %d\n", result.mNetworkName.c_str(), result.mChannel, result.mRssi); } api->SetLinkMode(cfg); api->GetLinkMode(cfg); printf("LinkMode %d %d %d\n", cfg.mRxOnWhenIdle, cfg.mDeviceType, cfg.mNetworkData); cfg.mDeviceType = true; api->SetLinkMode(cfg); api->Attach("Test", 0x3456, extpanid, networkKey, {}, 1 << channel, [&api, channel, extpanid](ClientError aError) { printf("Attach result %d\n", static_cast<int>(aError)); sleep(10); uint64_t extpanidCheck; std::vector<uint8_t> activeDataset; if (aError == OTBR_ERROR_NONE) { std::string name; uint64_t extAddress = 0; uint16_t rloc16 = 0xffff; std::vector<uint8_t> networkData; std::vector<uint8_t> stableNetworkData; int8_t rssi; int8_t txPower; std::vector<otbr::DBus::ChildInfo> childTable; std::vector<otbr::DBus::NeighborInfo> neighborTable; uint32_t partitionId; uint16_t channelResult; TEST_ASSERT(api->GetChannel(channelResult) == OTBR_ERROR_NONE); TEST_ASSERT(channelResult == channel); TEST_ASSERT(api->GetNetworkName(name) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetExtPanId(extpanidCheck) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetRloc16(rloc16) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetExtendedAddress(extAddress) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetNetworkData(networkData) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetStableNetworkData(stableNetworkData) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetChildTable(childTable) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetNeighborTable(neighborTable) == OTBR_ERROR_NONE); printf("neighborTable size %zu\n", neighborTable.size()); printf("childTable size %zu\n", childTable.size()); TEST_ASSERT(neighborTable.size() == 1); TEST_ASSERT(childTable.size() == 1); TEST_ASSERT(api->GetPartitionId(partitionId) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetInstantRssi(rssi) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetRadioTxPower(txPower) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetActiveDatasetTlvs(activeDataset) == OTBR_ERROR_NONE); api->FactoryReset(nullptr); TEST_ASSERT(api->GetNetworkName(name) == OTBR_ERROR_NONE); TEST_ASSERT(rloc16 != 0xffff); TEST_ASSERT(extAddress != 0); TEST_ASSERT(!networkData.empty()); TEST_ASSERT(api->GetNeighborTable(neighborTable) == OTBR_ERROR_NONE); TEST_ASSERT(neighborTable.empty()); } if (aError != OTBR_ERROR_NONE || extpanidCheck != extpanid) { exit(-1); } TEST_ASSERT(api->SetActiveDatasetTlvs(activeDataset) == OTBR_ERROR_NONE); api->Attach([&api, channel, extpanid](ClientError aErr) { uint8_t routerId; otbr::DBus::LeaderData leaderData; uint8_t leaderWeight; uint16_t channelResult; uint64_t extpanidCheck; Ip6Prefix prefix; OnMeshPrefix onMeshPrefix = {}; prefix.mPrefix = {0xfd, 0xcd, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; prefix.mLength = 64; onMeshPrefix.mPrefix = prefix; onMeshPrefix.mPreference = 0; onMeshPrefix.mStable = true; TEST_ASSERT(aErr == ClientError::ERROR_NONE); TEST_ASSERT(api->GetChannel(channelResult) == OTBR_ERROR_NONE); TEST_ASSERT(channelResult == channel); TEST_ASSERT(api->GetExtPanId(extpanidCheck) == OTBR_ERROR_NONE); TEST_ASSERT(extpanidCheck == extpanid); TEST_ASSERT(api->GetLocalLeaderWeight(leaderWeight) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetLeaderData(leaderData) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetRouterId(routerId) == OTBR_ERROR_NONE); TEST_ASSERT(routerId == leaderData.mLeaderRouterId); CheckExternalRoute(api.get(), prefix); TEST_ASSERT(api->AddOnMeshPrefix(onMeshPrefix) == OTBR_ERROR_NONE); TEST_ASSERT(api->RemoveOnMeshPrefix(onMeshPrefix.mPrefix) == OTBR_ERROR_NONE); api->FactoryReset(nullptr); TEST_ASSERT(api->JoinerStart("ABCDEF", "", "", "", "", "", nullptr) == ClientError::OT_ERROR_NOT_FOUND); TEST_ASSERT(api->JoinerStart("ABCDEF", "", "", "", "", "", [](ClientError aJoinError) { TEST_ASSERT(aJoinError == ClientError::OT_ERROR_NOT_FOUND); exit(0); }) == ClientError::ERROR_NONE); }); }); }); while (true) { dbus_connection_read_write_dispatch(connection.get(), 0); } exit: dbus_error_free(&error); return 0; }; <commit_msg>[tests] add test for `FactoryReset` DBus API (#929)<commit_after>/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory> #include <dbus/dbus.h> #include <unistd.h> #include "common/code_utils.hpp" #include "dbus/client/thread_api_dbus.hpp" #include "dbus/common/constants.hpp" using otbr::DBus::ActiveScanResult; using otbr::DBus::ClientError; using otbr::DBus::DeviceRole; using otbr::DBus::ExternalRoute; using otbr::DBus::Ip6Prefix; using otbr::DBus::LinkModeConfig; using otbr::DBus::OnMeshPrefix; using otbr::DBus::ThreadApiDBus; #define TEST_ASSERT(x) \ do \ { \ if (!(x)) \ { \ printf("Assert failed at %s:%d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } while (false) struct DBusConnectionDeleter { void operator()(DBusConnection *aConnection) { dbus_connection_unref(aConnection); } }; using UniqueDBusConnection = std::unique_ptr<DBusConnection, DBusConnectionDeleter>; static bool operator==(const otbr::DBus::Ip6Prefix &aLhs, const otbr::DBus::Ip6Prefix &aRhs) { bool prefixDataEquality = (aLhs.mPrefix.size() == aRhs.mPrefix.size()) && (memcmp(&aLhs.mPrefix[0], &aRhs.mPrefix[0], aLhs.mPrefix.size()) == 0); return prefixDataEquality && aLhs.mLength == aRhs.mLength; } static void CheckExternalRoute(ThreadApiDBus *aApi, const Ip6Prefix &aPrefix) { ExternalRoute route; std::vector<ExternalRoute> externalRouteTable; route.mPrefix = aPrefix; route.mStable = true; route.mPreference = 0; TEST_ASSERT(aApi->AddExternalRoute(route) == OTBR_ERROR_NONE); TEST_ASSERT(aApi->GetExternalRoutes(externalRouteTable) == OTBR_ERROR_NONE); TEST_ASSERT(externalRouteTable.size() == 1); TEST_ASSERT(externalRouteTable[0].mPrefix == aPrefix); TEST_ASSERT(externalRouteTable[0].mPreference == 0); TEST_ASSERT(externalRouteTable[0].mStable); TEST_ASSERT(externalRouteTable[0].mNextHopIsThisDevice); TEST_ASSERT(aApi->RemoveExternalRoute(aPrefix) == OTBR_ERROR_NONE); } int main() { DBusError error; UniqueDBusConnection connection; std::unique_ptr<ThreadApiDBus> api; uint64_t extpanid = 0xdead00beaf00cafe; std::string region; dbus_error_init(&error); connection = UniqueDBusConnection(dbus_bus_get(DBUS_BUS_SYSTEM, &error)); VerifyOrExit(connection != nullptr); VerifyOrExit(dbus_bus_register(connection.get(), &error) == true); api = std::unique_ptr<ThreadApiDBus>(new ThreadApiDBus(connection.get())); api->AddDeviceRoleHandler( [](DeviceRole aRole) { printf("Device role changed to %d\n", static_cast<uint8_t>(aRole)); }); TEST_ASSERT(api->SetRadioRegion("US") == ClientError::ERROR_NONE); TEST_ASSERT(api->GetRadioRegion(region) == ClientError::ERROR_NONE); TEST_ASSERT(region == "US"); api->Scan([&api, extpanid](const std::vector<ActiveScanResult> &aResult) { LinkModeConfig cfg = {true, false, true}; std::vector<uint8_t> networkKey = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}; uint16_t channel = 11; for (auto &&result : aResult) { printf("%s channel %d rssi %d\n", result.mNetworkName.c_str(), result.mChannel, result.mRssi); } api->SetLinkMode(cfg); api->GetLinkMode(cfg); printf("LinkMode %d %d %d\n", cfg.mRxOnWhenIdle, cfg.mDeviceType, cfg.mNetworkData); cfg.mDeviceType = true; api->SetLinkMode(cfg); api->Attach("Test", 0x3456, extpanid, networkKey, {}, 1 << channel, [&api, channel, extpanid](ClientError aError) { printf("Attach result %d\n", static_cast<int>(aError)); sleep(10); uint64_t extpanidCheck; std::vector<uint8_t> activeDataset; if (aError == OTBR_ERROR_NONE) { std::string name; uint64_t extAddress = 0; uint16_t rloc16 = 0xffff; std::vector<uint8_t> networkData; std::vector<uint8_t> stableNetworkData; int8_t rssi; int8_t txPower; std::vector<otbr::DBus::ChildInfo> childTable; std::vector<otbr::DBus::NeighborInfo> neighborTable; uint32_t partitionId; uint16_t channelResult; TEST_ASSERT(api->GetChannel(channelResult) == OTBR_ERROR_NONE); TEST_ASSERT(channelResult == channel); TEST_ASSERT(api->GetNetworkName(name) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetExtPanId(extpanidCheck) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetRloc16(rloc16) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetExtendedAddress(extAddress) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetNetworkData(networkData) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetStableNetworkData(stableNetworkData) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetChildTable(childTable) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetNeighborTable(neighborTable) == OTBR_ERROR_NONE); printf("neighborTable size %zu\n", neighborTable.size()); printf("childTable size %zu\n", childTable.size()); TEST_ASSERT(neighborTable.size() == 1); TEST_ASSERT(childTable.size() == 1); TEST_ASSERT(api->GetPartitionId(partitionId) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetInstantRssi(rssi) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetRadioTxPower(txPower) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetActiveDatasetTlvs(activeDataset) == OTBR_ERROR_NONE); api->FactoryReset(nullptr); TEST_ASSERT(api->GetNetworkName(name) == OTBR_ERROR_NONE); TEST_ASSERT(rloc16 != 0xffff); TEST_ASSERT(extAddress != 0); TEST_ASSERT(!networkData.empty()); TEST_ASSERT(api->GetNeighborTable(neighborTable) == OTBR_ERROR_NONE); TEST_ASSERT(neighborTable.empty()); } if (aError != OTBR_ERROR_NONE || extpanidCheck != extpanid) { exit(-1); } TEST_ASSERT(api->SetActiveDatasetTlvs(activeDataset) == OTBR_ERROR_NONE); api->Attach([&api, channel, extpanid](ClientError aErr) { uint8_t routerId; otbr::DBus::LeaderData leaderData; uint8_t leaderWeight; uint16_t channelResult; uint64_t extpanidCheck; Ip6Prefix prefix; OnMeshPrefix onMeshPrefix = {}; prefix.mPrefix = {0xfd, 0xcd, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; prefix.mLength = 64; onMeshPrefix.mPrefix = prefix; onMeshPrefix.mPreference = 0; onMeshPrefix.mStable = true; TEST_ASSERT(aErr == ClientError::ERROR_NONE); TEST_ASSERT(api->GetChannel(channelResult) == OTBR_ERROR_NONE); TEST_ASSERT(channelResult == channel); TEST_ASSERT(api->GetExtPanId(extpanidCheck) == OTBR_ERROR_NONE); TEST_ASSERT(extpanidCheck == extpanid); TEST_ASSERT(api->GetLocalLeaderWeight(leaderWeight) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetLeaderData(leaderData) == OTBR_ERROR_NONE); TEST_ASSERT(api->GetRouterId(routerId) == OTBR_ERROR_NONE); TEST_ASSERT(routerId == leaderData.mLeaderRouterId); CheckExternalRoute(api.get(), prefix); TEST_ASSERT(api->AddOnMeshPrefix(onMeshPrefix) == OTBR_ERROR_NONE); TEST_ASSERT(api->RemoveOnMeshPrefix(onMeshPrefix.mPrefix) == OTBR_ERROR_NONE); api->FactoryReset(nullptr); TEST_ASSERT(api->JoinerStart("ABCDEF", "", "", "", "", "", nullptr) == ClientError::OT_ERROR_NOT_FOUND); TEST_ASSERT(api->JoinerStart("ABCDEF", "", "", "", "", "", [&api](ClientError aJoinError) { DeviceRole deviceRole; TEST_ASSERT(aJoinError == ClientError::OT_ERROR_NOT_FOUND); api->FactoryReset(nullptr); api->GetDeviceRole(deviceRole); TEST_ASSERT(deviceRole == otbr::DBus::OTBR_DEVICE_ROLE_DISABLED); exit(0); }) == ClientError::ERROR_NONE); }); }); }); while (true) { dbus_connection_read_write_dispatch(connection.get(), 0); } exit: dbus_error_free(&error); return 0; }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: absdev.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:56:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SOT_ABSDEV_HXX #define _SOT_ABSDEV_HXX #ifndef _TOOLS_SOLAR_H #include <tools/solar.h> #endif class JobSetup; class AbstractDeviceData { protected: JobSetup * pJobSetup; public: virtual ~AbstractDeviceData() {} virtual AbstractDeviceData * Copy() const = 0; virtual BOOL Equals( const AbstractDeviceData & ) const = 0; JobSetup * GetJobSetup() const { return pJobSetup; } }; #endif // _SOT_ABSDEV_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.256); FILE MERGED 2005/09/05 18:47:24 rt 1.1.1.1.256.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: absdev.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:33:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SOT_ABSDEV_HXX #define _SOT_ABSDEV_HXX #ifndef _TOOLS_SOLAR_H #include <tools/solar.h> #endif class JobSetup; class AbstractDeviceData { protected: JobSetup * pJobSetup; public: virtual ~AbstractDeviceData() {} virtual AbstractDeviceData * Copy() const = 0; virtual BOOL Equals( const AbstractDeviceData & ) const = 0; JobSetup * GetJobSetup() const { return pJobSetup; } }; #endif // _SOT_ABSDEV_HXX <|endoftext|>
<commit_before>/******************************* Copyright (c) 2016-2020 Grégoire Angerand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **********************************/ #include "transforms.h" #include <yave/meshes/MeshData.h> #include <yave/animations/Animation.h> #include <yave/graphics/images/ImageData.h> #include <y/utils/log.h> #include <y/utils/perf.h> namespace editor { namespace import { template<typename T> static core::Vector<T> copy(core::Span<T> t) { return core::Vector<T>(t); } static math::Vec3 h_transform(const math::Vec3& v, const math::Transform<>& tr) { const auto h = tr * math::Vec4(v, 1.0f); return h.to<3>() / h.w(); } static math::Vec3 transform(const math::Vec3& v, const math::Transform<>& tr) { return tr.to<3, 3>() * v; } static Vertex transform(const Vertex& v, const math::Transform<>& tr) { return Vertex { h_transform(v.position, tr), transform(v.normal, tr).normalized(), transform(v.tangent, tr).normalized(), v.uv }; } static BoneTransform transform(const BoneTransform& bone, const math::Transform<>& tr) { auto [pos, rot, scale] = tr.decompose(); return BoneTransform { bone.position + pos, bone.scale * scale, bone.rotation * rot }; } MeshData transform(const MeshData& mesh, const math::Transform<>& tr) { y_profile(); auto vertices = core::vector_with_capacity<Vertex>(mesh.vertices().size()); std::transform(mesh.vertices().begin(), mesh.vertices().end(), std::back_inserter(vertices), [=](const auto& vert) { return transform(vert, tr); }); if(mesh.has_skeleton()) { auto bones = core::vector_with_capacity<Bone>(mesh.bones().size()); std::transform(mesh.bones().begin(), mesh.bones().end(), std::back_inserter(bones), [=](const auto& bone) { return bone.has_parent() ? bone : Bone{bone.name, bone.parent, transform(bone.local_transform, tr)}; }); return MeshData(std::move(vertices), copy(mesh.triangles()), copy(mesh.skin()), std::move(bones)); } return MeshData(std::move(vertices), copy(mesh.triangles())); } MeshData compute_tangents(const MeshData& mesh) { y_profile(); core::Vector<Vertex> vertices = copy(mesh.vertices()); core::Vector<IndexedTriangle> triangles = copy(mesh.triangles()); for(IndexedTriangle tri : triangles) { const math::Vec3 edges[] = {vertices[tri[1]].position - vertices[tri[0]].position, vertices[tri[2]].position - vertices[tri[0]].position}; const math::Vec2 uvs[] = {vertices[tri[0]].uv, vertices[tri[1]].uv, vertices[tri[2]].uv}; const float dt[] = {uvs[1].y() - uvs[0].y(), uvs[2].y() - uvs[0].y()}; math::Vec3 ta = -((edges[0] * dt[1]) - (edges[1] * dt[0])).normalized(); vertices[tri[0]].tangent += ta; vertices[tri[1]].tangent += ta; vertices[tri[2]].tangent += ta; } for(Vertex& v : vertices) { v.tangent.normalize(); } return MeshData(std::move(vertices), std::move(triangles), copy(mesh.skin()), copy(mesh.bones())); } static AnimationChannel set_speed(const AnimationChannel& anim, float speed) { y_profile(); auto keys = core::vector_with_capacity<AnimationChannel::BoneKey>(anim.keys().size()); std::transform(anim.keys().begin(), anim.keys().end(), std::back_inserter(keys), [=](const auto& key){ return AnimationChannel::BoneKey{key.time / speed, key.local_transform}; }); return AnimationChannel(anim.name(), std::move(keys)); } static ImageData copy(const ImageData& image) { return ImageData(image.size().to<2>(), image.data(), image.format(), image.mipmaps()); } Animation set_speed(const Animation& anim, float speed) { y_profile(); auto channels = core::vector_with_capacity<AnimationChannel>(anim.channels().size()); std::transform(anim.channels().begin(), anim.channels().end(), std::back_inserter(channels), [=](const auto& channel){ return set_speed(channel, speed); }); return Animation(anim.duration() / speed, std::move(channels)); } ImageData compute_mipmaps(const ImageData& image) { y_profile(); if(image.layers() != 1 || image.size().z() != 1) { log_msg("Only one layer is supported.", Log::Error); return copy(image); } if(image.format() != ImageFormat(VK_FORMAT_R8G8B8A8_UNORM)) { log_msg("Only RGBA is supported.", Log::Error); return copy(image); } const ImageFormat format(VK_FORMAT_R8G8B8A8_UNORM); const usize components = 4; const usize mip_count = ImageData::mip_count(image.size()); const usize data_size = ImageData::layer_byte_size(image.size(), format, mip_count); const std::unique_ptr<u8[]> data = std::make_unique<u8[]>(data_size); const auto compute_mip = [&](const u8* image_data, u8* output, const math::Vec2ui& orig_size) -> usize { usize cursor = 0; const math::Vec2ui mip_size = {std::max(1u, orig_size.x() / 2), std::max(1u, orig_size.y() / 2)}; usize row_size = orig_size.x(); for(usize y = 0; y != mip_size.y(); ++y) { for(usize x = 0; x != mip_size.x(); ++x) { const usize orig = (x * 2 + y * 2 * row_size); for(usize c = 0; c != components; ++c) { u32 acc = image_data[components * (orig) + c]; acc += image_data[components * (orig + 1) + c]; acc += image_data[components * (orig + row_size) + c]; acc += image_data[components * (orig + row_size + 1) + c]; y_debug_assert(output + cursor < data.get() + data_size); output[cursor++] = std::min(acc / 4, 0xFFu); } } } return cursor; }; u8* image_data = data.get(); usize mip_byte_size = image.byte_size(0); std::memcpy(image_data, image.data(), mip_byte_size); for(usize mip = 0; mip < mip_count - 1; ++mip) { const usize s = compute_mip(image_data, image_data + mip_byte_size, image.size(mip).to<2>()); image_data += mip_byte_size; mip_byte_size = s; } y_debug_assert(image_data + mip_byte_size == data.get() + data_size); return ImageData(image.size().to<2>(), data.get(), format, mip_count); } } } <commit_msg>Fixed mipmaping not working for sRGB textures<commit_after>/******************************* Copyright (c) 2016-2020 Grégoire Angerand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **********************************/ #include "transforms.h" #include <yave/meshes/MeshData.h> #include <yave/animations/Animation.h> #include <yave/graphics/images/ImageData.h> #include <y/utils/log.h> #include <y/utils/perf.h> namespace editor { namespace import { template<typename T> static core::Vector<T> copy(core::Span<T> t) { return core::Vector<T>(t); } static math::Vec3 h_transform(const math::Vec3& v, const math::Transform<>& tr) { const auto h = tr * math::Vec4(v, 1.0f); return h.to<3>() / h.w(); } static math::Vec3 transform(const math::Vec3& v, const math::Transform<>& tr) { return tr.to<3, 3>() * v; } static Vertex transform(const Vertex& v, const math::Transform<>& tr) { return Vertex { h_transform(v.position, tr), transform(v.normal, tr).normalized(), transform(v.tangent, tr).normalized(), v.uv }; } static BoneTransform transform(const BoneTransform& bone, const math::Transform<>& tr) { auto [pos, rot, scale] = tr.decompose(); return BoneTransform { bone.position + pos, bone.scale * scale, bone.rotation * rot }; } MeshData transform(const MeshData& mesh, const math::Transform<>& tr) { y_profile(); auto vertices = core::vector_with_capacity<Vertex>(mesh.vertices().size()); std::transform(mesh.vertices().begin(), mesh.vertices().end(), std::back_inserter(vertices), [=](const auto& vert) { return transform(vert, tr); }); if(mesh.has_skeleton()) { auto bones = core::vector_with_capacity<Bone>(mesh.bones().size()); std::transform(mesh.bones().begin(), mesh.bones().end(), std::back_inserter(bones), [=](const auto& bone) { return bone.has_parent() ? bone : Bone{bone.name, bone.parent, transform(bone.local_transform, tr)}; }); return MeshData(std::move(vertices), copy(mesh.triangles()), copy(mesh.skin()), std::move(bones)); } return MeshData(std::move(vertices), copy(mesh.triangles())); } MeshData compute_tangents(const MeshData& mesh) { y_profile(); core::Vector<Vertex> vertices = copy(mesh.vertices()); core::Vector<IndexedTriangle> triangles = copy(mesh.triangles()); for(IndexedTriangle tri : triangles) { const math::Vec3 edges[] = {vertices[tri[1]].position - vertices[tri[0]].position, vertices[tri[2]].position - vertices[tri[0]].position}; const math::Vec2 uvs[] = {vertices[tri[0]].uv, vertices[tri[1]].uv, vertices[tri[2]].uv}; const float dt[] = {uvs[1].y() - uvs[0].y(), uvs[2].y() - uvs[0].y()}; math::Vec3 ta = -((edges[0] * dt[1]) - (edges[1] * dt[0])).normalized(); vertices[tri[0]].tangent += ta; vertices[tri[1]].tangent += ta; vertices[tri[2]].tangent += ta; } for(Vertex& v : vertices) { v.tangent.normalize(); } return MeshData(std::move(vertices), std::move(triangles), copy(mesh.skin()), copy(mesh.bones())); } static AnimationChannel set_speed(const AnimationChannel& anim, float speed) { y_profile(); auto keys = core::vector_with_capacity<AnimationChannel::BoneKey>(anim.keys().size()); std::transform(anim.keys().begin(), anim.keys().end(), std::back_inserter(keys), [=](const auto& key){ return AnimationChannel::BoneKey{key.time / speed, key.local_transform}; }); return AnimationChannel(anim.name(), std::move(keys)); } static ImageData copy(const ImageData& image) { return ImageData(image.size().to<2>(), image.data(), image.format(), image.mipmaps()); } Animation set_speed(const Animation& anim, float speed) { y_profile(); auto channels = core::vector_with_capacity<AnimationChannel>(anim.channels().size()); std::transform(anim.channels().begin(), anim.channels().end(), std::back_inserter(channels), [=](const auto& channel){ return set_speed(channel, speed); }); return Animation(anim.duration() / speed, std::move(channels)); } template<typename T> static float to_normalized(T t) { return float(t) / std::numeric_limits<T>::max(); } core::FixedArray<float> compute_mipmaps_internal(core::FixedArray<float> input, const math::Vec2ui& size, usize mip_count, bool sRGB = false) { y_profile(); const usize components = 4; y_debug_assert(size.x() * size.y() * components == input.size()); if(sRGB) { y_profile_zone("degamma"); for(usize i = 0; i != input.size(); ++i) { input[i] = std::pow(input[i], 2.2f); } } const ImageFormat normalized_format = VK_FORMAT_R32G32B32A32_SFLOAT; const usize output_size = ImageData::layer_byte_size(math::Vec3ui(size, 1), normalized_format, mip_count) / sizeof(float); core::FixedArray<float> output(output_size); { const auto compute_mip = [](const float* image_data, float* out, const math::Vec2ui& orig_size) -> usize { usize cursor = 0; const math::Vec2ui mip_size = {std::max(1u, orig_size.x() / 2), std::max(1u, orig_size.y() / 2)}; const usize row_size = orig_size.x(); for(usize y = 0; y != mip_size.y(); ++y) { for(usize x = 0; x != mip_size.x(); ++x) { const usize orig = (x * 2 + y * 2 * row_size); for(usize cc = 0; cc != components; ++cc) { const float a = image_data[components * (orig) + cc]; const float b = image_data[components * (orig + 1) + cc]; const float c = image_data[components * (orig + row_size) + cc]; const float d = image_data[components * (orig + row_size + 1) + cc]; out[cursor++] = std::min((a + b + c + d) * 0.25f, 1.0f); } } } return cursor; }; float* out_data = output.data(); usize mip_values = size.x() * size.y() * components; std::copy_n(input.data(), mip_values, out_data); for(usize mip = 0; mip < mip_count - 1; ++mip) { const usize s = compute_mip(out_data, out_data + mip_values, ImageData::mip_size(math::Vec3ui(size, 1), mip).to<2>()); out_data += mip_values; mip_values = s; } } if(sRGB) { y_profile_zone("regamma"); for(usize i = 0; i != output.size(); ++i) { output[i] = std::pow(output[i], 1.0f / 2.2f); } } return output; } ImageData compute_mipmaps(const ImageData& image) { y_profile(); if(image.layers() != 1 || image.size().z() != 1) { log_msg("Only one layer is supported.", Log::Error); return copy(image); } const bool is_sRGB = image.format() == ImageFormat(VK_FORMAT_R8G8B8A8_SRGB); if(image.format() != ImageFormat(VK_FORMAT_R8G8B8A8_UNORM) && !is_sRGB) { log_msg("Only RGBA is supported.", Log::Error); return copy(image); } const usize components = 4; const usize texels = image.size().x() * image.size().y(); const usize mip_count = ImageData::mip_count(image.size()); core::FixedArray<float> input(texels * components); { y_profile_zone("normalization"); const u8* image_data = image.data(); for(usize i = 0; i != input.size(); ++i) { input[i] = to_normalized(image_data[i]); } } core::FixedArray<float> output = compute_mipmaps_internal(std::move(input), image.size().to<2>(), mip_count, is_sRGB); core::FixedArray<u8> data(output.size()); { y_profile_zone("denormalization"); for(usize i = 0; i != output.size(); ++i) { data[i] = u8(output[i] * 255.0f); } } output.clear(); return ImageData(image.size().to<2>(), data.data(), image.format(), mip_count); } } } <|endoftext|>
<commit_before>// $Id$ // Author: Matevz Tadel 2009 /************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #include "AliEveMultiView.h" #include <TGPack.h> #include <TBrowser.h> //______________________________________________________________________________ // Full description of AliEveMultiView // ClassImp(AliEveMultiView) AliEveMultiView* AliEveMultiView::fgInstance = 0; AliEveMultiView* AliEveMultiView::Instance() { // Return static instance. return fgInstance; } AliEveMultiView::AliEveMultiView(Bool_t setMuonView) : fRPhiMgr(0), fRhoZMgr(0), fMuonMgr(0), f3DView(0), fRPhiView(0), fRhoZView(0), fMuonView(0), fRPhiGeomScene(0), fRhoZGeomScene(0), fMuonGeomScene(0), fRPhiEventScene(0), fRhoZEventScene(0), fMuonEventScene(0), fGeomGentle(0), fGeomGentleRPhi(0), fGeomGentleRhoZ(0), fGeomGentleTrd(0), fGeomGentleMuon(0), fIsMuonView(kFALSE), fPack(0) { // Constructor --- creates required scenes, projection managers // and GL viewers. if (fgInstance) throw TEveException("AliEveMultiView::AliEveMultiView already instantiated."); fgInstance = this; // Scenes //======== fRPhiGeomScene = gEve->SpawnNewScene("RPhi Geometry", "Scene holding projected geometry for the RPhi view."); fRhoZGeomScene = gEve->SpawnNewScene("RhoZ Geometry", "Scene holding projected geometry for the RhoZ view."); fMuonGeomScene = gEve->SpawnNewScene("Muon Geometry", "Scene holding projected geometry for the Muon view."); fRPhiEventScene = gEve->SpawnNewScene("RPhi Event Data", "Scene holding projected event-data for the RPhi view."); fRhoZEventScene = gEve->SpawnNewScene("RhoZ Event Data", "Scene holding projected event-data for the RhoZ view."); fMuonEventScene = gEve->SpawnNewScene("Muon Event Data", "Scene holding projected event-data for the Muon view."); fIsMuonView = setMuonView; // Projection managers //===================== fRPhiMgr = new TEveProjectionManager(); fRPhiMgr->SetProjection(TEveProjection::kPT_RPhi); gEve->AddToListTree(fRPhiMgr, kFALSE); { TEveProjectionAxes* a = new TEveProjectionAxes(fRPhiMgr); a->SetMainColor(kWhite); a->SetTitle("R-Phi"); a->SetTitleSize(0.05); a->SetTitleFont(102); a->SetLabelSize(0.025); a->SetLabelFont(102); fRPhiGeomScene->AddElement(a); } fRhoZMgr = new TEveProjectionManager(); fRhoZMgr->SetProjection(TEveProjection::kPT_RhoZ); gEve->AddToListTree(fRhoZMgr, kFALSE); { TEveProjectionAxes* a = new TEveProjectionAxes(fRhoZMgr); a->SetMainColor(kWhite); a->SetTitle("Rho-Z"); a->SetTitleSize(0.05); a->SetTitleFont(102); a->SetLabelSize(0.025); a->SetLabelFont(102); fRhoZGeomScene->AddElement(a); } if(fIsMuonView) { fMuonMgr = new TEveProjectionManager(); fMuonMgr->SetProjection(TEveProjection::kPT_RhoZ); gEve->AddToListTree(fMuonMgr, kFALSE); { TEveProjectionAxes* a = new TEveProjectionAxes(fMuonMgr); a->SetMainColor(kWhite); a->SetTitle("Rho-Z Muon"); a->SetTitleSize(0.05); a->SetTitleFont(102); a->SetLabelSize(0.025); a->SetLabelFont(102); fMuonGeomScene->AddElement(a); } } // Viewers //========= TEveWindowSlot *slot = 0; TEveWindowPack *pack = 0; slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); pack = slot->MakePack(); // slot is destroyed here pack->SetElementName("Multi View"); pack->SetHorizontal(); pack->SetShowTitleBar(kFALSE); pack->NewSlot()->MakeCurrent(); // new slot is created from pack f3DView = gEve->SpawnNewViewer("3D View", ""); f3DView->AddScene(gEve->GetGlobalScene()); f3DView->AddScene(gEve->GetEventScene()); pack = pack->NewSlot()->MakePack(); // new slot created from pack, then slot is destroyed and new pack returned pack->SetShowTitleBar(kFALSE); pack->NewSlot()->MakeCurrent(); // new slot from pack fRPhiView = gEve->SpawnNewViewer("RPhi View", ""); fRPhiView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); fRPhiView->AddScene(fRPhiGeomScene); fRPhiView->AddScene(fRPhiEventScene); fPack = pack; pack->NewSlot()->MakeCurrent(); // new slot from pack fRhoZView = gEve->SpawnNewViewer("RhoZ View", ""); fRhoZView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); fRhoZView->AddScene(fRhoZGeomScene); fRhoZView->AddScene(fRhoZEventScene); if(fIsMuonView) { pack->NewSlot()->MakeCurrent(); // new slot from pack fMuonView = gEve->SpawnNewViewer("RhoZ View Muon", ""); fMuonView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); fMuonView->AddScene(fMuonGeomScene); fMuonView->AddScene(fMuonEventScene); } } AliEveMultiView::~AliEveMultiView() { DestroyAllGeometries(); delete fGeomGentle; delete fGeomGentleRPhi; delete fGeomGentleRhoZ; delete fRPhiMgr; delete fRhoZMgr; delete fMuonMgr; } //------------------------------------------------------------------------- void AliEveMultiView::InitGeomGentle(TEveGeoShape* g3d, TEveGeoShape* grphi, TEveGeoShape* grhoz, TEveGeoShape* gmuon) { // Initialize gentle geometry. fGeomGentle = g3d; fGeomGentleRPhi = grphi; fGeomGentleRPhi->IncDenyDestroy(); fGeomGentleRhoZ = grhoz; fGeomGentleRhoZ->IncDenyDestroy(); if(fIsMuonView) { fGeomGentleMuon = gmuon; fGeomGentleMuon->IncDenyDestroy(); } ImportGeomRPhi(fGeomGentleRPhi); ImportGeomRhoZ(fGeomGentleRhoZ); if(fIsMuonView) ImportGeomMuon(fGeomGentleMuon); } void AliEveMultiView::InitGeomGentleTrd(TEveGeoShape* gtrd) { // Initialize gentle geometry TRD. fGeomGentleTrd = gtrd; ImportGeomRPhi(fGeomGentleTrd); ImportGeomRhoZ(fGeomGentleTrd); if(fIsMuonView) ImportGeomMuon(fGeomGentleTrd); } void AliEveMultiView::InitGeomGentleMuon(TEveGeoShape* gmuon, Bool_t showRPhi, Bool_t showRhoZ, Bool_t showMuon) { // Initialize gentle geometry for MUON. fGeomGentleMuon = gmuon; if (showRPhi) ImportGeomRPhi(fGeomGentleMuon); if (showRhoZ) ImportGeomRhoZ(fGeomGentleMuon); if (showMuon && fIsMuonView) ImportGeomMuon(fGeomGentleMuon); } //------------------------------------------------------------------------- void AliEveMultiView::SetDepth(Float_t d) { // Set current depth on all projection managers. fRPhiMgr->SetCurrentDepth(d); fRhoZMgr->SetCurrentDepth(d); if(fIsMuonView) fMuonMgr->SetCurrentDepth(d); } //------------------------------------------------------------------------- void AliEveMultiView::ImportGeomRPhi(TEveElement* el) { // Import el into r-phi geometry scene. fRPhiMgr->ImportElements(el, fRPhiGeomScene); } void AliEveMultiView::ImportGeomRhoZ(TEveElement* el) { // Import el into rho-z geometry scene. fRhoZMgr->ImportElements(el, fRhoZGeomScene); } void AliEveMultiView::ImportGeomMuon(TEveElement* el) { // Import el into muon geometry scene. if(fIsMuonView) fMuonMgr->ImportElements(el, fMuonGeomScene); } void AliEveMultiView::ImportEventRPhi(TEveElement* el) { // Import el into r-phi event scene. fRPhiMgr->ImportElements(el, fRPhiEventScene); } void AliEveMultiView::ImportEventRhoZ(TEveElement* el) { // Import el into rho-z event scene. fRhoZMgr->ImportElements(el, fRhoZEventScene); } void AliEveMultiView::ImportEventMuon(TEveElement* el) { // Import el into muon event scene. if(fIsMuonView) fMuonMgr->ImportElements(el, fMuonEventScene); } void AliEveMultiView::DestroyEventRPhi() { // Destroy all elements in r-phi event scene. fRPhiEventScene->DestroyElements(); } void AliEveMultiView::DestroyEventRhoZ() { // Destroy all elements in rho-z event scene. fRhoZEventScene->DestroyElements(); } void AliEveMultiView::DestroyEventMuon() { // Destroy all elements in rho-z event scene. if(fIsMuonView) fMuonEventScene->DestroyElements(); } //------------------------------------------------------------------------- void AliEveMultiView::SetCenterRPhi(Double_t x, Double_t y, Double_t z) { // Set center of r-phi manager. fRPhiMgr->SetCenter(x, y, z); } void AliEveMultiView::SetCenterRhoZ(Double_t x, Double_t y, Double_t z) { // Set center of rho-z manager. fRhoZMgr->SetCenter(x, y, z); } void AliEveMultiView::SetCenterMuon(Double_t x, Double_t y, Double_t z) { // Set center of rho-z manager. if(fIsMuonView) fMuonMgr->SetCenter(x, y, z); } void AliEveMultiView::DestroyAllGeometries() { // Destroy 3d, r-phi and rho-z geometries. fGeomGentle->DestroyElements(); fGeomGentleRPhi->DestroyElements(); fGeomGentleRhoZ->DestroyElements(); if(fIsMuonView) fGeomGentleMuon->DestroyElements(); } <commit_msg>update of the ratio of the size of 3D view and RhoPhi, RhoZ views in MultiView mode from 1:1 to 2:1<commit_after>// $Id$ // Author: Matevz Tadel 2009 /************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #include "AliEveMultiView.h" #include <TGPack.h> #include <TBrowser.h> //______________________________________________________________________________ // Full description of AliEveMultiView // ClassImp(AliEveMultiView) AliEveMultiView* AliEveMultiView::fgInstance = 0; AliEveMultiView* AliEveMultiView::Instance() { // Return static instance. return fgInstance; } AliEveMultiView::AliEveMultiView(Bool_t setMuonView) : fRPhiMgr(0), fRhoZMgr(0), fMuonMgr(0), f3DView(0), fRPhiView(0), fRhoZView(0), fMuonView(0), fRPhiGeomScene(0), fRhoZGeomScene(0), fMuonGeomScene(0), fRPhiEventScene(0), fRhoZEventScene(0), fMuonEventScene(0), fGeomGentle(0), fGeomGentleRPhi(0), fGeomGentleRhoZ(0), fGeomGentleTrd(0), fGeomGentleMuon(0), fIsMuonView(kFALSE), fPack(0) { // Constructor --- creates required scenes, projection managers // and GL viewers. if (fgInstance) throw TEveException("AliEveMultiView::AliEveMultiView already instantiated."); fgInstance = this; // Scenes //======== fRPhiGeomScene = gEve->SpawnNewScene("RPhi Geometry", "Scene holding projected geometry for the RPhi view."); fRhoZGeomScene = gEve->SpawnNewScene("RhoZ Geometry", "Scene holding projected geometry for the RhoZ view."); fMuonGeomScene = gEve->SpawnNewScene("Muon Geometry", "Scene holding projected geometry for the Muon view."); fRPhiEventScene = gEve->SpawnNewScene("RPhi Event Data", "Scene holding projected event-data for the RPhi view."); fRhoZEventScene = gEve->SpawnNewScene("RhoZ Event Data", "Scene holding projected event-data for the RhoZ view."); fMuonEventScene = gEve->SpawnNewScene("Muon Event Data", "Scene holding projected event-data for the Muon view."); fIsMuonView = setMuonView; // Projection managers //===================== fRPhiMgr = new TEveProjectionManager(); fRPhiMgr->SetProjection(TEveProjection::kPT_RPhi); gEve->AddToListTree(fRPhiMgr, kFALSE); { TEveProjectionAxes* a = new TEveProjectionAxes(fRPhiMgr); a->SetMainColor(kWhite); a->SetTitle("R-Phi"); a->SetTitleSize(0.05); a->SetTitleFont(102); a->SetLabelSize(0.025); a->SetLabelFont(102); fRPhiGeomScene->AddElement(a); } fRhoZMgr = new TEveProjectionManager(); fRhoZMgr->SetProjection(TEveProjection::kPT_RhoZ); gEve->AddToListTree(fRhoZMgr, kFALSE); { TEveProjectionAxes* a = new TEveProjectionAxes(fRhoZMgr); a->SetMainColor(kWhite); a->SetTitle("Rho-Z"); a->SetTitleSize(0.05); a->SetTitleFont(102); a->SetLabelSize(0.025); a->SetLabelFont(102); fRhoZGeomScene->AddElement(a); } if(fIsMuonView) { fMuonMgr = new TEveProjectionManager(); fMuonMgr->SetProjection(TEveProjection::kPT_RhoZ); gEve->AddToListTree(fMuonMgr, kFALSE); { TEveProjectionAxes* a = new TEveProjectionAxes(fMuonMgr); a->SetMainColor(kWhite); a->SetTitle("Rho-Z Muon"); a->SetTitleSize(0.05); a->SetTitleFont(102); a->SetLabelSize(0.025); a->SetLabelFont(102); fMuonGeomScene->AddElement(a); } } // Viewers //========= TEveWindowSlot *slot = 0; TEveWindowPack *pack = 0; slot = TEveWindow::CreateWindowInTab(gEve->GetBrowser()->GetTabRight()); pack = slot->MakePack(); // slot is destroyed here pack->SetElementName("Multi View"); pack->SetHorizontal(); pack->SetShowTitleBar(kFALSE); pack->NewSlotWithWeight(2)->MakeCurrent(); // new slot is created from pack f3DView = gEve->SpawnNewViewer("3D View", ""); f3DView->AddScene(gEve->GetGlobalScene()); f3DView->AddScene(gEve->GetEventScene()); pack = pack->NewSlot()->MakePack(); // new slot created from pack, then slot is destroyed and new pack returned pack->SetShowTitleBar(kFALSE); pack->NewSlot()->MakeCurrent(); // new slot from pack fRPhiView = gEve->SpawnNewViewer("RPhi View", ""); fRPhiView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); fRPhiView->AddScene(fRPhiGeomScene); fRPhiView->AddScene(fRPhiEventScene); fPack = pack; pack->NewSlot()->MakeCurrent(); // new slot from pack fRhoZView = gEve->SpawnNewViewer("RhoZ View", ""); fRhoZView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); fRhoZView->AddScene(fRhoZGeomScene); fRhoZView->AddScene(fRhoZEventScene); if(fIsMuonView) { pack->NewSlot()->MakeCurrent(); // new slot from pack fMuonView = gEve->SpawnNewViewer("RhoZ View Muon", ""); fMuonView->GetGLViewer()->SetCurrentCamera(TGLViewer::kCameraOrthoXOY); fMuonView->AddScene(fMuonGeomScene); fMuonView->AddScene(fMuonEventScene); } } AliEveMultiView::~AliEveMultiView() { DestroyAllGeometries(); delete fGeomGentle; delete fGeomGentleRPhi; delete fGeomGentleRhoZ; delete fRPhiMgr; delete fRhoZMgr; delete fMuonMgr; } //------------------------------------------------------------------------- void AliEveMultiView::InitGeomGentle(TEveGeoShape* g3d, TEveGeoShape* grphi, TEveGeoShape* grhoz, TEveGeoShape* gmuon) { // Initialize gentle geometry. fGeomGentle = g3d; fGeomGentleRPhi = grphi; fGeomGentleRPhi->IncDenyDestroy(); fGeomGentleRhoZ = grhoz; fGeomGentleRhoZ->IncDenyDestroy(); if(fIsMuonView) { fGeomGentleMuon = gmuon; fGeomGentleMuon->IncDenyDestroy(); } ImportGeomRPhi(fGeomGentleRPhi); ImportGeomRhoZ(fGeomGentleRhoZ); if(fIsMuonView) ImportGeomMuon(fGeomGentleMuon); } void AliEveMultiView::InitGeomGentleTrd(TEveGeoShape* gtrd) { // Initialize gentle geometry TRD. fGeomGentleTrd = gtrd; ImportGeomRPhi(fGeomGentleTrd); ImportGeomRhoZ(fGeomGentleTrd); if(fIsMuonView) ImportGeomMuon(fGeomGentleTrd); } void AliEveMultiView::InitGeomGentleMuon(TEveGeoShape* gmuon, Bool_t showRPhi, Bool_t showRhoZ, Bool_t showMuon) { // Initialize gentle geometry for MUON. fGeomGentleMuon = gmuon; if (showRPhi) ImportGeomRPhi(fGeomGentleMuon); if (showRhoZ) ImportGeomRhoZ(fGeomGentleMuon); if (showMuon && fIsMuonView) ImportGeomMuon(fGeomGentleMuon); } //------------------------------------------------------------------------- void AliEveMultiView::SetDepth(Float_t d) { // Set current depth on all projection managers. fRPhiMgr->SetCurrentDepth(d); fRhoZMgr->SetCurrentDepth(d); if(fIsMuonView) fMuonMgr->SetCurrentDepth(d); } //------------------------------------------------------------------------- void AliEveMultiView::ImportGeomRPhi(TEveElement* el) { // Import el into r-phi geometry scene. fRPhiMgr->ImportElements(el, fRPhiGeomScene); } void AliEveMultiView::ImportGeomRhoZ(TEveElement* el) { // Import el into rho-z geometry scene. fRhoZMgr->ImportElements(el, fRhoZGeomScene); } void AliEveMultiView::ImportGeomMuon(TEveElement* el) { // Import el into muon geometry scene. if(fIsMuonView) fMuonMgr->ImportElements(el, fMuonGeomScene); } void AliEveMultiView::ImportEventRPhi(TEveElement* el) { // Import el into r-phi event scene. fRPhiMgr->ImportElements(el, fRPhiEventScene); } void AliEveMultiView::ImportEventRhoZ(TEveElement* el) { // Import el into rho-z event scene. fRhoZMgr->ImportElements(el, fRhoZEventScene); } void AliEveMultiView::ImportEventMuon(TEveElement* el) { // Import el into muon event scene. if(fIsMuonView) fMuonMgr->ImportElements(el, fMuonEventScene); } void AliEveMultiView::DestroyEventRPhi() { // Destroy all elements in r-phi event scene. fRPhiEventScene->DestroyElements(); } void AliEveMultiView::DestroyEventRhoZ() { // Destroy all elements in rho-z event scene. fRhoZEventScene->DestroyElements(); } void AliEveMultiView::DestroyEventMuon() { // Destroy all elements in rho-z event scene. if(fIsMuonView) fMuonEventScene->DestroyElements(); } //------------------------------------------------------------------------- void AliEveMultiView::SetCenterRPhi(Double_t x, Double_t y, Double_t z) { // Set center of r-phi manager. fRPhiMgr->SetCenter(x, y, z); } void AliEveMultiView::SetCenterRhoZ(Double_t x, Double_t y, Double_t z) { // Set center of rho-z manager. fRhoZMgr->SetCenter(x, y, z); } void AliEveMultiView::SetCenterMuon(Double_t x, Double_t y, Double_t z) { // Set center of rho-z manager. if(fIsMuonView) fMuonMgr->SetCenter(x, y, z); } void AliEveMultiView::DestroyAllGeometries() { // Destroy 3d, r-phi and rho-z geometries. fGeomGentle->DestroyElements(); fGeomGentleRPhi->DestroyElements(); fGeomGentleRhoZ->DestroyElements(); if(fIsMuonView) fGeomGentleMuon->DestroyElements(); } <|endoftext|>
<commit_before>#include "SpriteSheet.h" #include "Utilities/ResourceManager.h" #include "TinyXML/tinyxml.h" #include "Logging.h" namespace Graphics { void SpriteSheet::MakeResident () { glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); if (surface->format->BytesPerPixel == 3) { glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels); } else { glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); } } SpriteSheet::SpriteSheet ( const std::string& name ) : texID(0) { std::string configPath, imagePath; if (name[0] == '+') { configPath = ""; imagePath = "Images/" + name.substr(1, std::string::npos) + ".png"; } else { configPath = "Sprites/" + name + ".xml"; imagePath = "Sprites/" + name + ".png"; } SDL_RWops* configRWOps = ResourceManager::OpenFile(configPath); SDL_RWops* imageRWOps = ResourceManager::OpenFile(imagePath); if (!imageRWOps) { // TODO: make this work gracefully LOG("Graphics::SpriteSheet", LOG_ERROR, "Failed to load image: %s", name.c_str()); exit(1); } surface = IMG_LoadTyped_RW(imageRWOps, 1, const_cast<char*>("PNG")); if (configRWOps) { // load config size_t confLength; char* confData = (char*)ResourceManager::ReadFull(&confLength, configRWOps, 1); TiXmlDocument* xmlDoc = new TiXmlDocument(name + ".xml"); confData = (char*)realloc(confData, confLength + 1); confData[confLength] = '\0'; xmlDoc->Parse(confData); free(confData); if (xmlDoc->Error()) { LOG("Graphics::SpriteSheet", LOG_ERROR, "XML error: %s", xmlDoc->ErrorDesc()); exit(1); } TiXmlElement* root = xmlDoc->RootElement(); assert(root); TiXmlElement* dimensions = root->FirstChild("dimensions")->ToElement(); assert(dimensions); int rc; rc = dimensions->QueryIntAttribute("x", &sheetTilesX); assert(rc == TIXML_SUCCESS); rc = dimensions->QueryIntAttribute("y", &sheetTilesY); assert(rc == TIXML_SUCCESS); assert(sheetTilesX > 0); assert(sheetTilesY > 0); tileSizeX = surface->w / sheetTilesX; tileSizeY = surface->h / sheetTilesY; if (root->FirstChild("rotational")) rotational = true; else rotational = false; delete xmlDoc; } else { // assume it's just one sprite sheetTilesX = 1; sheetTilesY = 1; rotational = false; tileSizeX = surface->w; tileSizeY = surface->h; } } SpriteSheet::~SpriteSheet () { if (texID) glDeleteTextures(1, &texID); SDL_FreeSurface(surface); } void SpriteSheet::Draw ( int x, int y, const vec2& size ) { vec2 halfSize = size / 2.0f; if (texID) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); else MakeResident(); float vx = halfSize.X(), vy = halfSize.Y(); GLfloat vertices[] = { -vx, -vy, vx, -vy, vx, vy, -vx, vy }; float texBLX, texBLY, texWidth = tileSizeX, texHeight = tileSizeY; texBLX = (tileSizeX * x); texBLY = (tileSizeY * y); GLfloat texCoords[] = { texBLX, texBLY + texHeight, texBLX + texWidth, texBLY + texHeight, texBLX + texWidth, texBLY, texBLX, texBLY }; glVertexPointer(2, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texCoords); glDrawArrays(GL_QUADS, 0, 4); } void SpriteSheet::DrawRotation ( const vec2& size, float angle ) { int numObjects = sheetTilesX * sheetTilesY; angle -= M_PI / 2.0; if (angle < 0.0) angle += 2.0*M_PI; // angle is now 0 = north, 2π = north, anticlockwise angle /= 2.0*M_PI; // angle is now 0=north, 1=north, anticlockwise angle = 1.0f - angle; int index = (int)((angle - 0.00001f) * numObjects) + 1; if (index == sheetTilesX * sheetTilesY) index = 0; int x = index % sheetTilesX; int y = (index - x) / sheetTilesX; Draw(x, y, size); } } <commit_msg>Slightly adjusted the formula used to determine where the image used in rotational sprites changes.<commit_after>#include "SpriteSheet.h" #include "Utilities/ResourceManager.h" #include "TinyXML/tinyxml.h" #include "Logging.h" namespace Graphics { void SpriteSheet::MakeResident () { glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); if (surface->format->BytesPerPixel == 3) { glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels); } else { glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); } } SpriteSheet::SpriteSheet ( const std::string& name ) : texID(0) { std::string configPath, imagePath; if (name[0] == '+') { configPath = ""; imagePath = "Images/" + name.substr(1, std::string::npos) + ".png"; } else { configPath = "Sprites/" + name + ".xml"; imagePath = "Sprites/" + name + ".png"; } SDL_RWops* configRWOps = ResourceManager::OpenFile(configPath); SDL_RWops* imageRWOps = ResourceManager::OpenFile(imagePath); if (!imageRWOps) { // TODO: make this work gracefully LOG("Graphics::SpriteSheet", LOG_ERROR, "Failed to load image: %s", name.c_str()); exit(1); } surface = IMG_LoadTyped_RW(imageRWOps, 1, const_cast<char*>("PNG")); if (configRWOps) { // load config size_t confLength; char* confData = (char*)ResourceManager::ReadFull(&confLength, configRWOps, 1); TiXmlDocument* xmlDoc = new TiXmlDocument(name + ".xml"); confData = (char*)realloc(confData, confLength + 1); confData[confLength] = '\0'; xmlDoc->Parse(confData); free(confData); if (xmlDoc->Error()) { LOG("Graphics::SpriteSheet", LOG_ERROR, "XML error: %s", xmlDoc->ErrorDesc()); exit(1); } TiXmlElement* root = xmlDoc->RootElement(); assert(root); TiXmlElement* dimensions = root->FirstChild("dimensions")->ToElement(); assert(dimensions); int rc; rc = dimensions->QueryIntAttribute("x", &sheetTilesX); assert(rc == TIXML_SUCCESS); rc = dimensions->QueryIntAttribute("y", &sheetTilesY); assert(rc == TIXML_SUCCESS); assert(sheetTilesX > 0); assert(sheetTilesY > 0); tileSizeX = surface->w / sheetTilesX; tileSizeY = surface->h / sheetTilesY; if (root->FirstChild("rotational")) rotational = true; else rotational = false; delete xmlDoc; } else { // assume it's just one sprite sheetTilesX = 1; sheetTilesY = 1; rotational = false; tileSizeX = surface->w; tileSizeY = surface->h; } } SpriteSheet::~SpriteSheet () { if (texID) glDeleteTextures(1, &texID); SDL_FreeSurface(surface); } void SpriteSheet::Draw ( int x, int y, const vec2& size ) { vec2 halfSize = size / 2.0f; if (texID) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, texID); else MakeResident(); float vx = halfSize.X(), vy = halfSize.Y(); GLfloat vertices[] = { -vx, -vy, vx, -vy, vx, vy, -vx, vy }; float texBLX, texBLY, texWidth = tileSizeX, texHeight = tileSizeY; texBLX = (tileSizeX * x); texBLY = (tileSizeY * y); GLfloat texCoords[] = { texBLX, texBLY + texHeight, texBLX + texWidth, texBLY + texHeight, texBLX + texWidth, texBLY, texBLX, texBLY }; glVertexPointer(2, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texCoords); glDrawArrays(GL_QUADS, 0, 4); } void SpriteSheet::DrawRotation ( const vec2& size, float angle ) { int numObjects = sheetTilesX * sheetTilesY; angle += (M_PI / float(numObjects)); angle -= M_PI / 2.0; if (angle < 0.0) angle += 2.0*M_PI; // angle is now 0 = north, 2π = north, anticlockwise angle /= 2.0*M_PI; // angle is now 0=north, 1=north, anticlockwise angle = 1.0f - angle; int index = (int)((angle - 0.00001f) * numObjects) + 1; if (index == sheetTilesX * sheetTilesY) index = 0; int x = index % sheetTilesX; int y = (index - x) / sheetTilesX; Draw(x, y, size); } } <|endoftext|>
<commit_before>#include "combobox.h" #include <Tempest/Application> #include <Tempest/ListView> #include <Tempest/Painter> #include <Tempest/Panel> using namespace Tempest; struct ComboBox::Overlay:UiOverlay { Overlay(ComboBox* owner):owner(owner) {} ~Overlay() { owner->overlay = nullptr; } void mouseDownEvent(MouseEvent&) override { delete this; } ComboBox* owner; }; struct ComboBox::DropPanel:Tempest::Panel { void paintEvent(Tempest::PaintEvent& e) { Tempest::Painter p(e); style().draw(p,this,Style::E_MenuBackground,state(),Rect(0,0,w(),h()),Style::Extra(*this)); } }; struct ComboBox::ProxyDelegate : ListDelegate { ProxyDelegate(ListDelegate& owner):owner(owner){} size_t size() const override { return owner.size(); } Widget* createView(size_t position, Role role) override { return owner.createView(position,role); } Widget* createView(size_t position ) override { return owner.createView(position,R_ListBoxItem); } void removeView(Widget* w, size_t position) override { return owner.removeView(w,position); } Widget* update (Widget* w, size_t position) override { return owner.update(w,position); } ListDelegate& owner; }; template<class T> struct ComboBox::DefaultDelegate : ArrayListDelegate<T,Button> { DefaultDelegate(std::vector<std::string>&& items):ArrayListDelegate<T,Button>(this->items), items(items){} size_t size() const override { return items.size(); } Widget* createView(size_t i, ListDelegate::Role role) override { auto* w = ArrayListDelegate<T,Button>::createView(i,role); if(auto b = dynamic_cast<Button*>(w)) b->setButtonType(Button::T_FlatButton); return w; } Widget* createView(size_t i) override { auto* w = ArrayListDelegate<T,Button>::createView(i); if(auto b = dynamic_cast<Button*>(w)) b->setButtonType(Button::T_FlatButton); return w; } Widget* update (Widget* w, size_t i) override { if(auto b = dynamic_cast<Button*>(w)) { b->setText(items[i]); return b; } return ArrayListDelegate<T,Button>::update(w,i); } std::vector<std::string> items; }; ComboBox::ComboBox() { setMargins(0); auto& m = style().metrics(); setSizeHint(Size(m.buttonSize,m.buttonSize)); setSizePolicy(Preferred,Fixed); setLayout(Horizontal); } ComboBox::~ComboBox() { closeMenu(); } void ComboBox::setItems(const std::vector<std::string>& items) { auto i = items; setDelegate(new DefaultDelegate<std::string>(std::move(i))); } void ComboBox::proxyOnItemSelected(size_t id, Widget*) { if(overlay==nullptr) { openMenu(); } else { closeMenu(); applyItemSelection(id); } } void ComboBox::implSetDelegate(ListDelegate* d) { removeDelegate(); delegate.reset(d); delegate->onItemViewSelected.bind(this,&ComboBox::proxyOnItemSelected); delegate->invalidateView .bind(this,&ComboBox::invalidateView ); delegate->updateView .bind(this,&ComboBox::updateView ); updateView(); } void ComboBox::removeDelegate() { if(!delegate) return; this->removeAllWidgets(); delegate->onItemViewSelected.ubind(this,&ComboBox::proxyOnItemSelected); delegate->invalidateView .ubind(this,&ComboBox::invalidateView ); delegate->updateView .ubind(this,&ComboBox::updateView ); } void ComboBox::setCurrentIndex(size_t id) { if(selectedId==id) return; selectedId = id; onSelectionChanged(id); updateView(); } size_t ComboBox::currentIndex() const { return selectedId; } void ComboBox::invalidateView() { if(widgetsCount()>0) { auto w = this->takeWidget(&widget(0)); delegate->removeView(w,selectedId); } { auto w = delegate->createView(selectedId,ListDelegate::R_ListBoxView); setSizeHint(w->sizeHint()); addWidget(w); } if(proxyDelegate!=nullptr) proxyDelegate->invalidateView(); } void ComboBox::updateView() { if(widgetsCount()>0) { auto w = this->takeWidget(&widget(0)); w = delegate->update(w,selectedId); setSizeHint(w->sizeHint()); addWidget(w); } else { auto w = delegate->createView(selectedId,ListDelegate::R_ListBoxView); setSizeHint(w->sizeHint()); addWidget(w); } if(proxyDelegate!=nullptr) proxyDelegate->updateView(); } void ComboBox::paintEvent(PaintEvent& e) { Tempest::Painter p(e); style().draw(p,this, Style::E_Background,state(),Rect(0,0,w(),h()),Style::Extra(*this)); } void ComboBox::mouseWheelEvent(MouseEvent& e) { auto size = delegate->size(); if(size==0 || e.delta==0) return; size_t ci = currentIndex(); int d = (e.delta<0 ? 1 : -1); if(d<0 && ci==0) return; if(ci+d>=size) return; applyItemSelection(ci+d); } void ComboBox::openMenu() { overlay = new Overlay(this); auto list = createDropList(); overlay->addWidget(list); list->setPosition(this->mapToRoot(Point(0,0))); list->resize(std::max(w(),list->w()),list->h()); SystemApi::addOverlay(overlay); while(overlay!=nullptr && Application::isRunning()) { Application::processEvents(); } } void ComboBox::closeMenu() { delete overlay; overlay = nullptr; proxyDelegate = nullptr; } void ComboBox::applyItemSelection(size_t id) { if(id==selectedId) return; setCurrentIndex(id); onItemSelected(id); onSelectionChanged(id); } Widget* ComboBox::createDropList() { Panel* p = new DropPanel(); p->setLayout(Horizontal); p->setMargins(0); ListView* list = new ListView(); proxyDelegate = new ProxyDelegate(*delegate); list->setDelegate(proxyDelegate); list->onItemSelected.bind(this,&ComboBox::applyItemSelection); auto szh = list->centralWidget().sizeHint(); p->resize(szh); p->addWidget(list); return p; } <commit_msg>fixup<commit_after>#include "combobox.h" #include <Tempest/Application> #include <Tempest/ListView> #include <Tempest/Painter> #include <Tempest/Panel> using namespace Tempest; struct ComboBox::Overlay:UiOverlay { Overlay(ComboBox* owner):owner(owner) {} ~Overlay() { owner->overlay = nullptr; } void mouseDownEvent(MouseEvent&) override { owner->closeMenu(); } ComboBox* owner; }; struct ComboBox::DropPanel:Tempest::Panel { void paintEvent(Tempest::PaintEvent& e) { Tempest::Painter p(e); style().draw(p,this,Style::E_MenuBackground,state(),Rect(0,0,w(),h()),Style::Extra(*this)); } }; struct ComboBox::ProxyDelegate : ListDelegate { ProxyDelegate(ListDelegate& owner):owner(owner){} size_t size() const override { return owner.size(); } Widget* createView(size_t position, Role role) override { return owner.createView(position,role); } Widget* createView(size_t position ) override { return owner.createView(position,R_ListBoxItem); } void removeView(Widget* w, size_t position) override { return owner.removeView(w,position); } Widget* update (Widget* w, size_t position) override { return owner.update(w,position); } ListDelegate& owner; }; template<class T> struct ComboBox::DefaultDelegate : ArrayListDelegate<T,Button> { DefaultDelegate(std::vector<std::string>&& items):ArrayListDelegate<T,Button>(this->items), items(items){} size_t size() const override { return items.size(); } Widget* createView(size_t i, ListDelegate::Role role) override { auto* w = ArrayListDelegate<T,Button>::createView(i,role); if(auto b = dynamic_cast<Button*>(w)) b->setButtonType(Button::T_FlatButton); return w; } Widget* createView(size_t i) override { auto* w = ArrayListDelegate<T,Button>::createView(i); if(auto b = dynamic_cast<Button*>(w)) b->setButtonType(Button::T_FlatButton); return w; } Widget* update (Widget* w, size_t i) override { if(auto b = dynamic_cast<Button*>(w)) { b->setText(items[i]); return b; } return ArrayListDelegate<T,Button>::update(w,i); } std::vector<std::string> items; }; ComboBox::ComboBox() { setMargins(0); auto& m = style().metrics(); setSizeHint(Size(m.buttonSize,m.buttonSize)); setSizePolicy(Preferred,Fixed); setLayout(Horizontal); } ComboBox::~ComboBox() { closeMenu(); } void ComboBox::setItems(const std::vector<std::string>& items) { auto i = items; setDelegate(new DefaultDelegate<std::string>(std::move(i))); } void ComboBox::proxyOnItemSelected(size_t id, Widget*) { if(overlay==nullptr) { openMenu(); } else { closeMenu(); applyItemSelection(id); } } void ComboBox::implSetDelegate(ListDelegate* d) { removeDelegate(); delegate.reset(d); delegate->onItemViewSelected.bind(this,&ComboBox::proxyOnItemSelected); delegate->invalidateView .bind(this,&ComboBox::invalidateView ); delegate->updateView .bind(this,&ComboBox::updateView ); updateView(); } void ComboBox::removeDelegate() { if(!delegate) return; this->removeAllWidgets(); delegate->onItemViewSelected.ubind(this,&ComboBox::proxyOnItemSelected); delegate->invalidateView .ubind(this,&ComboBox::invalidateView ); delegate->updateView .ubind(this,&ComboBox::updateView ); } void ComboBox::setCurrentIndex(size_t id) { if(selectedId==id) return; selectedId = id; onSelectionChanged(id); updateView(); } size_t ComboBox::currentIndex() const { return selectedId; } void ComboBox::invalidateView() { if(widgetsCount()>0) { auto w = this->takeWidget(&widget(0)); delegate->removeView(w,selectedId); } { auto w = delegate->createView(selectedId,ListDelegate::R_ListBoxView); setSizeHint(w->sizeHint()); addWidget(w); } if(proxyDelegate!=nullptr) proxyDelegate->invalidateView(); } void ComboBox::updateView() { if(widgetsCount()>0) { auto w = this->takeWidget(&widget(0)); w = delegate->update(w,selectedId); setSizeHint(w->sizeHint()); addWidget(w); } else { auto w = delegate->createView(selectedId,ListDelegate::R_ListBoxView); setSizeHint(w->sizeHint()); addWidget(w); } if(proxyDelegate!=nullptr) proxyDelegate->updateView(); } void ComboBox::paintEvent(PaintEvent& e) { Tempest::Painter p(e); style().draw(p,this, Style::E_Background,state(),Rect(0,0,w(),h()),Style::Extra(*this)); } void ComboBox::mouseWheelEvent(MouseEvent& e) { auto size = delegate->size(); if(size==0 || e.delta==0) return; size_t ci = currentIndex(); int d = (e.delta<0 ? 1 : -1); if(d<0 && ci==0) return; if(ci+d>=size) return; applyItemSelection(ci+d); } void ComboBox::openMenu() { overlay = new Overlay(this); auto list = createDropList(); overlay->addWidget(list); list->setPosition(this->mapToRoot(Point(0,0))); list->resize(std::max(w(),list->w()),list->h()); SystemApi::addOverlay(overlay); while(overlay!=nullptr && Application::isRunning()) { Application::processEvents(); } } void ComboBox::closeMenu() { delete overlay; overlay = nullptr; proxyDelegate = nullptr; } void ComboBox::applyItemSelection(size_t id) { if(id==selectedId) return; setCurrentIndex(id); onItemSelected(id); onSelectionChanged(id); } Widget* ComboBox::createDropList() { Panel* p = new DropPanel(); p->setLayout(Horizontal); p->setMargins(0); ListView* list = new ListView(); proxyDelegate = new ProxyDelegate(*delegate); list->setDelegate(proxyDelegate); list->onItemSelected.bind(this,&ComboBox::applyItemSelection); auto szh = list->centralWidget().sizeHint(); p->resize(szh); p->addWidget(list); return p; } <|endoftext|>
<commit_before>#ifndef _TREE_HPP_ #define _TREE_HPP_ #include "NodeN.hpp" #include "../EstructurasLineales/Lista.hpp" template<class T> class Tree { protected: Node<T>* _root; public: Tree() : root(NULL) { }; Tree(T e) : root(new NodeN<T>(e)) { }; Tree(T, Lista<Tree<T>>); ~Tree(); bool isNull() const { return _root == NULL; } Lista<Tree<T>> getChilds() const; void destroy(); void operator=(const Tree<T> &); }; #endif<commit_msg>Constructors, Destructors, insert, getChilds, and operator= added<commit_after>#ifndef _TREE_HPP_ #define _TREE_HPP_ #include <iostream> #include "NodeN.hpp" #include "../EstructurasLineales/Lista.hpp" template<class T> class Tree { protected: NodeN<T>* _root; public: Tree() : _root(NULL) { }; Tree(NodeN<T> *p) : _root(p) { }; Tree(const Tree<T>& t) : _root(copyTree(t._root)) { }; Tree(T e) : _root(new NodeN<T>(e)) { }; Tree(T, Lista<Tree<T>>); ~Tree() { _root = destroy(_root); }; bool isNull() const { return _root == NULL; } void insert(Tree<T>); Lista<Tree<T>> getChilds() const; void destroy() { _root = destroy(_root); } void operator=(const Tree<T> &); private: NodeN<T>* copyTree(NodeN<T>*) const; NodeN<T>* destroy(NodeN<T>* p); }; template<class T> Tree<T>::Tree(T e, Lista<Tree<T>> L) { _root = new NodeN<T>(e); if (!L.esVacia()) { _root->setLeft(copyTree(L.popPrimero()._root)); for (NodeN<T>* silbings = _root->getLeft(); !L.esVacia(); silbings = silbings->getRight()) silbings->setRight(copyTree(L.popPrimero()._root)); } } template<class T> void Tree<T>::insert(Tree<T> t) { if (!t.isNull()) { NodeN<T> *sil = _root->getLeft(); while(sil->getRight() != NULL) sil = sil->getRight(); sil->setRight(copyTree(t._root)); } } template<class T> Lista<Tree<T>> Tree<T>::getChilds() const { Lista<Tree<T>> L; for (NodeN<T> *s = _root->getLeft(); s != NULL; s = s->getRight()) { Tree<T> t(new NodeN<T>(s->getKey(), copyTree(s->getLeft()))); L.pushUltimo(t); } return L; } template<class T> void Tree<T>::operator=(const Tree<T> &tree) { if (this != &tree) { this->_root = destroy(this->_root); this->_root = copyTree(tree._root); } } // ===================================================================== template<class T> NodeN<T>* Tree<T>::copyTree(NodeN<T>* p) const { if (p != NULL) return new NodeN<T>(p->getKey(), copyTree(p->getLeft()), copyTree(p->getRight())); return NULL; } template<class T> NodeN<T>* Tree<T>::destroy(NodeN<T>* p) { if (p != NULL) { p->setLeft(destroy(p->getLeft())); p->setRight(destroy(p->getRight())); delete p; } return NULL; } #endif <|endoftext|>
<commit_before>#include "MultiPassBallDetector.h" #include "Tools/CameraGeometry.h" #include "Tools/PatchWork.h" #include "Tools/BlackSpotExtractor.h" #include "Classifier/Model1.h" #include "Classifier/Fy1500_Conf.h" #include "Classifier/FrugallyDeep.h" using namespace std; MultiPassBallDetector::MultiPassBallDetector() { DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:keyPoints", "draw key points extracted from integral image", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawCandidates", "draw ball candidates", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawCandidatesResizes", "draw ball candidates (resized)", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawPercepts", "draw ball percepts", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawPatchContrast", "draw patch contrast (only when contrast-check is in use!", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:draw_projected_ball","", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawPatchInImage", "draw the gray-scale patch like it is passed to the CNN in the image", false); theBallKeyPointExtractor = registerModule<BallKeyPointExtractor>("BallKeyPointExtractor", true); getDebugParameterList().add(&params); cnnMap = createCNNMap(); // initialize classifier selection setClassifier(params.classifier, params.classifierClose); } MultiPassBallDetector::~MultiPassBallDetector() { getDebugParameterList().remove(&params); } void MultiPassBallDetector::execute(CameraInfo::CameraID id) { cameraID = id; getBallCandidates().reset(); // 1. pass: projection of the previous ball BestPatchList lastBallPatches = getPatchesByLastBall(); executeCNNOnPatches(lastBallPatches, static_cast<int>(lastBallPatches.size())); // 2. pass: keypoints std::vector<double> scoresForKeyPoints; BestPatchList keypointPatches; if(!getMultiBallPercept().wasSeen()) { // update parameter theBallKeyPointExtractor->getModuleT()->setParameter(params.keyDetector); theBallKeyPointExtractor->getModuleT()->setCameraId(cameraID); theBallKeyPointExtractor->getModuleT()->calculateKeyPointsBetter(keypointPatches); scoresForKeyPoints = executeCNNOnPatches(keypointPatches, params.maxNumberOfKeys); // TODO: how to extract/provide all patches and not only the ones from the keypoint detection? if(params.providePatches) { providePatches(keypointPatches); } else if(params.numberOfExportBestPatches > 0) { extractPatches(keypointPatches); } } // 3. pass: patches around the most promising patch of the second pass if(!getMultiBallPercept().wasSeen() && !scoresForKeyPoints.empty()) { // Convert the keypoints to a vector std::vector<BestPatchList::Patch> keypoints; keypoints.reserve(keypointPatches.size()); for(BestPatchList::reverse_iterator i = keypointPatches.rbegin(); i != keypointPatches.rend(); ++i) { keypoints.push_back(*i); } // Find the maximum score double maxScore = 0.0; size_t idxMaxScore = 0; for(size_t i = 0; i < scoresForKeyPoints.size(); i++) { if(scoresForKeyPoints[i] > maxScore) { idxMaxScore = i; maxScore = scoresForKeyPoints[i]; } } // Add keypoints around the original patch BestPatchList aroundPromisingKeyPoint; int radius = keypoints[idxMaxScore].max.x - keypoints[idxMaxScore].min.x; int halfRadius = radius / 2; for(int x=keypoints[idxMaxScore].min.x; x <= keypoints[idxMaxScore].max.x; x += halfRadius) { for(int y=keypoints[idxMaxScore].min.y; y <= keypoints[idxMaxScore].max.y; y += halfRadius) { BestPatchList::Patch p(x-halfRadius, y-halfRadius, x+halfRadius, y+halfRadius, 0.0); DEBUG_REQUEST("Vision:CNNBallDetector:drawCandidates", // center of respawned patch CIRCLE_PX(ColorClasses::pink,x, y, 2); ); aroundPromisingKeyPoint.add(p); } } executeCNNOnPatches(aroundPromisingKeyPoint, static_cast<int>(aroundPromisingKeyPoint.size())); } DEBUG_REQUEST("Vision:MultiPassBallDetector:drawPercepts", for(MultiBallPercept::ConstABPIterator iter = getMultiBallPercept().begin(); iter != getMultiBallPercept().end(); iter++) { if((*iter).cameraId == cameraID) { CIRCLE_PX(ColorClasses::orange, (int)((*iter).centerInImage.x+0.5), (int)((*iter).centerInImage.y+0.5), (int)((*iter).radiusInImage+0.5)); } } ); } std::vector<double> MultiPassBallDetector::executeCNNOnPatches(const BestPatchList& best, int maxNumberOfKeys) { // the used patch size const int patch_size = 16; std::vector<double> scores; scores.reserve(best.size()); // NOTE: patches are sorted in the ascending order, so start from the end to get the best patches int index = 0; for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) { if(getFieldPercept().getValidField().isInside((*i).min) && getFieldPercept().getValidField().isInside((*i).max)) { // limit the max amount of evaluated keys if(index > maxNumberOfKeys) { break; } static BallCandidates::PatchYUVClassified patch((*i).min, (*i).max, patch_size); patch.min = (*i).min; patch.max = (*i).max; if(!getImage().isInside(patch.min) || !getImage().isInside(patch.max)) { continue; } // // add an additional border as post-processing int postBorder = (int)(patch.radius()*params.postBorderFactorFar); double selectedCNNThreshold = params.cnn.threshold; if(patch.width() >= params.postMaxCloseSize) // HACK: use patch size as estimate if close or far away { postBorder = (int)(patch.radius()*params.postBorderFactorClose); selectedCNNThreshold = params.cnn.thresholdClose; } // resize the patch if possible if(getImage().isInside(patch.min - postBorder) && getImage().isInside(patch.max + postBorder)) { patch.min -= postBorder; patch.max += postBorder; } // extract the pixels PatchWork::subsampling(getImage(), getFieldColorPercept(), patch); // (5) check contrast if(params.checkContrast) { //double stddev = PatchWork::calculateContrastIterative2nd(getImage(),getFieldColorPercept(),min.x,min.y,max.x,max.y,patch_size); double stddev = PatchWork::calculateContrastIterative2nd(patch); DEBUG_REQUEST("Vision:MultiPassBallDetector:drawPatchContrast", CANVAS(((cameraID == CameraInfo::Top)?"ImageTop":"ImageBottom")); PEN("FF0000", 1); // red Vector2i c = patch.center(); CIRCLE( c.x, c.y, stddev / 5.0); ); // skip this patch, if contrast doesn't fullfill minimum double selectedContrastMinimum = params.contrastMinimum; if(patch.width() >= params.postMaxCloseSize) { selectedContrastMinimum = params.contrastMinimumClose; } if(stddev <= selectedContrastMinimum) { continue; } } PatchWork::multiplyBrightness((cameraID == CameraInfo::Top) ? params.brightnessMultiplierTop : params.brightnessMultiplierBottom, patch); DEBUG_REQUEST("Vision:MultiPassBallDetector:drawPatchInImage", unsigned int offsetX = patch.min.x; unsigned int offsetY = patch.min.y; unsigned int pixelWidth = (unsigned int) ((double) (patch.max.x - patch.min.x) / (double) patch.size() + 0.5); for(unsigned int x = 0; x < patch.size(); x++) { for(unsigned int y = 0; y < patch.size(); y++) { unsigned char pixelY = patch.data[x*patch_size + y].pixel.y; // draw each image pixel this patch pixel occupies for(unsigned int px=0; px < pixelWidth; px++) { for(unsigned int py=0; py < pixelWidth; py++) { getDebugImageDrawings().drawPointToImage(pixelY, 128, 128, static_cast<int>(offsetX + (x*pixelWidth) + px), offsetY + (y*pixelWidth) + py); } } } } ); // run CNN stopwatch.start(); std::shared_ptr<AbstractCNNFinder> cnn = currentCNN; if(patch.width() >= params.postMaxCloseSize) { cnn = currentCNNClose; } STOPWATCH_START("MultiPassBallDetector:predict"); cnn->predict(patch, params.cnn.meanBrightnessOffset); STOPWATCH_STOP("MultiPassBallDetector:predict"); bool found = false; double radius = cnn->getRadius(); Vector2d pos = cnn->getCenter(); if(cnn->getBallConfidence() >= selectedCNNThreshold && pos.x >= 0.0 && pos.y >= 0.0) { found = true; } stopwatch.stop(); stopwatch_values.push_back(static_cast<double>(stopwatch.lastValue) * 0.001); scores.push_back(cnn->getBallConfidence()); if (found) { // adjust the center and radius of the patch Vector2d ballCenterInPatch(pos.x * patch.width(), pos.y*patch.width()); addBallPercept(ballCenterInPatch + patch.min, radius*patch.width()); } DEBUG_REQUEST("Vision:MultiPassBallDetector:drawCandidates", // original patch RECT_PX(ColorClasses::skyblue, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y); // possibly revised patch RECT_PX(ColorClasses::orange, patch.min.x, patch.min.y, patch.max.x, patch.max.y); ); index++; } // end if in field } // end for return scores; } BestPatchList MultiPassBallDetector::getPatchesByLastBall() { BestPatchList best; if (getBallModel().valid) { Vector3d ballInField; ballInField.x = getBallModel().position.x; ballInField.y = getBallModel().position.y; ballInField.z = getFieldInfo().ballRadius; Vector2i ballInImage; if (CameraGeometry::relativePointToImage(getCameraMatrix(), getImage().cameraInfo, ballInField, ballInImage)) { double estimatedRadius = CameraGeometry::estimatedBallRadius( getCameraMatrix(), getImage().cameraInfo, getFieldInfo().ballRadius, ballInImage.x, ballInImage.y); int border = static_cast<int>((estimatedRadius * 1.1) + 0.5); Vector2i start = ballInImage - border; Vector2i end = ballInImage + border; if (start.y >= 0 && end.y < static_cast<int>(getImage().height()) && start.x >= 0 && end.x < static_cast<int>(getImage().width())) { DEBUG_REQUEST("Vision:MultiPassBallDetector:drawProjectedBall", RECT_PX(ColorClasses::pink, start.x, start.y, end.x, end.y); CIRCLE_PX(ColorClasses::pink, ballInImage.x, ballInImage.y, static_cast<int>(estimatedRadius)); ); best.add( start.x, start.y, end.x, end.y, -1.0); } } } return best; } std::map<string, std::shared_ptr<AbstractCNNFinder> > MultiPassBallDetector::createCNNMap() { std::map<string, std::shared_ptr<AbstractCNNFinder> > result; // register classifiers result.insert({ "fy1500_conf", std::make_shared<Fy1500_Conf>() }); result.insert({ "model1", std::make_shared<Model1>() }); #ifndef WIN32 result.insert({ "fdeep_fy1300", std::make_shared<FrugallyDeep>("fy1300.json")}); result.insert({ "fdeep_fy1500", std::make_shared<FrugallyDeep>("fy1500.json")}); #endif return result; } void MultiPassBallDetector::setClassifier(const std::string& name, const std::string& nameClose) { auto location = cnnMap.find(name); if(location != cnnMap.end()){ currentCNN = location->second; } location = cnnMap.find(nameClose); if(location != cnnMap.end()){ currentCNNClose = location->second; } } /** * Extract at most numberOfExportBestPatches for the logfile (and add it to the blackboard). * * WARNING: This will include the border around the patch. The resulting patch is 24x24 pixel in size * (currently internal patches size is 16x16). * To reconstruct the original patch, remove the border again. */ void MultiPassBallDetector::extractPatches(const BestPatchList& best) { int idx = 0; for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) { if(idx >= params.numberOfExportBestPatches) { break; } int offset = ((*i).max.x - (*i).min.x)/4; Vector2i min = (*i).min - offset; Vector2i max = (*i).max + offset; if(getFieldPercept().getValidField().isInside(min) && getFieldPercept().getValidField().isInside(max)) { BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified(); q.min = min; q.max = max; q.setSize(24); PatchWork::subsampling(getImage(), getFieldColorPercept(), q); idx++; } } } /** Provides all the internally generated patches in the representation */ void MultiPassBallDetector::providePatches(const BestPatchList& best) { for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) { BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified(); q.min = (*i).min; q.max = (*i).max; q.setSize(16); } } void MultiPassBallDetector::addBallPercept(const Vector2d& center, double radius) { const double ballRadius = 50.0; MultiBallPercept::BallPercept ballPercept; if(CameraGeometry::imagePixelToFieldCoord( getCameraMatrix(), getImage().cameraInfo, center.x, center.y, ballRadius, ballPercept.positionOnField)) { ballPercept.cameraId = cameraID; ballPercept.centerInImage = center; ballPercept.radiusInImage = radius; getMultiBallPercept().add(ballPercept); getMultiBallPercept().frameInfoWhenBallWasSeen = getFrameInfo(); } }<commit_msg>Correct name when registerring debug request<commit_after>#include "MultiPassBallDetector.h" #include "Tools/CameraGeometry.h" #include "Tools/PatchWork.h" #include "Tools/BlackSpotExtractor.h" #include "Classifier/Model1.h" #include "Classifier/Fy1500_Conf.h" #include "Classifier/FrugallyDeep.h" using namespace std; MultiPassBallDetector::MultiPassBallDetector() { DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:keyPoints", "draw key points extracted from integral image", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawCandidates", "draw ball candidates", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawCandidatesResizes", "draw ball candidates (resized)", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawPercepts", "draw ball percepts", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawPatchContrast", "draw patch contrast (only when contrast-check is in use!", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawProjectedBall","", false); DEBUG_REQUEST_REGISTER("Vision:MultiPassBallDetector:drawPatchInImage", "draw the gray-scale patch like it is passed to the CNN in the image", false); theBallKeyPointExtractor = registerModule<BallKeyPointExtractor>("BallKeyPointExtractor", true); getDebugParameterList().add(&params); cnnMap = createCNNMap(); // initialize classifier selection setClassifier(params.classifier, params.classifierClose); } MultiPassBallDetector::~MultiPassBallDetector() { getDebugParameterList().remove(&params); } void MultiPassBallDetector::execute(CameraInfo::CameraID id) { cameraID = id; getBallCandidates().reset(); // 1. pass: projection of the previous ball BestPatchList lastBallPatches = getPatchesByLastBall(); executeCNNOnPatches(lastBallPatches, static_cast<int>(lastBallPatches.size())); // 2. pass: keypoints std::vector<double> scoresForKeyPoints; BestPatchList keypointPatches; if(!getMultiBallPercept().wasSeen()) { // update parameter theBallKeyPointExtractor->getModuleT()->setParameter(params.keyDetector); theBallKeyPointExtractor->getModuleT()->setCameraId(cameraID); theBallKeyPointExtractor->getModuleT()->calculateKeyPointsBetter(keypointPatches); scoresForKeyPoints = executeCNNOnPatches(keypointPatches, params.maxNumberOfKeys); // TODO: how to extract/provide all patches and not only the ones from the keypoint detection? if(params.providePatches) { providePatches(keypointPatches); } else if(params.numberOfExportBestPatches > 0) { extractPatches(keypointPatches); } } // 3. pass: patches around the most promising patch of the second pass if(!getMultiBallPercept().wasSeen() && !scoresForKeyPoints.empty()) { // Convert the keypoints to a vector std::vector<BestPatchList::Patch> keypoints; keypoints.reserve(keypointPatches.size()); for(BestPatchList::reverse_iterator i = keypointPatches.rbegin(); i != keypointPatches.rend(); ++i) { keypoints.push_back(*i); } // Find the maximum score double maxScore = 0.0; size_t idxMaxScore = 0; for(size_t i = 0; i < scoresForKeyPoints.size(); i++) { if(scoresForKeyPoints[i] > maxScore) { idxMaxScore = i; maxScore = scoresForKeyPoints[i]; } } // Add keypoints around the original patch BestPatchList aroundPromisingKeyPoint; int radius = keypoints[idxMaxScore].max.x - keypoints[idxMaxScore].min.x; int halfRadius = radius / 2; for(int x=keypoints[idxMaxScore].min.x; x <= keypoints[idxMaxScore].max.x; x += halfRadius) { for(int y=keypoints[idxMaxScore].min.y; y <= keypoints[idxMaxScore].max.y; y += halfRadius) { BestPatchList::Patch p(x-halfRadius, y-halfRadius, x+halfRadius, y+halfRadius, 0.0); DEBUG_REQUEST("Vision:CNNBallDetector:drawCandidates", // center of respawned patch CIRCLE_PX(ColorClasses::pink,x, y, 2); ); aroundPromisingKeyPoint.add(p); } } executeCNNOnPatches(aroundPromisingKeyPoint, static_cast<int>(aroundPromisingKeyPoint.size())); } DEBUG_REQUEST("Vision:MultiPassBallDetector:drawPercepts", for(MultiBallPercept::ConstABPIterator iter = getMultiBallPercept().begin(); iter != getMultiBallPercept().end(); iter++) { if((*iter).cameraId == cameraID) { CIRCLE_PX(ColorClasses::orange, (int)((*iter).centerInImage.x+0.5), (int)((*iter).centerInImage.y+0.5), (int)((*iter).radiusInImage+0.5)); } } ); } std::vector<double> MultiPassBallDetector::executeCNNOnPatches(const BestPatchList& best, int maxNumberOfKeys) { // the used patch size const int patch_size = 16; std::vector<double> scores; scores.reserve(best.size()); // NOTE: patches are sorted in the ascending order, so start from the end to get the best patches int index = 0; for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) { if(getFieldPercept().getValidField().isInside((*i).min) && getFieldPercept().getValidField().isInside((*i).max)) { // limit the max amount of evaluated keys if(index > maxNumberOfKeys) { break; } static BallCandidates::PatchYUVClassified patch((*i).min, (*i).max, patch_size); patch.min = (*i).min; patch.max = (*i).max; if(!getImage().isInside(patch.min) || !getImage().isInside(patch.max)) { continue; } // // add an additional border as post-processing int postBorder = (int)(patch.radius()*params.postBorderFactorFar); double selectedCNNThreshold = params.cnn.threshold; if(patch.width() >= params.postMaxCloseSize) // HACK: use patch size as estimate if close or far away { postBorder = (int)(patch.radius()*params.postBorderFactorClose); selectedCNNThreshold = params.cnn.thresholdClose; } // resize the patch if possible if(getImage().isInside(patch.min - postBorder) && getImage().isInside(patch.max + postBorder)) { patch.min -= postBorder; patch.max += postBorder; } // extract the pixels PatchWork::subsampling(getImage(), getFieldColorPercept(), patch); // (5) check contrast if(params.checkContrast) { //double stddev = PatchWork::calculateContrastIterative2nd(getImage(),getFieldColorPercept(),min.x,min.y,max.x,max.y,patch_size); double stddev = PatchWork::calculateContrastIterative2nd(patch); DEBUG_REQUEST("Vision:MultiPassBallDetector:drawPatchContrast", CANVAS(((cameraID == CameraInfo::Top)?"ImageTop":"ImageBottom")); PEN("FF0000", 1); // red Vector2i c = patch.center(); CIRCLE( c.x, c.y, stddev / 5.0); ); // skip this patch, if contrast doesn't fullfill minimum double selectedContrastMinimum = params.contrastMinimum; if(patch.width() >= params.postMaxCloseSize) { selectedContrastMinimum = params.contrastMinimumClose; } if(stddev <= selectedContrastMinimum) { continue; } } PatchWork::multiplyBrightness((cameraID == CameraInfo::Top) ? params.brightnessMultiplierTop : params.brightnessMultiplierBottom, patch); DEBUG_REQUEST("Vision:MultiPassBallDetector:drawPatchInImage", unsigned int offsetX = patch.min.x; unsigned int offsetY = patch.min.y; unsigned int pixelWidth = (unsigned int) ((double) (patch.max.x - patch.min.x) / (double) patch.size() + 0.5); for(unsigned int x = 0; x < patch.size(); x++) { for(unsigned int y = 0; y < patch.size(); y++) { unsigned char pixelY = patch.data[x*patch_size + y].pixel.y; // draw each image pixel this patch pixel occupies for(unsigned int px=0; px < pixelWidth; px++) { for(unsigned int py=0; py < pixelWidth; py++) { getDebugImageDrawings().drawPointToImage(pixelY, 128, 128, static_cast<int>(offsetX + (x*pixelWidth) + px), offsetY + (y*pixelWidth) + py); } } } } ); // run CNN stopwatch.start(); std::shared_ptr<AbstractCNNFinder> cnn = currentCNN; if(patch.width() >= params.postMaxCloseSize) { cnn = currentCNNClose; } STOPWATCH_START("MultiPassBallDetector:predict"); cnn->predict(patch, params.cnn.meanBrightnessOffset); STOPWATCH_STOP("MultiPassBallDetector:predict"); bool found = false; double radius = cnn->getRadius(); Vector2d pos = cnn->getCenter(); if(cnn->getBallConfidence() >= selectedCNNThreshold && pos.x >= 0.0 && pos.y >= 0.0) { found = true; } stopwatch.stop(); stopwatch_values.push_back(static_cast<double>(stopwatch.lastValue) * 0.001); scores.push_back(cnn->getBallConfidence()); if (found) { // adjust the center and radius of the patch Vector2d ballCenterInPatch(pos.x * patch.width(), pos.y*patch.width()); addBallPercept(ballCenterInPatch + patch.min, radius*patch.width()); } DEBUG_REQUEST("Vision:MultiPassBallDetector:drawCandidates", // original patch RECT_PX(ColorClasses::skyblue, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y); // possibly revised patch RECT_PX(ColorClasses::orange, patch.min.x, patch.min.y, patch.max.x, patch.max.y); ); index++; } // end if in field } // end for return scores; } BestPatchList MultiPassBallDetector::getPatchesByLastBall() { BestPatchList best; if (getBallModel().valid) { Vector3d ballInField; ballInField.x = getBallModel().position.x; ballInField.y = getBallModel().position.y; ballInField.z = getFieldInfo().ballRadius; Vector2i ballInImage; if (CameraGeometry::relativePointToImage(getCameraMatrix(), getImage().cameraInfo, ballInField, ballInImage)) { double estimatedRadius = CameraGeometry::estimatedBallRadius( getCameraMatrix(), getImage().cameraInfo, getFieldInfo().ballRadius, ballInImage.x, ballInImage.y); int border = static_cast<int>((estimatedRadius * 1.1) + 0.5); Vector2i start = ballInImage - border; Vector2i end = ballInImage + border; if (start.y >= 0 && end.y < static_cast<int>(getImage().height()) && start.x >= 0 && end.x < static_cast<int>(getImage().width())) { DEBUG_REQUEST("Vision:MultiPassBallDetector:drawProjectedBall", RECT_PX(ColorClasses::pink, start.x, start.y, end.x, end.y); CIRCLE_PX(ColorClasses::pink, ballInImage.x, ballInImage.y, static_cast<int>(estimatedRadius)); ); best.add( start.x, start.y, end.x, end.y, -1.0); } } } return best; } std::map<string, std::shared_ptr<AbstractCNNFinder> > MultiPassBallDetector::createCNNMap() { std::map<string, std::shared_ptr<AbstractCNNFinder> > result; // register classifiers result.insert({ "fy1500_conf", std::make_shared<Fy1500_Conf>() }); result.insert({ "model1", std::make_shared<Model1>() }); #ifndef WIN32 result.insert({ "fdeep_fy1300", std::make_shared<FrugallyDeep>("fy1300.json")}); result.insert({ "fdeep_fy1500", std::make_shared<FrugallyDeep>("fy1500.json")}); #endif return result; } void MultiPassBallDetector::setClassifier(const std::string& name, const std::string& nameClose) { auto location = cnnMap.find(name); if(location != cnnMap.end()){ currentCNN = location->second; } location = cnnMap.find(nameClose); if(location != cnnMap.end()){ currentCNNClose = location->second; } } /** * Extract at most numberOfExportBestPatches for the logfile (and add it to the blackboard). * * WARNING: This will include the border around the patch. The resulting patch is 24x24 pixel in size * (currently internal patches size is 16x16). * To reconstruct the original patch, remove the border again. */ void MultiPassBallDetector::extractPatches(const BestPatchList& best) { int idx = 0; for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) { if(idx >= params.numberOfExportBestPatches) { break; } int offset = ((*i).max.x - (*i).min.x)/4; Vector2i min = (*i).min - offset; Vector2i max = (*i).max + offset; if(getFieldPercept().getValidField().isInside(min) && getFieldPercept().getValidField().isInside(max)) { BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified(); q.min = min; q.max = max; q.setSize(24); PatchWork::subsampling(getImage(), getFieldColorPercept(), q); idx++; } } } /** Provides all the internally generated patches in the representation */ void MultiPassBallDetector::providePatches(const BestPatchList& best) { for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) { BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified(); q.min = (*i).min; q.max = (*i).max; q.setSize(16); } } void MultiPassBallDetector::addBallPercept(const Vector2d& center, double radius) { const double ballRadius = 50.0; MultiBallPercept::BallPercept ballPercept; if(CameraGeometry::imagePixelToFieldCoord( getCameraMatrix(), getImage().cameraInfo, center.x, center.y, ballRadius, ballPercept.positionOnField)) { ballPercept.cameraId = cameraID; ballPercept.centerInImage = center; ballPercept.radiusInImage = radius; getMultiBallPercept().add(ballPercept); getMultiBallPercept().frameInfoWhenBallWasSeen = getFrameInfo(); } }<|endoftext|>
<commit_before> #ifndef __UTILS_H #define __UTILS_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <math.h> /** * @brief Flash size register address */ #define ID_FLASH_ADDRESS (0x1FFF7A22) /** * @brief Device ID register address */ #define ID_DBGMCU_IDCODE (0xE0042000) /** * "Returns" the device signature * * Possible returns: * - 0x0413: STM32F405xx/07xx and STM32F415xx/17xx) * - 0x0419: STM32F42xxx and STM32F43xxx * - 0x0423: STM32F401xB/C * - 0x0433: STM32F401xD/E * - 0x0431: STM32F411xC/E * * Returned data is in 16-bit mode, but only bits 11:0 are valid, bits 15:12 are always 0. * Defined as macro */ #define STM_ID_GetSignature() ((*(uint16_t *)(ID_DBGMCU_IDCODE)) & 0x0FFF) /** * "Returns" the device revision * * Revisions possible: * - 0x1000: Revision A * - 0x1001: Revision Z * - 0x1003: Revision Y * - 0x1007: Revision 1 * - 0x2001: Revision 3 * * Returned data is in 16-bit mode. */ #define STM_ID_GetRevision() (*(uint16_t *)(ID_DBGMCU_IDCODE + 2)) /** * "Returns" the Flash size * * Returned data is in 16-bit mode, returned value is flash size in kB (kilo bytes). */ #define STM_ID_GetFlashSize() (*(uint16_t *)(ID_FLASH_ADDRESS)) #ifdef M_PI #undef M_PI #endif #define M_PI (3.14159265358979323846f) #define MACRO_MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MACRO_MIN(x, y) (((x) < (y)) ? (x) : (y)) #define SQ(x) ((x) * (x)) static const float one_by_sqrt3 = 0.57735026919f; static const float two_by_sqrt3 = 1.15470053838f; static const float sqrt3_by_2 = 0.86602540378f; //beware of inserting large values! static inline float wrap_pm(float x, float pm_range) { while (x >= pm_range) x -= (2.0f * pm_range); while (x < -pm_range) x += (2.0f * pm_range); return x; } //beware of inserting large angles! static inline float wrap_pm_pi(float theta) { return wrap_pm(theta, M_PI); } // like fmodf, but always positive static inline float fmodf_pos(float x, float y) { float out = fmodf(x, y); if (out < 0.0f) out += y; return out; } // Compute rising edge timings (0.0 - 1.0) as a function of alpha-beta // as per the magnitude invariant clarke transform // The magnitude of the alpha-beta vector may not be larger than sqrt(3)/2 // Returns 0 on success, and -1 if the input was out of range int SVM(float alpha, float beta, float* tA, float* tB, float* tC); float fast_atan2(float y, float x); float horner_fma(float x, const float *coeffs, size_t count); int mod(int dividend, int divisor); uint32_t deadline_to_timeout(uint32_t deadline_ms); uint32_t timeout_to_deadline(uint32_t timeout_ms); int is_in_the_future(uint32_t time_ms); uint32_t micros(void); void delay_us(uint32_t us); float our_arm_sin_f32(float x); float our_arm_cos_f32(float x); #ifdef __cplusplus } #endif #endif //__UTILS_H <commit_msg>Move gpio helper functions<commit_after> #ifndef __UTILS_H #define __UTILS_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <math.h> /** * @brief Flash size register address */ #define ID_FLASH_ADDRESS (0x1FFF7A22) /** * @brief Device ID register address */ #define ID_DBGMCU_IDCODE (0xE0042000) /** * "Returns" the device signature * * Possible returns: * - 0x0413: STM32F405xx/07xx and STM32F415xx/17xx) * - 0x0419: STM32F42xxx and STM32F43xxx * - 0x0423: STM32F401xB/C * - 0x0433: STM32F401xD/E * - 0x0431: STM32F411xC/E * * Returned data is in 16-bit mode, but only bits 11:0 are valid, bits 15:12 are always 0. * Defined as macro */ #define STM_ID_GetSignature() ((*(uint16_t *)(ID_DBGMCU_IDCODE)) & 0x0FFF) /** * "Returns" the device revision * * Revisions possible: * - 0x1000: Revision A * - 0x1001: Revision Z * - 0x1003: Revision Y * - 0x1007: Revision 1 * - 0x2001: Revision 3 * * Returned data is in 16-bit mode. */ #define STM_ID_GetRevision() (*(uint16_t *)(ID_DBGMCU_IDCODE + 2)) /** * "Returns" the Flash size * * Returned data is in 16-bit mode, returned value is flash size in kB (kilo bytes). */ #define STM_ID_GetFlashSize() (*(uint16_t *)(ID_FLASH_ADDRESS)) #ifdef M_PI #undef M_PI #endif #define M_PI (3.14159265358979323846f) #define MACRO_MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MACRO_MIN(x, y) (((x) < (y)) ? (x) : (y)) #define SQ(x) ((x) * (x)) static const float one_by_sqrt3 = 0.57735026919f; static const float two_by_sqrt3 = 1.15470053838f; static const float sqrt3_by_2 = 0.86602540378f; //beware of inserting large values! static inline float wrap_pm(float x, float pm_range) { while (x >= pm_range) x -= (2.0f * pm_range); while (x < -pm_range) x += (2.0f * pm_range); return x; } //beware of inserting large angles! static inline float wrap_pm_pi(float theta) { return wrap_pm(theta, M_PI); } // like fmodf, but always positive static inline float fmodf_pos(float x, float y) { float out = fmodf(x, y); if (out < 0.0f) out += y; return out; } // Compute rising edge timings (0.0 - 1.0) as a function of alpha-beta // as per the magnitude invariant clarke transform // The magnitude of the alpha-beta vector may not be larger than sqrt(3)/2 // Returns 0 on success, and -1 if the input was out of range int SVM(float alpha, float beta, float* tA, float* tB, float* tC); float fast_atan2(float y, float x); float horner_fma(float x, const float *coeffs, size_t count); int mod(int dividend, int divisor); uint32_t deadline_to_timeout(uint32_t deadline_ms); uint32_t timeout_to_deadline(uint32_t timeout_ms); int is_in_the_future(uint32_t time_ms); uint32_t micros(void); void delay_us(uint32_t us); float our_arm_sin_f32(float x); float our_arm_cos_f32(float x); #ifdef __cplusplus } #endif #include "gpio.h" constexpr GPIO_TypeDef* get_gpio_port_by_pin(uint16_t GPIO_pin){ switch(GPIO_pin){ case 1: return GPIO_1_GPIO_Port; break; case 2: return GPIO_2_GPIO_Port; break; case 3: return GPIO_3_GPIO_Port; break; case 4: return GPIO_4_GPIO_Port; break; #ifdef GPIO_5_GPIO_Port case 5: return GPIO_5_GPIO_Port; break; #endif #ifdef GPIO_6_GPIO_Port case 6: return GPIO_6_GPIO_Port; break; #endif #ifdef GPIO_7_GPIO_Port case 7: return GPIO_7_GPIO_Port; break; #endif #ifdef GPIO_8_GPIO_Port case 8: return GPIO_8_GPIO_Port; break; #endif default: return GPIO_1_GPIO_Port; } } constexpr uint16_t get_gpio_pin_by_pin(uint16_t GPIO_pin){ switch(GPIO_pin){ case 1: return GPIO_1_Pin; break; case 2: return GPIO_2_Pin; break; case 3: return GPIO_3_Pin; break; case 4: return GPIO_4_Pin; break; #ifdef GPIO_5_Pin case 5: return GPIO_5_Pin; break; #endif #ifdef GPIO_6_Pin case 6: return GPIO_6_Pin; break; #endif #ifdef GPIO_7_Pin case 7: return GPIO_7_Pin; break; #endif #ifdef GPIO_8_Pin case 8: return GPIO_8_Pin; break; #endif default: return GPIO_1_Pin; } } #endif //__UTILS_H <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Menu.h" #include "core/Engine.h" #include "events/EventDispatcher.h" #include "input/Input.h" #include "utils/Log.h" namespace ouzel { namespace gui { Menu::Menu() { eventHandler.keyboardHandler = std::bind(&Menu::handleKeyboard, this, std::placeholders::_1, std::placeholders::_2); eventHandler.gamepadHandler = std::bind(&Menu::handleGamepad, this, std::placeholders::_1, std::placeholders::_2); eventHandler.uiHandler = std::bind(&Menu::handleUI, this, std::placeholders::_1, std::placeholders::_2); } void Menu::enter() { sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler); } void Menu::leave() { eventHandler.remove(); } void Menu::setEnabled(bool newEnabled) { Widget::setEnabled(newEnabled); if (enabled) { if (!selectedWidget && !widgets.empty()) { selectWidget(widgets.front()); } } else { selectedWidget = nullptr; for (Widget* childWidget : widgets) { childWidget->setSelected(false); } } } void Menu::addChildWidget(Widget* widget) { addChild(widget); if (widget) { if (widget->menu) { widget->menu->removeChild(widget); } widget->menu = this; widgets.push_back(widget); if (!selectedWidget) { selectWidget(widget); } } } bool Menu::removeChildNode(Node* node) { auto i = std::find(widgets.begin(), widgets.end(), node); if (i != widgets.end()) { widgets.erase(i); Widget* widget = static_cast<Widget*>(node); widget->menu = nullptr; } if (selectedWidget == node) { selectWidget(nullptr); } if (!Node::removeChildNode(node)) { return false; } return true; } void Menu::selectWidget(Widget* widget) { if (!enabled) return; selectedWidget = nullptr; for (Widget* childWidget : widgets) { if (childWidget == widget) { selectedWidget = widget; childWidget->setSelected(true); } else { childWidget->setSelected(false); } } } void Menu::selectNextWidget() { if (!enabled) return; std::vector<Widget*>::iterator firstWidgetIterator = selectedWidget ? std::find(widgets.begin(), widgets.end(), selectedWidget) : widgets.end(); std::vector<Widget*>::iterator widgetIterator = firstWidgetIterator; do { if (widgetIterator == widgets.end()) { widgetIterator = widgets.begin(); } else { widgetIterator++; } if (widgetIterator != widgets.end() && (*widgetIterator)->isEnabled()) { selectWidget(*widgetIterator); break; } } while (widgetIterator != firstWidgetIterator); } void Menu::selectPreviousWidget() { if (!enabled) return; std::vector<Widget*>::iterator firstWidgetIterator = selectedWidget ? std::find(widgets.begin(), widgets.end(), selectedWidget) : widgets.end(); std::vector<Widget*>::iterator widgetIterator = firstWidgetIterator; do { if (widgetIterator == widgets.begin()) widgetIterator = widgets.end(); if (widgetIterator != widgets.begin()) widgetIterator--; if (widgetIterator != widgets.end() && (*widgetIterator)->isEnabled()) { selectWidget(*widgetIterator); break; } } while (widgetIterator != firstWidgetIterator); } bool Menu::handleKeyboard(Event::Type type, const KeyboardEvent& event) { if (!enabled) return true; if (type == Event::Type::KEY_PRESS && !widgets.empty()) { switch (event.key) { case input::KeyboardKey::LEFT: case input::KeyboardKey::UP: selectPreviousWidget(); break; case input::KeyboardKey::RIGHT: case input::KeyboardKey::DOWN: selectNextWidget(); break; case input::KeyboardKey::RETURN: case input::KeyboardKey::SPACE: { if (selectedWidget) { Event clickEvent; clickEvent.type = Event::Type::CLICK_NODE; clickEvent.uiEvent.node = selectedWidget; clickEvent.uiEvent.position = selectedWidget->getPosition(); sharedEngine->getEventDispatcher()->postEvent(clickEvent); } break; } default: break; } } return true; } bool Menu::handleGamepad(Event::Type type, const GamepadEvent& event) { if (!enabled) return true; if (type == Event::Type::GAMEPAD_BUTTON_CHANGE) { if (event.pressed) { if (event.button == input::GamepadButton::FACE1) { if (selectedWidget) { Event clickEvent; clickEvent.type = Event::Type::CLICK_NODE; clickEvent.uiEvent.node = selectedWidget; clickEvent.uiEvent.position = selectedWidget->getPosition(); sharedEngine->getEventDispatcher()->postEvent(clickEvent); } } else if (event.button == input::GamepadButton::DPAD_LEFT || event.button == input::GamepadButton::DPAD_UP) { if (!event.previousPressed && event.pressed) selectPreviousWidget(); } else if (event.button == input::GamepadButton::DPAD_RIGHT || event.button == input::GamepadButton::DPAD_DOWN) { if (!event.previousPressed && event.pressed) selectNextWidget(); } else if (event.button == input::GamepadButton::LEFT_THUMB_LEFT || event.button == input::GamepadButton::LEFT_THUMB_UP) { if (event.previousValue < 0.6f && event.value > 0.6f) selectPreviousWidget(); } else if (event.button == input::GamepadButton::LEFT_THUMB_RIGHT || event.button == input::GamepadButton::LEFT_THUMB_DOWN) { if (event.previousValue < 0.6f && event.value > 0.6f) selectNextWidget(); } } } return true; } bool Menu::handleUI(Event::Type type, const UIEvent& event) { if (!enabled) return true; if (type == Event::Type::ENTER_NODE) { if (std::find(widgets.begin(), widgets.end(), event.node) != widgets.end()) { selectWidget(static_cast<Widget*>(event.node)); } } return true; } } // namespace gui } // namespace ouzel <commit_msg>Activate menu items only if gamepad button was not previously pressed<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Menu.h" #include "core/Engine.h" #include "events/EventDispatcher.h" #include "input/Input.h" #include "utils/Log.h" namespace ouzel { namespace gui { Menu::Menu() { eventHandler.keyboardHandler = std::bind(&Menu::handleKeyboard, this, std::placeholders::_1, std::placeholders::_2); eventHandler.gamepadHandler = std::bind(&Menu::handleGamepad, this, std::placeholders::_1, std::placeholders::_2); eventHandler.uiHandler = std::bind(&Menu::handleUI, this, std::placeholders::_1, std::placeholders::_2); } void Menu::enter() { sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler); } void Menu::leave() { eventHandler.remove(); } void Menu::setEnabled(bool newEnabled) { Widget::setEnabled(newEnabled); if (enabled) { if (!selectedWidget && !widgets.empty()) { selectWidget(widgets.front()); } } else { selectedWidget = nullptr; for (Widget* childWidget : widgets) { childWidget->setSelected(false); } } } void Menu::addChildWidget(Widget* widget) { addChild(widget); if (widget) { if (widget->menu) { widget->menu->removeChild(widget); } widget->menu = this; widgets.push_back(widget); if (!selectedWidget) { selectWidget(widget); } } } bool Menu::removeChildNode(Node* node) { auto i = std::find(widgets.begin(), widgets.end(), node); if (i != widgets.end()) { widgets.erase(i); Widget* widget = static_cast<Widget*>(node); widget->menu = nullptr; } if (selectedWidget == node) { selectWidget(nullptr); } if (!Node::removeChildNode(node)) { return false; } return true; } void Menu::selectWidget(Widget* widget) { if (!enabled) return; selectedWidget = nullptr; for (Widget* childWidget : widgets) { if (childWidget == widget) { selectedWidget = widget; childWidget->setSelected(true); } else { childWidget->setSelected(false); } } } void Menu::selectNextWidget() { if (!enabled) return; std::vector<Widget*>::iterator firstWidgetIterator = selectedWidget ? std::find(widgets.begin(), widgets.end(), selectedWidget) : widgets.end(); std::vector<Widget*>::iterator widgetIterator = firstWidgetIterator; do { if (widgetIterator == widgets.end()) { widgetIterator = widgets.begin(); } else { widgetIterator++; } if (widgetIterator != widgets.end() && (*widgetIterator)->isEnabled()) { selectWidget(*widgetIterator); break; } } while (widgetIterator != firstWidgetIterator); } void Menu::selectPreviousWidget() { if (!enabled) return; std::vector<Widget*>::iterator firstWidgetIterator = selectedWidget ? std::find(widgets.begin(), widgets.end(), selectedWidget) : widgets.end(); std::vector<Widget*>::iterator widgetIterator = firstWidgetIterator; do { if (widgetIterator == widgets.begin()) widgetIterator = widgets.end(); if (widgetIterator != widgets.begin()) widgetIterator--; if (widgetIterator != widgets.end() && (*widgetIterator)->isEnabled()) { selectWidget(*widgetIterator); break; } } while (widgetIterator != firstWidgetIterator); } bool Menu::handleKeyboard(Event::Type type, const KeyboardEvent& event) { if (!enabled) return true; if (type == Event::Type::KEY_PRESS && !widgets.empty()) { switch (event.key) { case input::KeyboardKey::LEFT: case input::KeyboardKey::UP: selectPreviousWidget(); break; case input::KeyboardKey::RIGHT: case input::KeyboardKey::DOWN: selectNextWidget(); break; case input::KeyboardKey::RETURN: case input::KeyboardKey::SPACE: { if (selectedWidget) { Event clickEvent; clickEvent.type = Event::Type::CLICK_NODE; clickEvent.uiEvent.node = selectedWidget; clickEvent.uiEvent.position = selectedWidget->getPosition(); sharedEngine->getEventDispatcher()->postEvent(clickEvent); } break; } default: break; } } return true; } bool Menu::handleGamepad(Event::Type type, const GamepadEvent& event) { if (!enabled) return true; if (type == Event::Type::GAMEPAD_BUTTON_CHANGE) { if (event.pressed && !event.previousPressed) { if (event.button == input::GamepadButton::FACE1) { if (selectedWidget) { Event clickEvent; clickEvent.type = Event::Type::CLICK_NODE; clickEvent.uiEvent.node = selectedWidget; clickEvent.uiEvent.position = selectedWidget->getPosition(); sharedEngine->getEventDispatcher()->postEvent(clickEvent); } } else if (event.button == input::GamepadButton::DPAD_LEFT || event.button == input::GamepadButton::DPAD_UP) { if (!event.previousPressed && event.pressed) selectPreviousWidget(); } else if (event.button == input::GamepadButton::DPAD_RIGHT || event.button == input::GamepadButton::DPAD_DOWN) { if (!event.previousPressed && event.pressed) selectNextWidget(); } else if (event.button == input::GamepadButton::LEFT_THUMB_LEFT || event.button == input::GamepadButton::LEFT_THUMB_UP) { if (event.previousValue < 0.6f && event.value > 0.6f) selectPreviousWidget(); } else if (event.button == input::GamepadButton::LEFT_THUMB_RIGHT || event.button == input::GamepadButton::LEFT_THUMB_DOWN) { if (event.previousValue < 0.6f && event.value > 0.6f) selectNextWidget(); } } } return true; } bool Menu::handleUI(Event::Type type, const UIEvent& event) { if (!enabled) return true; if (type == Event::Type::ENTER_NODE) { if (std::find(widgets.begin(), widgets.end(), event.node) != widgets.end()) { selectWidget(static_cast<Widget*>(event.node)); } } return true; } } // namespace gui } // namespace ouzel <|endoftext|>
<commit_before>/** * @file pycantera.cpp * * This is the main file for the Python interface module. * */ // turn off warnings about long names under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "cantera/config.h" #include "Python.h" #ifdef HAS_NUMERIC #include "Numeric/arrayobject.h" #else #ifdef HAS_NUMARRAY #include "numarray/arrayobject.h" #else #ifdef HAS_NUMPY #include "numpy/libnumarray.h" #include "numpy/arrayobject.h" #else // Create a compilation error to cause the program to bomb #include "Numeric/arrayobject.h" #include "numarray/arrayobject.h" #include "numpy/libnumarray.h" #include "numpy/arrayobject.h" #endif #endif #endif #include "ct.h" #include "ctxml.h" #include "ctsurf.h" #include "ctbdry.h" #include "ctrpath.h" #include "ctreactor.h" #include "ctfunc.h" #include "ctonedim.h" #include "ctmultiphase.h" #include <iostream> using namespace std; // constants defined in the module static PyObject *ErrorObject; // local includes #include "pyutils.h" #include "ctphase_methods.cpp" #include "ctthermo_methods.cpp" #include "ctkinetics_methods.cpp" #include "cttransport_methods.cpp" #include "ctxml_methods.cpp" #include "ctfuncs.cpp" #include "ctsurf_methods.cpp" //#include "ctbndry_methods.cpp" #include "ctrpath_methods.cpp" #include "ctreactor_methods.cpp" #include "ctfunc_methods.cpp" #include "ctonedim_methods.cpp" #include "ctmultiphase_methods.cpp" #ifdef INCL_USER_PYTHON #include "ctuser.h" #include "ctuser_methods.cpp" #endif static PyObject* pyct_appdelete(PyObject *self, PyObject *args) { return Py_BuildValue("i",ct_appdelete()); } #include "methods.h" #include "pylogger.h" //#include "../../src/global.h" extern "C" { /* Initialization function for the module */ DL_EXPORT(void) init_cantera(void) { PyObject *m, *d; /* Initialize the type of the new type object here; doing it here * is required for portability to Windows without requiring C++. */ /* Create the module and add the functions */ m = Py_InitModule("_cantera", ct_methods); import_array(); Cantera::Logger* pylog = new Cantera::Py_Logger; setLogWriter(pylog); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyErr_NewException("cantera.error", NULL, NULL); PyDict_SetItemString(d, "error", ErrorObject); #ifdef HAS_NUMERIC PyDict_SetItemString(d, "nummod",PyString_FromString("Numeric")); #else #ifdef HAS_NUMARRAY PyDict_SetItemString(d, "nummod",PyString_FromString("numarray")); #else PyDict_SetItemString(d, "nummod",PyString_FromString("numpy")); #endif #endif } } <commit_msg>No longer need numarray stuff when using numpy<commit_after>/** * @file pycantera.cpp * * This is the main file for the Python interface module. * */ // turn off warnings about long names under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "cantera/config.h" #include "Python.h" #ifdef HAS_NUMERIC #include "Numeric/arrayobject.h" #else #ifdef HAS_NUMARRAY #include "numarray/arrayobject.h" #else #ifdef HAS_NUMPY //#include "numpy/libnumarray.h" #include "numpy/arrayobject.h" #else // Create a compilation error to cause the program to bomb #include "Numeric/arrayobject.h" #include "numarray/arrayobject.h" #include "numpy/libnumarray.h" #include "numpy/arrayobject.h" #endif #endif #endif #include "ct.h" #include "ctxml.h" #include "ctsurf.h" #include "ctbdry.h" #include "ctrpath.h" #include "ctreactor.h" #include "ctfunc.h" #include "ctonedim.h" #include "ctmultiphase.h" #include <iostream> using namespace std; // constants defined in the module static PyObject *ErrorObject; // local includes #include "pyutils.h" #include "ctphase_methods.cpp" #include "ctthermo_methods.cpp" #include "ctkinetics_methods.cpp" #include "cttransport_methods.cpp" #include "ctxml_methods.cpp" #include "ctfuncs.cpp" #include "ctsurf_methods.cpp" //#include "ctbndry_methods.cpp" #include "ctrpath_methods.cpp" #include "ctreactor_methods.cpp" #include "ctfunc_methods.cpp" #include "ctonedim_methods.cpp" #include "ctmultiphase_methods.cpp" #ifdef INCL_USER_PYTHON #include "ctuser.h" #include "ctuser_methods.cpp" #endif static PyObject* pyct_appdelete(PyObject *self, PyObject *args) { return Py_BuildValue("i",ct_appdelete()); } #include "methods.h" #include "pylogger.h" //#include "../../src/global.h" extern "C" { /* Initialization function for the module */ DL_EXPORT(void) init_cantera(void) { PyObject *m, *d; /* Initialize the type of the new type object here; doing it here * is required for portability to Windows without requiring C++. */ /* Create the module and add the functions */ m = Py_InitModule("_cantera", ct_methods); import_array(); Cantera::Logger* pylog = new Cantera::Py_Logger; setLogWriter(pylog); /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); ErrorObject = PyErr_NewException("cantera.error", NULL, NULL); PyDict_SetItemString(d, "error", ErrorObject); #ifdef HAS_NUMERIC PyDict_SetItemString(d, "nummod",PyString_FromString("Numeric")); #else #ifdef HAS_NUMARRAY PyDict_SetItemString(d, "nummod",PyString_FromString("numarray")); #else PyDict_SetItemString(d, "nummod",PyString_FromString("numpy")); #endif #endif } } <|endoftext|>
<commit_before>/* * Copyright 2008-2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "esnpapi.h" #include "proxyImpl.h" #include <any.h> #include <reflect.h> #include <org/w3c/dom.h> using namespace org::w3c::dom; void initializeSvgMetaData() { registerMetaData(smil::ElementTimeControl::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::ElementTimeControl_Bridge<Any, invoke> >::createInstance)); registerMetaData(smil::TimeEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::TimeEvent_Bridge<Any, invoke> >::createInstance)); registerMetaData(svg::GetSVGDocument::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::GetSVGDocument_Bridge<Any, invoke> >::createInstance)); registerMetaData(svg::SVGZoomEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::SVGZoomEvent_Bridge<Any, invoke> >::createInstance)); initializeSvgMetaDataA_G(); initializeSvgMetaDataH_N(); initializeSvgMetaDataO_U(); initializeSvgMetaDataV_Z(); } <commit_msg>(initializeSvgMetaData) : Register "XMLDocument".<commit_after>/* * Copyright 2008-2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "esnpapi.h" #include "proxyImpl.h" #include <any.h> #include <reflect.h> #include <org/w3c/dom.h> using namespace org::w3c::dom; void initializeSvgMetaData() { registerMetaData(smil::ElementTimeControl::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::ElementTimeControl_Bridge<Any, invoke> >::createInstance)); registerMetaData(smil::TimeEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::TimeEvent_Bridge<Any, invoke> >::createInstance)); registerMetaData(svg::GetSVGDocument::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::GetSVGDocument_Bridge<Any, invoke> >::createInstance)); registerMetaData(svg::SVGZoomEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::SVGZoomEvent_Bridge<Any, invoke> >::createInstance)); initializeSvgMetaDataA_G(); initializeSvgMetaDataH_N(); initializeSvgMetaDataO_U(); initializeSvgMetaDataV_Z(); registerMetaData(Document::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, Document_Bridge<Any, invoke> >::createInstance), "XMLDocument"); } <|endoftext|>
<commit_before>#include "line.hpp" // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <string> // std::string #include <vector> // std::vector namespace geometry { // constructor. // can be used for creating n-dimensional lines. Line::Line(const std::vector<float> point1, const std::vector<float> point2) { this->general_form_constant = NAN; if (point1 == point2 || point1.size() != point2.size()) { this->is_valid = false; // two identical points do not define a line. this->general_form_coefficients.push_back(NAN); } else { this->is_valid = true; // two distinct points define a line. this->are_points_defined = true; this->point1 = point1; this->point2 = point2; } } // constructor. // can be used for creating n-dimensional lines. Line::Line(const std::vector<float> general_form_coefficients, const float general_form_constant) { // TODO: add checks for the validity of general form coefficients and general form constant! this->is_valid = true; this->general_form_coefficients = general_form_coefficients; this->general_form_constant = general_form_constant; } std::string Line::get_general_form_equation() { // TODO: implement this function! std::string line_equation; return line_equation; } } <commit_msg>Bugfix `Line::Line` x 2: always initialize member `are_points_defined`.<commit_after>#include "line.hpp" // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <string> // std::string #include <vector> // std::vector namespace geometry { // constructor. // can be used for creating n-dimensional lines. Line::Line(const std::vector<float> point1, const std::vector<float> point2) { this->general_form_constant = NAN; if (point1 == point2 || point1.size() != point2.size()) { this->is_valid = false; // two identical points do not define a line. this->are_points_defined = false; this->general_form_coefficients.push_back(NAN); } else { this->is_valid = true; // two distinct points define a line. this->are_points_defined = true; this->point1 = point1; this->point2 = point2; } } // constructor. // can be used for creating n-dimensional lines. Line::Line(const std::vector<float> general_form_coefficients, const float general_form_constant) { // TODO: add checks for the validity of general form coefficients and general form constant! this->is_valid = true; this->are_points_defined = true; this->general_form_coefficients = general_form_coefficients; this->general_form_constant = general_form_constant; } std::string Line::get_general_form_equation() { // TODO: implement this function! std::string line_equation; return line_equation; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 Manjeet Dahiya * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "QXmppConfiguration.h" /// Creates a QXmppConfiguration object. QXmppConfiguration::QXmppConfiguration() : m_port(5222), m_resource("QXmpp"), m_autoAcceptSubscriptions(true), m_sendIntialPresence(true), m_sendRosterRequest(true), m_keepAlivePingsInterval(100), m_autoReconnectionEnabled(true), m_useSASLAuthentication(true), m_ignoreSslErrors(true), m_streamSecurityMode(QXmppConfiguration::TLSEnabled), m_nonSASLAuthMechanism(QXmppConfiguration::NonSASLDigest), m_SASLAuthMechanism(QXmppConfiguration::SASLDigestMD5) { } /// Destructor, destroys the QXmppConfiguration object. /// QXmppConfiguration::~QXmppConfiguration() { } /// Sets the host name. /// /// \param host host name of the XMPP server where connection has to be made /// (e.g. "jabber.org" and "talk.google.com"). It can also be an IP address in /// the form of a string (e.g. "192.168.1.25"). /// void QXmppConfiguration::setHost(const QString& host) { m_host = host; } /// Sets the domain name. /// /// \param domain Domain name e.g. "gmail.com" and "jabber.org". /// \note host name and domain name can be different for google /// domain name is gmail.com and host name is talk.google.com /// void QXmppConfiguration::setDomain(const QString& domain) { m_domain = domain; } /// Sets the port number. /// /// \param port Port number at which the XMPP server is listening. The default /// value is 5222. /// void QXmppConfiguration::setPort(int port) { m_port = port; } /// Sets the username. /// /// \param user Username of the account at the specified XMPP server. It should /// be the name without the domain name. E.g. "qxmpp.test1" and not /// "qxmpp.test1@gmail.com" /// void QXmppConfiguration::setUser(const QString& user) { m_user = user; } /// Sets the password. /// /// \param passwd Password for the specified username /// void QXmppConfiguration::setPasswd(const QString& passwd) { m_passwd = passwd; } /// Sets the resource identifier. /// /// \param resource Resource identifier of the client in connection. /// Multiple resources (e.g., devices or locations) may connect simultaneously /// to a server on behalf of each authorized client, with each resource /// differentiated by the resource identifier of an XMPP address /// (e.g. <node@domain/home> vs. <node@domain/work>) /// /// The default value is QXmpp /// void QXmppConfiguration::setResource(const QString& resource) { m_resource = resource; } /// Returns the host name. /// /// \return host name /// QString QXmppConfiguration::host() const { return m_host; } /// Returns the domain name. /// /// \return domain name /// QString QXmppConfiguration::domain() const { return m_domain; } /// Returns the port number. /// /// \return port number /// int QXmppConfiguration::port() const { return m_port; } /// Returns the username. /// /// \return username /// QString QXmppConfiguration::user() const { return m_user; } /// Returns the password. /// /// \return password /// QString QXmppConfiguration::passwd() const { return m_passwd; } /// Returns the resource identifier. /// /// \return resource identifier /// QString QXmppConfiguration::resource() const { return m_resource; } /// Returns the jabber id (jid). /// /// \return jabber id (jid) /// (e.g. "qxmpp.test1@gmail.com/resource" or qxmpptest@jabber.org/QXmpp156) /// QString QXmppConfiguration::jid() const { return getJidBare() + "/" + m_resource; } /// Returns the bare jabber id (jid), without the resource identifier. /// /// \return bare jabber id (jid) /// (e.g. "qxmpp.test1@gmail.com" or qxmpptest@jabber.org) /// QString QXmppConfiguration::jidBare() const { return m_user+"@"+m_domain; } /// Returns the auto-accept-subscriptions-request configuration. /// /// \return boolean value /// true means that auto-accept-subscriptions-request is enabled else disabled for false /// bool QXmppConfiguration::autoAcceptSubscriptions() const { return m_autoAcceptSubscriptions; } /// Sets the auto-accept-subscriptions-request configuration. /// /// \param value boolean value /// true means that auto-accept-subscriptions-request is enabled else disabled for false /// void QXmppConfiguration::setAutoAcceptSubscriptions(bool value) { m_autoAcceptSubscriptions = value; } /// Returns the auto-reconnect-on-disconnection-on-error configuration. /// /// \return boolean value /// true means that auto-reconnect is enabled else disabled for false /// bool QXmppConfiguration::autoReconnectionEnabled() const { return m_autoReconnectionEnabled; } /// Sets the auto-reconnect-on-disconnection-on-error configuration. /// /// \param value boolean value /// true means that auto-reconnect is enabled else disabled for false /// void QXmppConfiguration::setAutoReconnectionEnabled(bool value) { m_autoReconnectionEnabled = value; } /// Returns whether SSL errors (such as certificate validation errors) /// are to be ignored when connecting to the XMPP server. bool QXmppConfiguration::ignoreSslErrors() const { return m_ignoreSslErrors; } /// Specifies whether SSL errors (such as certificate validation errors) /// are to be ignored when connecting to an XMPP server. void QXmppConfiguration::setIgnoreSslErrors(bool value) { m_ignoreSslErrors = value; } /// Returns the type of authentication system specified by the user. /// \return true if SASL was specified else false. If the specified /// system is not available QXmpp will resort to the other one. bool QXmppConfiguration::useSASLAuthentication() const { return m_useSASLAuthentication; } /// Returns the type of authentication system specified by the user. /// \param useSASL to hint to use SASL authentication system if available. /// false will specify to use NonSASL XEP-0078: Non-SASL Authentication /// If the specified one is not availbe, library will use the othe one void QXmppConfiguration::setUseSASLAuthentication(bool useSASL) { m_useSASLAuthentication = useSASL; } /// Returns the specified security mode for the stream. The default value is /// QXmppConfiguration::TLSEnabled. /// \return StreamSecurityMode QXmppConfiguration::StreamSecurityMode QXmppConfiguration::streamSecurityMode() const { return m_streamSecurityMode; } /// Specifies the specified security mode for the stream. The default value is /// QXmppConfiguration::TLSEnabled. /// \param mode StreamSecurityMode void QXmppConfiguration::setStreamSecurityMode( QXmppConfiguration::StreamSecurityMode mode) { m_streamSecurityMode = mode; } /// Returns the Non-SASL authentication mechanism configuration. /// /// \return QXmppConfiguration::NonSASLAuthMechanism /// QXmppConfiguration::NonSASLAuthMechanism QXmppConfiguration::nonSASLAuthMechanism() const { return m_nonSASLAuthMechanism; } /// Hints the library the Non-SASL authentication mechanism to be used for authentication. /// /// \param mech QXmppConfiguration::NonSASLAuthMechanism /// void QXmppConfiguration::setNonSASLAuthMechanism( QXmppConfiguration::NonSASLAuthMechanism mech) { m_nonSASLAuthMechanism = mech; } /// Returns the SASL authentication mechanism configuration. /// /// \return QXmppConfiguration::SASLAuthMechanism /// QXmppConfiguration::SASLAuthMechanism QXmppConfiguration::sASLAuthMechanism() const { return m_SASLAuthMechanism; } /// Hints the library the SASL authentication mechanism to be used for authentication. /// /// \param mech QXmppConfiguration::SASLAuthMechanism /// void QXmppConfiguration::setSASLAuthMechanism( QXmppConfiguration::SASLAuthMechanism mech) { m_SASLAuthMechanism = mech; } /// Specifies the network proxy used for the connection made by QXmppClient. /// The default value is QNetworkProxy::DefaultProxy that is the proxy is /// determined based on the application proxy set using /// QNetworkProxy::setApplicationProxy(). /// \param proxy QNetworkProxy void QXmppConfiguration::setNetworkProxy(const QNetworkProxy& proxy) { m_networkProxy = proxy; } /// Returns the specified network proxy. /// The default value is QNetworkProxy::DefaultProxy that is the proxy is /// determined based on the application proxy set using /// QNetworkProxy::setApplicationProxy(). /// \return QNetworkProxy QNetworkProxy QXmppConfiguration::networkProxy() const { return m_networkProxy; } QString QXmppConfiguration::getHost() const { return m_host; } QString QXmppConfiguration::getDomain() const { return m_domain; } int QXmppConfiguration::getPort() const { return m_port; } QString QXmppConfiguration::getUser() const { return m_user; } QString QXmppConfiguration::getPasswd() const { return m_passwd; } QString QXmppConfiguration::getResource() const { return m_resource; } QString QXmppConfiguration::getJid() const { return getJidBare() + "/" + m_resource; } QString QXmppConfiguration::getJidBare() const { return m_user+"@"+m_domain; } bool QXmppConfiguration::getAutoAcceptSubscriptions() const { return m_autoAcceptSubscriptions; } bool QXmppConfiguration::getAutoReconnectionEnabled() const { return m_autoReconnectionEnabled; } bool QXmppConfiguration::getUseSASLAuthentication() const { return m_useSASLAuthentication; } bool QXmppConfiguration::getIgnoreSslErrors() const { return m_ignoreSslErrors; } QXmppConfiguration::StreamSecurityMode QXmppConfiguration::getStreamSecurityMode() const { return m_streamSecurityMode; } QXmppConfiguration::NonSASLAuthMechanism QXmppConfiguration::getNonSASLAuthMechanism() const { return m_nonSASLAuthMechanism; } QXmppConfiguration::SASLAuthMechanism QXmppConfiguration::getSASLAuthMechanism() const { return m_SASLAuthMechanism; } QNetworkProxy QXmppConfiguration::getNetworkProxy() const { return m_networkProxy; } <commit_msg>remove deprecated functions calls<commit_after>/* * Copyright (C) 2008-2010 Manjeet Dahiya * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "QXmppConfiguration.h" /// Creates a QXmppConfiguration object. QXmppConfiguration::QXmppConfiguration() : m_port(5222), m_resource("QXmpp"), m_autoAcceptSubscriptions(true), m_sendIntialPresence(true), m_sendRosterRequest(true), m_keepAlivePingsInterval(100), m_autoReconnectionEnabled(true), m_useSASLAuthentication(true), m_ignoreSslErrors(true), m_streamSecurityMode(QXmppConfiguration::TLSEnabled), m_nonSASLAuthMechanism(QXmppConfiguration::NonSASLDigest), m_SASLAuthMechanism(QXmppConfiguration::SASLDigestMD5) { } /// Destructor, destroys the QXmppConfiguration object. /// QXmppConfiguration::~QXmppConfiguration() { } /// Sets the host name. /// /// \param host host name of the XMPP server where connection has to be made /// (e.g. "jabber.org" and "talk.google.com"). It can also be an IP address in /// the form of a string (e.g. "192.168.1.25"). /// void QXmppConfiguration::setHost(const QString& host) { m_host = host; } /// Sets the domain name. /// /// \param domain Domain name e.g. "gmail.com" and "jabber.org". /// \note host name and domain name can be different for google /// domain name is gmail.com and host name is talk.google.com /// void QXmppConfiguration::setDomain(const QString& domain) { m_domain = domain; } /// Sets the port number. /// /// \param port Port number at which the XMPP server is listening. The default /// value is 5222. /// void QXmppConfiguration::setPort(int port) { m_port = port; } /// Sets the username. /// /// \param user Username of the account at the specified XMPP server. It should /// be the name without the domain name. E.g. "qxmpp.test1" and not /// "qxmpp.test1@gmail.com" /// void QXmppConfiguration::setUser(const QString& user) { m_user = user; } /// Sets the password. /// /// \param passwd Password for the specified username /// void QXmppConfiguration::setPasswd(const QString& passwd) { m_passwd = passwd; } /// Sets the resource identifier. /// /// \param resource Resource identifier of the client in connection. /// Multiple resources (e.g., devices or locations) may connect simultaneously /// to a server on behalf of each authorized client, with each resource /// differentiated by the resource identifier of an XMPP address /// (e.g. <node@domain/home> vs. <node@domain/work>) /// /// The default value is QXmpp /// void QXmppConfiguration::setResource(const QString& resource) { m_resource = resource; } /// Returns the host name. /// /// \return host name /// QString QXmppConfiguration::host() const { return m_host; } /// Returns the domain name. /// /// \return domain name /// QString QXmppConfiguration::domain() const { return m_domain; } /// Returns the port number. /// /// \return port number /// int QXmppConfiguration::port() const { return m_port; } /// Returns the username. /// /// \return username /// QString QXmppConfiguration::user() const { return m_user; } /// Returns the password. /// /// \return password /// QString QXmppConfiguration::passwd() const { return m_passwd; } /// Returns the resource identifier. /// /// \return resource identifier /// QString QXmppConfiguration::resource() const { return m_resource; } /// Returns the jabber id (jid). /// /// \return jabber id (jid) /// (e.g. "qxmpp.test1@gmail.com/resource" or qxmpptest@jabber.org/QXmpp156) /// QString QXmppConfiguration::jid() const { return jidBare() + "/" + m_resource; } /// Returns the bare jabber id (jid), without the resource identifier. /// /// \return bare jabber id (jid) /// (e.g. "qxmpp.test1@gmail.com" or qxmpptest@jabber.org) /// QString QXmppConfiguration::jidBare() const { return m_user+"@"+m_domain; } /// Returns the auto-accept-subscriptions-request configuration. /// /// \return boolean value /// true means that auto-accept-subscriptions-request is enabled else disabled for false /// bool QXmppConfiguration::autoAcceptSubscriptions() const { return m_autoAcceptSubscriptions; } /// Sets the auto-accept-subscriptions-request configuration. /// /// \param value boolean value /// true means that auto-accept-subscriptions-request is enabled else disabled for false /// void QXmppConfiguration::setAutoAcceptSubscriptions(bool value) { m_autoAcceptSubscriptions = value; } /// Returns the auto-reconnect-on-disconnection-on-error configuration. /// /// \return boolean value /// true means that auto-reconnect is enabled else disabled for false /// bool QXmppConfiguration::autoReconnectionEnabled() const { return m_autoReconnectionEnabled; } /// Sets the auto-reconnect-on-disconnection-on-error configuration. /// /// \param value boolean value /// true means that auto-reconnect is enabled else disabled for false /// void QXmppConfiguration::setAutoReconnectionEnabled(bool value) { m_autoReconnectionEnabled = value; } /// Returns whether SSL errors (such as certificate validation errors) /// are to be ignored when connecting to the XMPP server. bool QXmppConfiguration::ignoreSslErrors() const { return m_ignoreSslErrors; } /// Specifies whether SSL errors (such as certificate validation errors) /// are to be ignored when connecting to an XMPP server. void QXmppConfiguration::setIgnoreSslErrors(bool value) { m_ignoreSslErrors = value; } /// Returns the type of authentication system specified by the user. /// \return true if SASL was specified else false. If the specified /// system is not available QXmpp will resort to the other one. bool QXmppConfiguration::useSASLAuthentication() const { return m_useSASLAuthentication; } /// Returns the type of authentication system specified by the user. /// \param useSASL to hint to use SASL authentication system if available. /// false will specify to use NonSASL XEP-0078: Non-SASL Authentication /// If the specified one is not availbe, library will use the othe one void QXmppConfiguration::setUseSASLAuthentication(bool useSASL) { m_useSASLAuthentication = useSASL; } /// Returns the specified security mode for the stream. The default value is /// QXmppConfiguration::TLSEnabled. /// \return StreamSecurityMode QXmppConfiguration::StreamSecurityMode QXmppConfiguration::streamSecurityMode() const { return m_streamSecurityMode; } /// Specifies the specified security mode for the stream. The default value is /// QXmppConfiguration::TLSEnabled. /// \param mode StreamSecurityMode void QXmppConfiguration::setStreamSecurityMode( QXmppConfiguration::StreamSecurityMode mode) { m_streamSecurityMode = mode; } /// Returns the Non-SASL authentication mechanism configuration. /// /// \return QXmppConfiguration::NonSASLAuthMechanism /// QXmppConfiguration::NonSASLAuthMechanism QXmppConfiguration::nonSASLAuthMechanism() const { return m_nonSASLAuthMechanism; } /// Hints the library the Non-SASL authentication mechanism to be used for authentication. /// /// \param mech QXmppConfiguration::NonSASLAuthMechanism /// void QXmppConfiguration::setNonSASLAuthMechanism( QXmppConfiguration::NonSASLAuthMechanism mech) { m_nonSASLAuthMechanism = mech; } /// Returns the SASL authentication mechanism configuration. /// /// \return QXmppConfiguration::SASLAuthMechanism /// QXmppConfiguration::SASLAuthMechanism QXmppConfiguration::sASLAuthMechanism() const { return m_SASLAuthMechanism; } /// Hints the library the SASL authentication mechanism to be used for authentication. /// /// \param mech QXmppConfiguration::SASLAuthMechanism /// void QXmppConfiguration::setSASLAuthMechanism( QXmppConfiguration::SASLAuthMechanism mech) { m_SASLAuthMechanism = mech; } /// Specifies the network proxy used for the connection made by QXmppClient. /// The default value is QNetworkProxy::DefaultProxy that is the proxy is /// determined based on the application proxy set using /// QNetworkProxy::setApplicationProxy(). /// \param proxy QNetworkProxy void QXmppConfiguration::setNetworkProxy(const QNetworkProxy& proxy) { m_networkProxy = proxy; } /// Returns the specified network proxy. /// The default value is QNetworkProxy::DefaultProxy that is the proxy is /// determined based on the application proxy set using /// QNetworkProxy::setApplicationProxy(). /// \return QNetworkProxy QNetworkProxy QXmppConfiguration::networkProxy() const { return m_networkProxy; } QString QXmppConfiguration::getHost() const { return m_host; } QString QXmppConfiguration::getDomain() const { return m_domain; } int QXmppConfiguration::getPort() const { return m_port; } QString QXmppConfiguration::getUser() const { return m_user; } QString QXmppConfiguration::getPasswd() const { return m_passwd; } QString QXmppConfiguration::getResource() const { return m_resource; } QString QXmppConfiguration::getJid() const { return jidBare() + "/" + m_resource; } QString QXmppConfiguration::getJidBare() const { return m_user+"@"+m_domain; } bool QXmppConfiguration::getAutoAcceptSubscriptions() const { return m_autoAcceptSubscriptions; } bool QXmppConfiguration::getAutoReconnectionEnabled() const { return m_autoReconnectionEnabled; } bool QXmppConfiguration::getUseSASLAuthentication() const { return m_useSASLAuthentication; } bool QXmppConfiguration::getIgnoreSslErrors() const { return m_ignoreSslErrors; } QXmppConfiguration::StreamSecurityMode QXmppConfiguration::getStreamSecurityMode() const { return m_streamSecurityMode; } QXmppConfiguration::NonSASLAuthMechanism QXmppConfiguration::getNonSASLAuthMechanism() const { return m_nonSASLAuthMechanism; } QXmppConfiguration::SASLAuthMechanism QXmppConfiguration::getSASLAuthMechanism() const { return m_SASLAuthMechanism; } QNetworkProxy QXmppConfiguration::getNetworkProxy() const { return m_networkProxy; } <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "compound.hh" // // This header provides adaptors between the representation used by our compound_type<> // and representation used by Origin. // // For single-component keys the legacy representation is equivalent // to the only component's serialized form. For composite keys it the following // (See org.apache.cassandra.db.marshal.CompositeType): // // <representation> ::= ( <component> )+ // <component> ::= <length> <value> <EOC> // <length> ::= <uint16_t> // <EOC> ::= <uint8_t> // // <value> is component's value in serialized form. <EOC> is always 0 for partition key. // // Given a representation serialized using @CompoundType, provides a view on the // representation of the same components as they would be serialized by Origin. // // The view is exposed in a form of a byte range. For example of use see to_legacy() function. template <typename CompoundType> class legacy_compound_view { static_assert(!CompoundType::is_prefixable, "Legacy view not defined for prefixes"); CompoundType& _type; bytes_view _packed; public: legacy_compound_view(CompoundType& c, bytes_view packed) : _type(c) , _packed(packed) { } class iterator : public std::iterator<std::input_iterator_tag, bytes::value_type> { bool _singular; // Offset within virtual output space of a component. // // Offset: -2 -1 0 ... LEN-1 LEN // Field: [ length MSB ] [ length LSB ] [ VALUE ] [ EOC ] // int32_t _offset; typename CompoundType::iterator _i; public: struct end_tag {}; iterator(const legacy_compound_view& v) : _singular(v._type.is_singular()) , _offset(_singular ? 0 : -2) , _i(v._type.begin(v._packed)) { } iterator(const legacy_compound_view& v, end_tag) : _offset(-2) , _i(v._type.end(v._packed)) { } value_type operator*() const { int32_t component_size = _i->size(); if (_offset == -2) { return (component_size >> 8) & 0xff; } else if (_offset == -1) { return component_size & 0xff; } else if (_offset < component_size) { return (*_i)[_offset]; } else { // _offset == component_size return 0; // EOC field } } iterator& operator++() { auto component_size = (int32_t) _i->size(); if (_offset < component_size // When _singular, we skip the EOC byte. && (!_singular || _offset != (component_size - 1))) { ++_offset; } else { ++_i; _offset = -2; } return *this; } bool operator==(const iterator& other) const { return _offset == other._offset && other._i == _i; } bool operator!=(const iterator& other) const { return !(*this == other); } }; // A trichotomic comparator defined on @CompoundType representations which // orders them according to lexicographical ordering of their corresponding // legacy representations. // // tri_comparator(t)(k1, k2) // // ...is equivalent to: // // compare_unsigned(to_legacy(t, k1), to_legacy(t, k2)) // // ...but more efficient. // struct tri_comparator { const CompoundType& _type; tri_comparator(const CompoundType& type) : _type(type) { } tri_comparator(tri_comparator&& other) : _type(other._type) { } tri_comparator& operator=(tri_comparator&& other) { this->~tri_comparator(); new (this) tri_comparator(std::move(other)); return *this; } // @k1 and @k2 must be serialized using @type, which was passed to the constructor. int operator()(bytes_view k1, bytes_view k2) const { if (_type.is_singular()) { return compare_unsigned(*_type.begin(k1), *_type.begin(k2)); } return lexicographical_tri_compare( _type.begin(k1), _type.end(k1), _type.begin(k2), _type.end(k2), [] (const bytes_view& c1, const bytes_view& c2) -> int { if (c1.size() != c2.size()) { return c1.size() < c2.size() ? -1 : 1; } return memcmp(c1.begin(), c2.begin(), c1.size()); }); } }; // Equivalent to std::distance(begin(), end()), but computes faster size_t size() const { if (_type.is_singular()) { return _type.begin(_packed)->size(); } size_t s = 0; for (auto&& component : _type.components(_packed)) { s += 2 /* length field */ + component.size() + 1 /* EOC */; } return s; } iterator begin() const { return iterator(*this); } iterator end() const { return iterator(*this, typename iterator::end_tag()); } }; // Converts compound_type<> representation to legacy representation // @packed is assumed to be serialized using supplied @type. template <typename CompoundType> static inline bytes to_legacy(CompoundType& type, bytes_view packed) { legacy_compound_view<CompoundType> lv(type, packed); bytes legacy_form(bytes::initialized_later(), lv.size()); std::copy(lv.begin(), lv.end(), legacy_form.begin()); return legacy_form; } <commit_msg>compound_compat: Remove leftover code<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "compound.hh" // // This header provides adaptors between the representation used by our compound_type<> // and representation used by Origin. // // For single-component keys the legacy representation is equivalent // to the only component's serialized form. For composite keys it the following // (See org.apache.cassandra.db.marshal.CompositeType): // // <representation> ::= ( <component> )+ // <component> ::= <length> <value> <EOC> // <length> ::= <uint16_t> // <EOC> ::= <uint8_t> // // <value> is component's value in serialized form. <EOC> is always 0 for partition key. // // Given a representation serialized using @CompoundType, provides a view on the // representation of the same components as they would be serialized by Origin. // // The view is exposed in a form of a byte range. For example of use see to_legacy() function. template <typename CompoundType> class legacy_compound_view { static_assert(!CompoundType::is_prefixable, "Legacy view not defined for prefixes"); CompoundType& _type; bytes_view _packed; public: legacy_compound_view(CompoundType& c, bytes_view packed) : _type(c) , _packed(packed) { } class iterator : public std::iterator<std::input_iterator_tag, bytes::value_type> { bool _singular; // Offset within virtual output space of a component. // // Offset: -2 -1 0 ... LEN-1 LEN // Field: [ length MSB ] [ length LSB ] [ VALUE ] [ EOC ] // int32_t _offset; typename CompoundType::iterator _i; public: struct end_tag {}; iterator(const legacy_compound_view& v) : _singular(v._type.is_singular()) , _offset(_singular ? 0 : -2) , _i(v._type.begin(v._packed)) { } iterator(const legacy_compound_view& v, end_tag) : _offset(-2) , _i(v._type.end(v._packed)) { } value_type operator*() const { int32_t component_size = _i->size(); if (_offset == -2) { return (component_size >> 8) & 0xff; } else if (_offset == -1) { return component_size & 0xff; } else if (_offset < component_size) { return (*_i)[_offset]; } else { // _offset == component_size return 0; // EOC field } } iterator& operator++() { auto component_size = (int32_t) _i->size(); if (_offset < component_size // When _singular, we skip the EOC byte. && (!_singular || _offset != (component_size - 1))) { ++_offset; } else { ++_i; _offset = -2; } return *this; } bool operator==(const iterator& other) const { return _offset == other._offset && other._i == _i; } bool operator!=(const iterator& other) const { return !(*this == other); } }; // A trichotomic comparator defined on @CompoundType representations which // orders them according to lexicographical ordering of their corresponding // legacy representations. // // tri_comparator(t)(k1, k2) // // ...is equivalent to: // // compare_unsigned(to_legacy(t, k1), to_legacy(t, k2)) // // ...but more efficient. // struct tri_comparator { const CompoundType& _type; tri_comparator(const CompoundType& type) : _type(type) { } // @k1 and @k2 must be serialized using @type, which was passed to the constructor. int operator()(bytes_view k1, bytes_view k2) const { if (_type.is_singular()) { return compare_unsigned(*_type.begin(k1), *_type.begin(k2)); } return lexicographical_tri_compare( _type.begin(k1), _type.end(k1), _type.begin(k2), _type.end(k2), [] (const bytes_view& c1, const bytes_view& c2) -> int { if (c1.size() != c2.size()) { return c1.size() < c2.size() ? -1 : 1; } return memcmp(c1.begin(), c2.begin(), c1.size()); }); } }; // Equivalent to std::distance(begin(), end()), but computes faster size_t size() const { if (_type.is_singular()) { return _type.begin(_packed)->size(); } size_t s = 0; for (auto&& component : _type.components(_packed)) { s += 2 /* length field */ + component.size() + 1 /* EOC */; } return s; } iterator begin() const { return iterator(*this); } iterator end() const { return iterator(*this, typename iterator::end_tag()); } }; // Converts compound_type<> representation to legacy representation // @packed is assumed to be serialized using supplied @type. template <typename CompoundType> static inline bytes to_legacy(CompoundType& type, bytes_view packed) { legacy_compound_view<CompoundType> lv(type, packed); bytes legacy_form(bytes::initialized_later(), lv.size()); std::copy(lv.begin(), lv.end(), legacy_form.begin()); return legacy_form; } <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file brw_cubemap_normalize.cpp * * IR lower pass to perform the normalization of the cubemap coordinates to * have the largest magnitude component be -1.0 or 1.0. * * \author Eric Anholt <eric@anholt.net> */ #include "glsl/glsl_types.h" #include "glsl/ir.h" class brw_cubemap_normalize_visitor : public ir_hierarchical_visitor { public: brw_cubemap_normalize_visitor() { progress = false; } ir_visitor_status visit_leave(ir_texture *ir); bool progress; }; ir_visitor_status brw_cubemap_normalize_visitor::visit_leave(ir_texture *ir) { if (ir->sampler->type->sampler_dimensionality != GLSL_SAMPLER_DIM_CUBE) return visit_continue; if (ir->op == ir_txs) return visit_continue; void *mem_ctx = ralloc_parent(ir); ir_variable *var = new(mem_ctx) ir_variable(ir->coordinate->type, "coordinate", ir_var_auto); base_ir->insert_before(var); ir_dereference *deref = new(mem_ctx) ir_dereference_variable(var); ir_assignment *assign = new(mem_ctx) ir_assignment(deref, ir->coordinate, NULL); base_ir->insert_before(assign); deref = new(mem_ctx) ir_dereference_variable(var); ir_rvalue *swiz0 = new(mem_ctx) ir_swizzle(deref, 0, 0, 0, 0, 1); deref = new(mem_ctx) ir_dereference_variable(var); ir_rvalue *swiz1 = new(mem_ctx) ir_swizzle(deref, 1, 0, 0, 0, 1); deref = new(mem_ctx) ir_dereference_variable(var); ir_rvalue *swiz2 = new(mem_ctx) ir_swizzle(deref, 2, 0, 0, 0, 1); swiz0 = new(mem_ctx) ir_expression(ir_unop_abs, swiz0->type, swiz0, NULL); swiz1 = new(mem_ctx) ir_expression(ir_unop_abs, swiz1->type, swiz1, NULL); swiz2 = new(mem_ctx) ir_expression(ir_unop_abs, swiz2->type, swiz2, NULL); ir_expression *expr; expr = new(mem_ctx) ir_expression(ir_binop_max, glsl_type::float_type, swiz0, swiz1); expr = new(mem_ctx) ir_expression(ir_binop_max, glsl_type::float_type, expr, swiz2); expr = new(mem_ctx) ir_expression(ir_unop_rcp, glsl_type::float_type, expr, NULL); deref = new(mem_ctx) ir_dereference_variable(var); ir->coordinate = new(mem_ctx) ir_expression(ir_binop_mul, ir->coordinate->type, deref, expr); progress = true; return visit_continue; } extern "C" { bool brw_do_cubemap_normalize(exec_list *instructions) { brw_cubemap_normalize_visitor v; visit_list_elements(&v, instructions); return v.progress; } } <commit_msg>i965: Fix cube array coordinate normalization<commit_after>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file brw_cubemap_normalize.cpp * * IR lower pass to perform the normalization of the cubemap coordinates to * have the largest magnitude component be -1.0 or 1.0. * * \author Eric Anholt <eric@anholt.net> */ #include "glsl/glsl_types.h" #include "glsl/ir.h" #include "program/prog_instruction.h" /* For WRITEMASK_* */ class brw_cubemap_normalize_visitor : public ir_hierarchical_visitor { public: brw_cubemap_normalize_visitor() { progress = false; } ir_visitor_status visit_leave(ir_texture *ir); bool progress; }; ir_visitor_status brw_cubemap_normalize_visitor::visit_leave(ir_texture *ir) { if (ir->sampler->type->sampler_dimensionality != GLSL_SAMPLER_DIM_CUBE) return visit_continue; if (ir->op == ir_txs) return visit_continue; void *mem_ctx = ralloc_parent(ir); ir_variable *var = new(mem_ctx) ir_variable(ir->coordinate->type, "coordinate", ir_var_auto); base_ir->insert_before(var); ir_dereference *deref = new(mem_ctx) ir_dereference_variable(var); ir_assignment *assign = new(mem_ctx) ir_assignment(deref, ir->coordinate, NULL); base_ir->insert_before(assign); deref = new(mem_ctx) ir_dereference_variable(var); ir_rvalue *swiz0 = new(mem_ctx) ir_swizzle(deref, 0, 0, 0, 0, 1); deref = new(mem_ctx) ir_dereference_variable(var); ir_rvalue *swiz1 = new(mem_ctx) ir_swizzle(deref, 1, 0, 0, 0, 1); deref = new(mem_ctx) ir_dereference_variable(var); ir_rvalue *swiz2 = new(mem_ctx) ir_swizzle(deref, 2, 0, 0, 0, 1); swiz0 = new(mem_ctx) ir_expression(ir_unop_abs, swiz0->type, swiz0, NULL); swiz1 = new(mem_ctx) ir_expression(ir_unop_abs, swiz1->type, swiz1, NULL); swiz2 = new(mem_ctx) ir_expression(ir_unop_abs, swiz2->type, swiz2, NULL); ir_expression *expr; expr = new(mem_ctx) ir_expression(ir_binop_max, glsl_type::float_type, swiz0, swiz1); expr = new(mem_ctx) ir_expression(ir_binop_max, glsl_type::float_type, expr, swiz2); expr = new(mem_ctx) ir_expression(ir_unop_rcp, glsl_type::float_type, expr, NULL); /* coordinate.xyz *= expr */ assign = new(mem_ctx) ir_assignment( new(mem_ctx) ir_dereference_variable(var), new(mem_ctx) ir_expression(ir_binop_mul, ir->coordinate->type, new(mem_ctx) ir_dereference_variable(var), expr)); assign->write_mask = WRITEMASK_XYZ; base_ir->insert_before(assign); ir->coordinate = new(mem_ctx) ir_dereference_variable(var); progress = true; return visit_continue; } extern "C" { bool brw_do_cubemap_normalize(exec_list *instructions) { brw_cubemap_normalize_visitor v; visit_list_elements(&v, instructions); return v.progress; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file task.cpp * * Main task handling the temperature calibration process * * @author Beat Küng <beat-kueng@gmx.net> */ #include <uORB/topics/sensor_gyro.h> #include <mathlib/mathlib.h> #include <px4_log.h> #include <px4_posix.h> #include <px4_tasks.h> #include <drivers/drv_hrt.h> #include <unistd.h> #include "common.h" #include "temperature_calibration.h" #include "accel.h" #include "baro.h" #include "gyro.h" class TemperatureCalibration; namespace temperature_calibration { TemperatureCalibration *instance = nullptr; } class TemperatureCalibration { public: /** * Constructor */ TemperatureCalibration(bool accel, bool baro, bool gyro); /** * Destructor */ ~TemperatureCalibration(); /** * Start task. * * @return OK on success. */ int start(); static void do_temperature_calibration(int argc, char *argv[]); void task_main(); void exit() { _force_task_exit = true; } private: bool _force_task_exit = false; int _control_task = -1; // task handle for task bool _accel; ///< enable accel calibration? bool _baro; ///< enable baro calibration? bool _gyro; ///< enable gyro calibration? }; TemperatureCalibration::TemperatureCalibration(bool accel, bool baro, bool gyro) : _accel(accel), _baro(baro), _gyro(gyro) { } TemperatureCalibration::~TemperatureCalibration() { } void TemperatureCalibration::task_main() { // subscribe to all gyro instances int gyro_sub[SENSOR_COUNT_MAX]; px4_pollfd_struct_t fds[SENSOR_COUNT_MAX] = {}; unsigned num_gyro = orb_group_count(ORB_ID(sensor_gyro)); if (num_gyro > SENSOR_COUNT_MAX) { num_gyro = SENSOR_COUNT_MAX; } for (unsigned i = 0; i < num_gyro; i++) { gyro_sub[i] = orb_subscribe_multi(ORB_ID(sensor_gyro), i); fds[i].fd = gyro_sub[i]; fds[i].events = POLLIN; } int32_t min_temp_rise = 24; param_get(param_find("SYS_CAL_TEMP"), &min_temp_rise); PX4_INFO("Waiting for %i degrees difference in sensor temperature", min_temp_rise); //init calibrators TemperatureCalibrationBase *calibrators[3]; bool error_reported[3] = {}; int num_calibrators = 0; if (_accel) { calibrators[num_calibrators] = new TemperatureCalibrationAccel(min_temp_rise); if (calibrators[num_calibrators]) { ++num_calibrators; } else { PX4_ERR("alloc failed"); } } if (_baro) { calibrators[num_calibrators] = new TemperatureCalibrationBaro(min_temp_rise); if (calibrators[num_calibrators]) { ++num_calibrators; } else { PX4_ERR("alloc failed"); } } if (_gyro) { calibrators[num_calibrators] = new TemperatureCalibrationGyro(min_temp_rise, gyro_sub, num_gyro); if (calibrators[num_calibrators]) { ++num_calibrators; } else { PX4_ERR("alloc failed"); } } // reset params for (int i = 0; i < num_calibrators; ++i) { calibrators[i]->reset_calibration(); } // make sure the system updates the changed parameters param_notify_changes(); usleep(300000); // wait a bit for the system to apply the parameters hrt_abstime next_progress_output = hrt_absolute_time() + 1e6; while (!_force_task_exit) { /* we poll on the gyro(s), since this is the sensor with the highest update rate. * Each individual sensor will then check on its own if there's new data. */ int ret = px4_poll(fds, num_gyro, 1000); if (ret < 0) { // Poll error, sleep and try again usleep(10000); continue; } else if (ret == 0) { // Poll timeout or no new data, do nothing continue; } //if gyro is not enabled: we must do an orb_copy here, so that poll() does not immediately return again if (!_gyro) { sensor_gyro_s gyro_data; for (int i = 0; i < num_gyro; ++i) { orb_copy(ORB_ID(sensor_gyro), gyro_sub[i], &gyro_data); } } int min_progress = 110; for (int i = 0; i < num_calibrators; ++i) { ret = calibrators[i]->update(); if (ret < 0) { if (!error_reported[i]) { PX4_ERR("Calibration update step failed (%i)", ret); error_reported[i] = true; } } else if (ret < min_progress) { min_progress = ret; } } if (min_progress == 110) { break; // we are done } //print progress each second hrt_abstime now = hrt_absolute_time(); if (now > next_progress_output) { PX4_INFO("Calibration progress: %i%%", min_progress); next_progress_output = now + 1e6; } } PX4_INFO("Sensor Measurments completed"); // do final calculations & parameter storage for (int i = 0; i < num_calibrators; ++i) { int ret = calibrators[i]->finish(); if (ret < 0) { PX4_ERR("Failed to finish calibration process (%i)", ret); } } for (int i = 0; i < num_calibrators; ++i) { delete calibrators[i]; } for (unsigned i = 0; i < num_gyro; i++) { orb_unsubscribe(gyro_sub[i]); } delete temperature_calibration::instance; temperature_calibration::instance = nullptr; PX4_INFO("Exiting temperature calibration task"); } void TemperatureCalibration::do_temperature_calibration(int argc, char *argv[]) { temperature_calibration::instance->task_main(); } int TemperatureCalibration::start() { ASSERT(_control_task == -1); _control_task = px4_task_spawn_cmd("temperature_calib", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 5800, (px4_main_t)&TemperatureCalibration::do_temperature_calibration, nullptr); if (_control_task < 0) { delete temperature_calibration::instance; temperature_calibration::instance = nullptr; PX4_ERR("start failed"); return -errno; } return 0; } int run_temperature_calibration(bool accel, bool baro, bool gyro) { PX4_INFO("Starting temperature calibration task (accel=%i, baro=%i, gyro=%i)", (int)accel, (int)baro, (int)gyro); temperature_calibration::instance = new TemperatureCalibration(accel, baro, gyro); if (temperature_calibration::instance == nullptr) { PX4_ERR("alloc failed"); return 1; } return temperature_calibration::instance->start(); } <commit_msg>temperature_calibration: make sure to save the params after the process<commit_after>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file task.cpp * * Main task handling the temperature calibration process * * @author Beat Küng <beat-kueng@gmx.net> */ #include <uORB/topics/sensor_gyro.h> #include <mathlib/mathlib.h> #include <px4_log.h> #include <px4_posix.h> #include <px4_tasks.h> #include <drivers/drv_hrt.h> #include <unistd.h> #include "common.h" #include "temperature_calibration.h" #include "accel.h" #include "baro.h" #include "gyro.h" class TemperatureCalibration; namespace temperature_calibration { TemperatureCalibration *instance = nullptr; } class TemperatureCalibration { public: /** * Constructor */ TemperatureCalibration(bool accel, bool baro, bool gyro); /** * Destructor */ ~TemperatureCalibration(); /** * Start task. * * @return OK on success. */ int start(); static void do_temperature_calibration(int argc, char *argv[]); void task_main(); void exit() { _force_task_exit = true; } private: bool _force_task_exit = false; int _control_task = -1; // task handle for task bool _accel; ///< enable accel calibration? bool _baro; ///< enable baro calibration? bool _gyro; ///< enable gyro calibration? }; TemperatureCalibration::TemperatureCalibration(bool accel, bool baro, bool gyro) : _accel(accel), _baro(baro), _gyro(gyro) { } TemperatureCalibration::~TemperatureCalibration() { } void TemperatureCalibration::task_main() { // subscribe to all gyro instances int gyro_sub[SENSOR_COUNT_MAX]; px4_pollfd_struct_t fds[SENSOR_COUNT_MAX] = {}; unsigned num_gyro = orb_group_count(ORB_ID(sensor_gyro)); if (num_gyro > SENSOR_COUNT_MAX) { num_gyro = SENSOR_COUNT_MAX; } for (unsigned i = 0; i < num_gyro; i++) { gyro_sub[i] = orb_subscribe_multi(ORB_ID(sensor_gyro), i); fds[i].fd = gyro_sub[i]; fds[i].events = POLLIN; } int32_t min_temp_rise = 24; param_get(param_find("SYS_CAL_TEMP"), &min_temp_rise); PX4_INFO("Waiting for %i degrees difference in sensor temperature", min_temp_rise); //init calibrators TemperatureCalibrationBase *calibrators[3]; bool error_reported[3] = {}; int num_calibrators = 0; if (_accel) { calibrators[num_calibrators] = new TemperatureCalibrationAccel(min_temp_rise); if (calibrators[num_calibrators]) { ++num_calibrators; } else { PX4_ERR("alloc failed"); } } if (_baro) { calibrators[num_calibrators] = new TemperatureCalibrationBaro(min_temp_rise); if (calibrators[num_calibrators]) { ++num_calibrators; } else { PX4_ERR("alloc failed"); } } if (_gyro) { calibrators[num_calibrators] = new TemperatureCalibrationGyro(min_temp_rise, gyro_sub, num_gyro); if (calibrators[num_calibrators]) { ++num_calibrators; } else { PX4_ERR("alloc failed"); } } // reset params for (int i = 0; i < num_calibrators; ++i) { calibrators[i]->reset_calibration(); } // make sure the system updates the changed parameters param_notify_changes(); usleep(300000); // wait a bit for the system to apply the parameters hrt_abstime next_progress_output = hrt_absolute_time() + 1e6; while (!_force_task_exit) { /* we poll on the gyro(s), since this is the sensor with the highest update rate. * Each individual sensor will then check on its own if there's new data. */ int ret = px4_poll(fds, num_gyro, 1000); if (ret < 0) { // Poll error, sleep and try again usleep(10000); continue; } else if (ret == 0) { // Poll timeout or no new data, do nothing continue; } //if gyro is not enabled: we must do an orb_copy here, so that poll() does not immediately return again if (!_gyro) { sensor_gyro_s gyro_data; for (int i = 0; i < num_gyro; ++i) { orb_copy(ORB_ID(sensor_gyro), gyro_sub[i], &gyro_data); } } int min_progress = 110; for (int i = 0; i < num_calibrators; ++i) { ret = calibrators[i]->update(); if (ret < 0) { if (!error_reported[i]) { PX4_ERR("Calibration update step failed (%i)", ret); error_reported[i] = true; } } else if (ret < min_progress) { min_progress = ret; } } if (min_progress == 110) { break; // we are done } //print progress each second hrt_abstime now = hrt_absolute_time(); if (now > next_progress_output) { PX4_INFO("Calibration progress: %i%%", min_progress); next_progress_output = now + 1e6; } } PX4_INFO("Sensor Measurments completed"); // do final calculations & parameter storage for (int i = 0; i < num_calibrators; ++i) { int ret = calibrators[i]->finish(); if (ret < 0) { PX4_ERR("Failed to finish calibration process (%i)", ret); } } param_notify_changes(); int ret = param_save_default(); if (ret != 0) { PX4_ERR("Failed to save params (%i)", ret); } for (int i = 0; i < num_calibrators; ++i) { delete calibrators[i]; } for (unsigned i = 0; i < num_gyro; i++) { orb_unsubscribe(gyro_sub[i]); } delete temperature_calibration::instance; temperature_calibration::instance = nullptr; PX4_INFO("Exiting temperature calibration task"); } void TemperatureCalibration::do_temperature_calibration(int argc, char *argv[]) { temperature_calibration::instance->task_main(); } int TemperatureCalibration::start() { ASSERT(_control_task == -1); _control_task = px4_task_spawn_cmd("temperature_calib", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 5800, (px4_main_t)&TemperatureCalibration::do_temperature_calibration, nullptr); if (_control_task < 0) { delete temperature_calibration::instance; temperature_calibration::instance = nullptr; PX4_ERR("start failed"); return -errno; } return 0; } int run_temperature_calibration(bool accel, bool baro, bool gyro) { PX4_INFO("Starting temperature calibration task (accel=%i, baro=%i, gyro=%i)", (int)accel, (int)baro, (int)gyro); temperature_calibration::instance = new TemperatureCalibration(accel, baro, gyro); if (temperature_calibration::instance == nullptr) { PX4_ERR("alloc failed"); return 1; } return temperature_calibration::instance->start(); } <|endoftext|>
<commit_before> #include "luiText.h" #include "pandaVersion.h" TypeHandle LUIText::_type_handle; LUIText::LUIText(PyObject* self, LUIObject* parent, const wstring& text, const string& font_name, float font_size, float x, float y, bool wordwrap) : LUIObject(self, parent, x, y), _text(text), _font_size(font_size), _wordwrap(wordwrap) { set_font(font_name); } LUIText::~LUIText() { } void LUIText::update_text() { int len = _text.size(); nassertv(_font != NULL); if (lui_cat.is_spam()) { lui_cat.spam() << "Current text is '" << _text.c_str() << "'" << endl; } // Remove all sprites which aren't required while (_children.size() > len) { if (lui_cat.is_spam()) { lui_cat.spam() << "Removing sprite .. " << endl; } remove_child(*_children.begin()); } // Allocate as many sprites as required int to_allocate = len - _children.size(); for (int i = 0; i < to_allocate; ++i) { if (lui_cat.is_spam()) { lui_cat.spam() << "Allocating sprite .. " << endl; } PT(LUISprite) sprite = new LUISprite(this); // Required for smooth text rendering sprite->set_snap_position(false); } // Pixels per unit, used to convert betweeen coordinate spaces float ppu = _font_size; float line_height = _font->get_line_height(); // Unreference all current glyphs _glyphs.clear(); // Iterate over the sprites int char_idx = 0; float current_x_pos = 0.0f; for (auto it = _children.begin(); it != _children.end(); ++it, ++char_idx) { LUIBaseElement* child = *it; LUISprite* sprite = DCAST(LUISprite, child); // A lui text should have only sprites contained, otherwise something went wrong nassertv(sprite != NULL); int char_code = (int)_text.at(char_idx); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) const_glyph; #else const TextGlyph* const_glyph; #endif if (!_font->get_glyph(char_code, const_glyph)) { sprite->set_texture((Texture*)NULL); lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } CPT(DynamicTextGlyph) dynamic_glyph = DCAST(DynamicTextGlyph, const_glyph); // If this gets executed, a non-dynamic font got loaded. nassertv(dynamic_glyph != NULL); _glyphs.push_back(dynamic_glyph); // Some characters have no texture (like space) if (dynamic_glyph->get_page() == NULL) { lui_cat.debug() << "Character '" << (char)char_code << "' (Code: " << char_code << ") has no texture page!" << endl; sprite->hide(); } else { sprite->show(); // LUISprite has a check if the texture is the same, so if the atlas didn't // change, this is quite efficient. sprite->set_texture(dynamic_glyph->get_page()); // Position the glyph. sprite->set_pos( current_x_pos + dynamic_glyph->get_left() * ppu, (0.85 - dynamic_glyph->get_top()) * ppu + 1); // The V coordinate is inverted, as panda stores the textures flipped sprite->set_uv_range( dynamic_glyph->get_uv_left(), 1 - dynamic_glyph->get_uv_top(), dynamic_glyph->get_uv_right(), 1 - dynamic_glyph->get_uv_bottom()); // Determine size from coordinates sprite->set_size( (dynamic_glyph->get_right() - dynamic_glyph->get_left()) * ppu, (dynamic_glyph->get_top() - dynamic_glyph->get_bottom()) * ppu); sprite->set_color(_color); } // Move *cursor* by glyph length current_x_pos += dynamic_glyph->get_advance() * ppu; } set_size( floor(current_x_pos), floor(line_height * ppu)); } void LUIText::ls(int indent) { cout << string(indent, ' ') << "[" << _debug_name << "] pos = " << get_abs_pos().get_x() << ", " << get_abs_pos().get_y() << "; size = " << get_width() << " x " << get_height() << "; text = u'" << _text << "'; color = " << _color << " / " << _composed_color << "; z = " << _z_offset << endl; } int LUIText::get_char_index(float pos) const { if (lui_cat.is_spam()) { lui_cat.spam() << "Trying to resolve " << pos << " into a character index .." << endl; } nassertr(_font != NULL, 0); float cursor = 0.0f; for (int i = 0; i < _text.size(); ++i) { int char_code = (int)_text.at(i); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) glyph; #else const TextGlyph* glyph; #endif if (!_font->get_glyph(char_code, glyph)) { lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } nassertr(glyph != NULL, 0); cursor += glyph->get_advance() * _font_size; if (cursor > pos) { return i; } } return _text.size(); } float LUIText::get_char_pos(int char_index) const { if (lui_cat.is_spam()) { lui_cat.spam() << "Trying to resolve " << char_index << " into a character position .." << endl; } nassertr(_font != NULL, 0); // Make sure we don't iterate over the text bounds int iterate_max = min(char_index, (int)_text.size()); float cursor = 0.0f; for (int i = 0; i < iterate_max; i++) { int char_code = (int)_text.at(i); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) glyph; #else const TextGlyph* glyph; #endif if (!_font->get_glyph(char_code, glyph)) { lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } nassertr(glyph != NULL, 0); cursor += glyph->get_advance() * _font_size; } return cursor; } <commit_msg>Add wordwrap support based on the width of the parent element. Add get_line_breaks function to return all the places line breaks need to be added to fit the text in the container.<commit_after> #include "luiText.h" #include "pandaVersion.h" TypeHandle LUIText::_type_handle; LUIText::LUIText(PyObject* self, LUIObject* parent, const wstring& text, const string& font_name, float font_size, float x, float y, bool wordwrap) : LUIObject(self, parent, x, y, parent->get_parent_width(), parent->get_parent_width()), _text(text), _font_size(font_size), _wordwrap(wordwrap) { set_font(font_name); } LUIText::~LUIText() { } void LUIText::update_text() { int len = _text.size(); nassertv(_font != NULL); if (lui_cat.is_spam()) { lui_cat.spam() << "Current text is '" << _text.c_str() << "'" << endl; } // Remove all sprites which aren't required while (_children.size() > len) { if (lui_cat.is_spam()) { lui_cat.spam() << "Removing sprite .. " << endl; } remove_child(*_children.begin()); } // Allocate as many sprites as required int to_allocate = len - _children.size(); for (int i = 0; i < to_allocate; ++i) { if (lui_cat.is_spam()) { lui_cat.spam() << "Allocating sprite .. " << endl; } PT(LUISprite) sprite = new LUISprite(this); // Required for smooth text rendering sprite->set_snap_position(false); } // Pixels per unit, used to convert betweeen coordinate spaces float ppu = _font_size; float line_height = _font->get_line_height(); vector<int> line_breaks = get_line_breaks(); // Unreference all current glyphs _glyphs.clear(); // Iterate over the sprites int char_idx = 0; float current_x_pos = 0.0f; float current_y_pos = 0.0f; for (auto it = _children.begin(); it != _children.end(); ++it, ++char_idx) { LUIBaseElement* child = *it; LUISprite* sprite = DCAST(LUISprite, child); // A lui text should have only sprites contained, otherwise something went wrong nassertv(sprite != NULL); int char_code = (int)_text.at(char_idx); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) const_glyph; #else const TextGlyph* const_glyph; #endif // Newline if (_wordwrap == TRUE && char_code == 10) { current_x_pos = 0; current_y_pos += floor(line_height * ppu); continue; } if (_wordwrap == TRUE) { if(find(line_breaks.begin(), line_breaks.end(), char_idx) != line_breaks.end()) { current_x_pos = 0; current_y_pos += floor(line_height * ppu); } } if (!_font->get_glyph(char_code, const_glyph)) { sprite->set_texture((Texture*)NULL); lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } CPT(DynamicTextGlyph) dynamic_glyph = DCAST(DynamicTextGlyph, const_glyph); // If this gets executed, a non-dynamic font got loaded. nassertv(dynamic_glyph != NULL); _glyphs.push_back(dynamic_glyph); // Some characters have no texture (like space) if (dynamic_glyph->get_page() == NULL) { lui_cat.debug() << "Character '" << (char)char_code << "' (Code: " << char_code << ") has no texture page!" << endl; sprite->hide(); } else { sprite->show(); // LUISprite has a check if the texture is the same, so if the atlas didn't // change, this is quite efficient. sprite->set_texture(dynamic_glyph->get_page()); // Position the glyph. sprite->set_pos( current_x_pos + dynamic_glyph->get_left() * ppu, (0.85 - dynamic_glyph->get_top()) * ppu + 1 + current_y_pos); // The V coordinate is inverted, as panda stores the textures flipped sprite->set_uv_range( dynamic_glyph->get_uv_left(), 1 - dynamic_glyph->get_uv_top(), dynamic_glyph->get_uv_right(), 1 - dynamic_glyph->get_uv_bottom()); // Determine size from coordinates sprite->set_size( (dynamic_glyph->get_right() - dynamic_glyph->get_left()) * ppu, (dynamic_glyph->get_top() - dynamic_glyph->get_bottom()) * ppu); sprite->set_color(_color); } // Break word wrapping if (_wordwrap == TRUE && current_x_pos + dynamic_glyph->get_advance() * ppu > get_parent_width()) { // glyph length longer then width, force to next line current_x_pos = 0; current_y_pos += floor(line_height * ppu); } else { // Trim left if(_wordwrap == TRUE && current_x_pos == 0 && dynamic_glyph->get_page() == NULL) { continue; } // Move *cursor* by glyph length current_x_pos += dynamic_glyph->get_advance() * ppu; } } if (_wordwrap == TRUE) { set_size( get_parent_width(), floor(current_y_pos + line_height * ppu)); } else { set_size( floor(current_x_pos), floor(line_height * ppu)); } } void LUIText::ls(int indent) { cout << string(indent, ' ') << "[" << _debug_name << "] pos = " << get_abs_pos().get_x() << ", " << get_abs_pos().get_y() << "; size = " << get_width() << " x " << get_height() << "; text = u'" << _text << "'; color = " << _color << " / " << _composed_color << "; z = " << _z_offset << endl; } int LUIText::get_char_index(float pos) const { if (lui_cat.is_spam()) { lui_cat.spam() << "Trying to resolve " << pos << " into a character index .." << endl; } nassertr(_font != NULL, 0); float cursor = 0.0f; for (int i = 0; i < _text.size(); ++i) { int char_code = (int)_text.at(i); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) glyph; #else const TextGlyph* glyph; #endif if (!_font->get_glyph(char_code, glyph)) { lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } nassertr(glyph != NULL, 0); cursor += glyph->get_advance() * _font_size; if (cursor > pos) { return i; } } return _text.size(); } float LUIText::get_char_pos(int char_index) const { if (lui_cat.is_spam()) { lui_cat.spam() << "Trying to resolve " << char_index << " into a character position .." << endl; } nassertr(_font != NULL, 0); // Make sure we don't iterate over the text bounds int iterate_max = min(char_index, (int)_text.size()); float cursor = 0.0f; for (int i = 0; i < iterate_max; i++) { int char_code = (int)_text.at(i); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) glyph; #else const TextGlyph* glyph; #endif if (!_font->get_glyph(char_code, glyph)) { lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } nassertr(glyph != NULL, 0); cursor += glyph->get_advance() * _font_size; } return cursor; } // Returns a list of character indexes where linebreaks should occur when wrapping. vector<int> LUIText::get_line_breaks() { vector<int> result; if(_wordwrap == TRUE) { // Unreference all current glyphs _glyphs.clear(); int char_idx = 0; int word_start = 0; float word_start_pos = 0.0f; float future_x_pos = 0.0f; float line_start = 0.0f; float ppu = _font_size; for (auto it = _children.begin(); it != _children.end(); ++it, ++char_idx) { LUIBaseElement* child = *it; LUISprite* sprite = DCAST(LUISprite, child); // A lui text should have only sprites contained, otherwise something went wrong nassertr(sprite != NULL, result); int char_code = (int)_text.at(char_idx); #if PANDA_MAJOR_VERSION > 1 || PANDA_MINOR_VERSION >= 10 CPT(TextGlyph) const_glyph; #else const TextGlyph* const_glyph; #endif // Character is a newline, so lets include this in our list. if (char_code == 10) { result.push_back(char_idx); word_start = char_idx; word_start_pos = future_x_pos; line_start = future_x_pos; continue; } if (!_font->get_glyph(char_code, const_glyph)) { sprite->set_texture((Texture*)NULL); lui_cat.error() << "Font does not support character with char code " << char_code << ", ignoring .. target = " << _debug_name << endl; continue; } CPT(DynamicTextGlyph) dynamic_glyph = DCAST(DynamicTextGlyph, const_glyph); // If this gets executed, a non-dynamic font got loaded. nassertr(dynamic_glyph != NULL, result); _glyphs.push_back(dynamic_glyph); // If a space, lets mark this as the start of the word. if (dynamic_glyph->get_page() == NULL) { word_start = char_idx; word_start_pos = future_x_pos + dynamic_glyph->get_advance() * ppu; } // If adding the glyph to the current position on this line will force it over // the width of the label, put a new line at the start of the word. if (((future_x_pos - line_start) + (dynamic_glyph->get_advance() * ppu)) > get_parent_width()) { result.push_back(word_start); // After the newline is added, we update the current lines start position. line_start = word_start_pos; } // Move the cursor along by the glyph's width. future_x_pos += dynamic_glyph->get_advance() * ppu; } } return result; } <|endoftext|>
<commit_before>/// @file peer_info.cpp /// /// @brief Implementation of peer_info.hpp /// /// @author Thomas Vanderbruggen <thomas@koheron.com> /// @date 30/11/2014 /// /// (c) Koheron 2014 #include "peer_info.hpp" namespace kserver { // -------------------------------- // PeerInfo // -------------------------------- void PeerInfo::__build(struct sockaddr* sock_) { if(sock_ == nullptr) { ip_family = 0; strcpy(ip_str,""); port = 0; } else { ip_family = sock_->sa_family; if(ip_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *)&sock_; port = ntohs(s->sin_port); inet_ntop(AF_INET, &s->sin_addr, ip_str, sizeof ip_str); } else { // AF_INET6 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sock_; port = ntohs(s->sin6_port); inet_ntop(AF_INET6, &s->sin6_addr, ip_str, sizeof ip_str); } } } PeerInfo::PeerInfo(int comm_fd) { if(comm_fd == -1) { __build(nullptr); } else { // Get client informations struct sockaddr_storage addr; socklen_t len = sizeof addr; struct sockaddr *sockaddr_ptr; if(getpeername(comm_fd, (struct sockaddr*)&addr, &len) < 0) { sockaddr_ptr = NULL; } else { sockaddr_ptr = (struct sockaddr*)&addr; } __build(sockaddr_ptr); } } PeerInfo::PeerInfo(const PeerInfo& peer_info) { ip_family = peer_info.ip_family; strcpy(ip_str, peer_info.ip_str); port = peer_info.port; } } // namespace kserver <commit_msg>Add memset<commit_after>/// @file peer_info.cpp /// /// @brief Implementation of peer_info.hpp /// /// @author Thomas Vanderbruggen <thomas@koheron.com> /// @date 30/11/2014 /// /// (c) Koheron 2014 #include "peer_info.hpp" namespace kserver { // -------------------------------- // PeerInfo // -------------------------------- void PeerInfo::__build(struct sockaddr* sock_) { if(sock_ == nullptr) { ip_family = 0; strcpy(ip_str,""); port = 0; } else { ip_family = sock_->sa_family; if(ip_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *)&sock_; port = ntohs(s->sin_port); inet_ntop(AF_INET, &s->sin_addr, ip_str, sizeof ip_str); } else { // AF_INET6 struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sock_; port = ntohs(s->sin6_port); inet_ntop(AF_INET6, &s->sin6_addr, ip_str, sizeof ip_str); } } } PeerInfo::PeerInfo(int comm_fd) { memset(ip_str, 0, INET6_ADDRSTRLEN); if(comm_fd == -1) { __build(nullptr); } else { // Get client informations struct sockaddr_storage addr; socklen_t len = sizeof addr; struct sockaddr *sockaddr_ptr; memset(sockaddr_ptr, 0, sizeof(struct sockaddr)); if(getpeername(comm_fd, (struct sockaddr*)&addr, &len) < 0) { sockaddr_ptr = NULL; } else { sockaddr_ptr = (struct sockaddr*)&addr; } __build(sockaddr_ptr); } } PeerInfo::PeerInfo(const PeerInfo& peer_info) { ip_family = peer_info.ip_family; strcpy(ip_str, peer_info.ip_str); port = peer_info.port; } } // namespace kserver <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include <stdio.h> #include "bin/dartutils.h" #include "bin/dfe.h" #include "bin/eventhandler.h" #include "bin/file.h" #include "bin/loader.h" #include "bin/platform.h" #include "bin/snapshot_utils.h" #include "bin/utils.h" #include "platform/assert.h" #include "vm/benchmark_test.h" #include "vm/dart.h" #include "vm/unit_test.h" extern "C" { extern const uint8_t kDartVmSnapshotData[]; extern const uint8_t kDartVmSnapshotInstructions[]; extern const uint8_t kDartCoreIsolateSnapshotData[]; extern const uint8_t kDartCoreIsolateSnapshotInstructions[]; } // TODO(iposva, asiva): This is a placeholder for the real unittest framework. namespace dart { namespace bin { DFE dfe; } // Defined in vm/os_thread_win.cc extern bool private_flag_windows_run_tls_destructors; // Snapshot pieces when we link in a snapshot. #if defined(DART_NO_SNAPSHOT) #error "run_vm_tests must be built with a snapshot" #else const uint8_t* bin::vm_snapshot_data = kDartVmSnapshotData; const uint8_t* bin::vm_snapshot_instructions = kDartVmSnapshotInstructions; const uint8_t* bin::core_isolate_snapshot_data = kDartCoreIsolateSnapshotData; const uint8_t* bin::core_isolate_snapshot_instructions = kDartCoreIsolateSnapshotInstructions; #endif // Only run tests that match the filter string. The default does not match any // tests. static const char* const kNone = "No Test or Benchmarks"; static const char* const kList = "List all Tests and Benchmarks"; static const char* const kAllBenchmarks = "All Benchmarks"; static const char* run_filter = kNone; static const char* kernel_snapshot = NULL; static int run_matches = 0; void TestCase::Run() { OS::Print("Running test: %s\n", name()); (*run_)(); OS::Print("Done: %s\n", name()); } void RawTestCase::Run() { OS::Print("Running test: %s\n", name()); (*run_)(); OS::Print("Done: %s\n", name()); } void TestCaseBase::RunTest() { if (strcmp(run_filter, this->name()) == 0) { this->Run(); run_matches++; } else if (run_filter == kList) { OS::Print("%s\n", this->name()); run_matches++; } } void Benchmark::RunBenchmark() { if ((run_filter == kAllBenchmarks) || (strcmp(run_filter, this->name()) == 0)) { this->Run(); OS::Print("%s(%s): %" Pd64 "\n", this->name(), this->score_kind(), this->score()); run_matches++; } else if (run_filter == kList) { OS::Print("%s\n", this->name()); run_matches++; } } static void PrintUsage() { OS::PrintErr( "Usage: one of the following\n" " run_vm_tests --list\n" " run_vm_tests [--dfe=<snapshot file name>] --benchmarks\n" " run_vm_tests [--dfe=<snapshot file name>] [vm-flags ...] <test name>\n" " run_vm_tests [--dfe=<snapshot file name>] [vm-flags ...] <benchmark " "name>\n"); } #define CHECK_RESULT(result) \ if (Dart_IsError(result)) { \ *error = strdup(Dart_GetError(result)); \ Dart_ExitScope(); \ Dart_ShutdownIsolate(); \ return NULL; \ } static Dart_Isolate CreateIsolateAndSetup(const char* script_uri, const char* main, const char* package_root, const char* packages_config, Dart_IsolateFlags* flags, void* data, char** error) { ASSERT(script_uri != NULL); const bool is_service_isolate = strcmp(script_uri, DART_VM_SERVICE_ISOLATE_NAME) == 0; if (is_service_isolate) { // We don't need service isolate for VM tests. return NULL; } const bool is_kernel_isolate = strcmp(script_uri, DART_KERNEL_ISOLATE_NAME) == 0; if (!is_kernel_isolate) { *error = strdup("Spawning of only Kernel isolate is supported in run_vm_tests."); return NULL; } if (kernel_snapshot == NULL) { *error = strdup("Kernel snapshot location has to be specified via --dfe option"); return NULL; } script_uri = kernel_snapshot; bin::AppSnapshot* app_snapshot = bin::Snapshot::TryReadAppSnapshot(script_uri); if (app_snapshot == NULL) { *error = strdup("Failed to read kernel service app snapshot"); return NULL; } const uint8_t* isolate_snapshot_data = bin::core_isolate_snapshot_data; const uint8_t* isolate_snapshot_instructions = bin::core_isolate_snapshot_instructions; const uint8_t* ignore_vm_snapshot_data; const uint8_t* ignore_vm_snapshot_instructions; app_snapshot->SetBuffers( &ignore_vm_snapshot_data, &ignore_vm_snapshot_instructions, &isolate_snapshot_data, &isolate_snapshot_instructions); bin::IsolateData* isolate_data = new bin::IsolateData( script_uri, package_root, packages_config, NULL /* app_snapshot */); Dart_Isolate isolate = Dart_CreateIsolate( DART_KERNEL_ISOLATE_NAME, main, isolate_snapshot_data, isolate_snapshot_instructions, flags, isolate_data, error); if (isolate == NULL) { *error = strdup("Failed to create isolate"); delete isolate_data; return NULL; } Dart_EnterScope(); bin::DartUtils::SetOriginalWorkingDirectory(); Dart_Handle result = bin::DartUtils::PrepareForScriptLoading( false /* is_service_isolate */, false /* trace_loading */); CHECK_RESULT(result); Dart_ExitScope(); Dart_ExitIsolate(); bool retval = Dart_IsolateMakeRunnable(isolate); if (!retval) { *error = strdup("Invalid isolate state - Unable to make it runnable"); Dart_EnterIsolate(isolate); Dart_ShutdownIsolate(); return NULL; } return isolate; } static int Main(int argc, const char** argv) { // Flags being passed to the Dart VM. int dart_argc = 0; const char** dart_argv = NULL; // Perform platform specific initialization. if (!dart::bin::Platform::Initialize()) { OS::PrintErr("Initialization failed\n"); return 1; } if (argc < 2) { // Bad parameter count. PrintUsage(); return 1; } if (argc == 2 && strcmp(argv[1], "--list") == 0) { run_filter = kList; // List all tests and benchmarks and exit without initializing the VM. TestCaseBase::RunAll(); Benchmark::RunAll(argv[0]); TestCaseBase::RunAllRaw(); fflush(stdout); return 0; } int arg_pos = 1; bool start_kernel_isolate = false; if (strstr(argv[arg_pos], "--dfe") == argv[arg_pos]) { const char* delim = strstr(argv[1], "="); if (delim == NULL || strlen(delim + 1) == 0) { OS::PrintErr("Invalid value for the option: %s\n", argv[1]); PrintUsage(); return 1; } kernel_snapshot = strdup(delim + 1); // VM needs '--use-dart-frontend' option, which we will insert in place // of '--dfe' option. argv[arg_pos] = strdup("--use-dart-frontend"); start_kernel_isolate = true; ++arg_pos; } if (arg_pos == argc - 1 && strcmp(argv[arg_pos], "--benchmarks") == 0) { // "--benchmarks" is the last argument. run_filter = kAllBenchmarks; } else { // Last argument is the test name, the rest are vm flags. run_filter = argv[argc - 1]; // Remove the first value (executable) from the arguments and // exclude the last argument which is the test name. dart_argc = argc - 2; dart_argv = &argv[1]; } bin::TimerUtils::InitOnce(); bin::EventHandler::Start(); bool set_vm_flags_success = Flags::ProcessCommandLineFlags(dart_argc, dart_argv); ASSERT(set_vm_flags_success); const char* err_msg = Dart::InitOnce( dart::bin::vm_snapshot_data, dart::bin::vm_snapshot_instructions, CreateIsolateAndSetup /* create */, NULL /* shutdown */, NULL /* cleanup */, NULL /* thread_exit */, dart::bin::DartUtils::OpenFile, dart::bin::DartUtils::ReadFile, dart::bin::DartUtils::WriteFile, dart::bin::DartUtils::CloseFile, NULL /* entropy_source */, NULL /* get_service_assets */, start_kernel_isolate); ASSERT(err_msg == NULL); // Apply the filter to all registered tests. TestCaseBase::RunAll(); // Apply the filter to all registered benchmarks. Benchmark::RunAll(argv[0]); err_msg = Dart::Cleanup(); ASSERT(err_msg == NULL); bin::EventHandler::Stop(); TestCaseBase::RunAllRaw(); // Print a warning message if no tests or benchmarks were matched. if (run_matches == 0) { OS::PrintErr("No tests matched: %s\n", run_filter); return 1; } if (DynamicAssertionHelper::failed()) { return 255; } return 0; } } // namespace dart int main(int argc, const char** argv) { dart::bin::Platform::Exit(dart::Main(argc, argv)); } <commit_msg>Initialize Thread also during startup for run_vm_tests<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include <stdio.h> #include "bin/dartutils.h" #include "bin/dfe.h" #include "bin/eventhandler.h" #include "bin/file.h" #include "bin/loader.h" #include "bin/platform.h" #include "bin/snapshot_utils.h" #include "bin/thread.h" #include "bin/utils.h" #include "platform/assert.h" #include "vm/benchmark_test.h" #include "vm/dart.h" #include "vm/unit_test.h" extern "C" { extern const uint8_t kDartVmSnapshotData[]; extern const uint8_t kDartVmSnapshotInstructions[]; extern const uint8_t kDartCoreIsolateSnapshotData[]; extern const uint8_t kDartCoreIsolateSnapshotInstructions[]; } // TODO(iposva, asiva): This is a placeholder for the real unittest framework. namespace dart { namespace bin { DFE dfe; } // Defined in vm/os_thread_win.cc extern bool private_flag_windows_run_tls_destructors; // Snapshot pieces when we link in a snapshot. #if defined(DART_NO_SNAPSHOT) #error "run_vm_tests must be built with a snapshot" #else const uint8_t* bin::vm_snapshot_data = kDartVmSnapshotData; const uint8_t* bin::vm_snapshot_instructions = kDartVmSnapshotInstructions; const uint8_t* bin::core_isolate_snapshot_data = kDartCoreIsolateSnapshotData; const uint8_t* bin::core_isolate_snapshot_instructions = kDartCoreIsolateSnapshotInstructions; #endif // Only run tests that match the filter string. The default does not match any // tests. static const char* const kNone = "No Test or Benchmarks"; static const char* const kList = "List all Tests and Benchmarks"; static const char* const kAllBenchmarks = "All Benchmarks"; static const char* run_filter = kNone; static const char* kernel_snapshot = NULL; static int run_matches = 0; void TestCase::Run() { OS::Print("Running test: %s\n", name()); (*run_)(); OS::Print("Done: %s\n", name()); } void RawTestCase::Run() { OS::Print("Running test: %s\n", name()); (*run_)(); OS::Print("Done: %s\n", name()); } void TestCaseBase::RunTest() { if (strcmp(run_filter, this->name()) == 0) { this->Run(); run_matches++; } else if (run_filter == kList) { OS::Print("%s\n", this->name()); run_matches++; } } void Benchmark::RunBenchmark() { if ((run_filter == kAllBenchmarks) || (strcmp(run_filter, this->name()) == 0)) { this->Run(); OS::Print("%s(%s): %" Pd64 "\n", this->name(), this->score_kind(), this->score()); run_matches++; } else if (run_filter == kList) { OS::Print("%s\n", this->name()); run_matches++; } } static void PrintUsage() { OS::PrintErr( "Usage: one of the following\n" " run_vm_tests --list\n" " run_vm_tests [--dfe=<snapshot file name>] --benchmarks\n" " run_vm_tests [--dfe=<snapshot file name>] [vm-flags ...] <test name>\n" " run_vm_tests [--dfe=<snapshot file name>] [vm-flags ...] <benchmark " "name>\n"); } #define CHECK_RESULT(result) \ if (Dart_IsError(result)) { \ *error = strdup(Dart_GetError(result)); \ Dart_ExitScope(); \ Dart_ShutdownIsolate(); \ return NULL; \ } static Dart_Isolate CreateIsolateAndSetup(const char* script_uri, const char* main, const char* package_root, const char* packages_config, Dart_IsolateFlags* flags, void* data, char** error) { ASSERT(script_uri != NULL); const bool is_service_isolate = strcmp(script_uri, DART_VM_SERVICE_ISOLATE_NAME) == 0; if (is_service_isolate) { // We don't need service isolate for VM tests. return NULL; } const bool is_kernel_isolate = strcmp(script_uri, DART_KERNEL_ISOLATE_NAME) == 0; if (!is_kernel_isolate) { *error = strdup("Spawning of only Kernel isolate is supported in run_vm_tests."); return NULL; } if (kernel_snapshot == NULL) { *error = strdup("Kernel snapshot location has to be specified via --dfe option"); return NULL; } script_uri = kernel_snapshot; bin::AppSnapshot* app_snapshot = bin::Snapshot::TryReadAppSnapshot(script_uri); if (app_snapshot == NULL) { *error = strdup("Failed to read kernel service app snapshot"); return NULL; } const uint8_t* isolate_snapshot_data = bin::core_isolate_snapshot_data; const uint8_t* isolate_snapshot_instructions = bin::core_isolate_snapshot_instructions; const uint8_t* ignore_vm_snapshot_data; const uint8_t* ignore_vm_snapshot_instructions; app_snapshot->SetBuffers( &ignore_vm_snapshot_data, &ignore_vm_snapshot_instructions, &isolate_snapshot_data, &isolate_snapshot_instructions); bin::IsolateData* isolate_data = new bin::IsolateData( script_uri, package_root, packages_config, NULL /* app_snapshot */); Dart_Isolate isolate = Dart_CreateIsolate( DART_KERNEL_ISOLATE_NAME, main, isolate_snapshot_data, isolate_snapshot_instructions, flags, isolate_data, error); if (isolate == NULL) { *error = strdup("Failed to create isolate"); delete isolate_data; return NULL; } Dart_EnterScope(); bin::DartUtils::SetOriginalWorkingDirectory(); Dart_Handle result = bin::DartUtils::PrepareForScriptLoading( false /* is_service_isolate */, false /* trace_loading */); CHECK_RESULT(result); Dart_ExitScope(); Dart_ExitIsolate(); bool retval = Dart_IsolateMakeRunnable(isolate); if (!retval) { *error = strdup("Invalid isolate state - Unable to make it runnable"); Dart_EnterIsolate(isolate); Dart_ShutdownIsolate(); return NULL; } return isolate; } static int Main(int argc, const char** argv) { // Flags being passed to the Dart VM. int dart_argc = 0; const char** dart_argv = NULL; // Perform platform specific initialization. if (!dart::bin::Platform::Initialize()) { OS::PrintErr("Initialization failed\n"); return 1; } if (argc < 2) { // Bad parameter count. PrintUsage(); return 1; } if (argc == 2 && strcmp(argv[1], "--list") == 0) { run_filter = kList; // List all tests and benchmarks and exit without initializing the VM. TestCaseBase::RunAll(); Benchmark::RunAll(argv[0]); TestCaseBase::RunAllRaw(); fflush(stdout); return 0; } int arg_pos = 1; bool start_kernel_isolate = false; if (strstr(argv[arg_pos], "--dfe") == argv[arg_pos]) { const char* delim = strstr(argv[1], "="); if (delim == NULL || strlen(delim + 1) == 0) { OS::PrintErr("Invalid value for the option: %s\n", argv[1]); PrintUsage(); return 1; } kernel_snapshot = strdup(delim + 1); // VM needs '--use-dart-frontend' option, which we will insert in place // of '--dfe' option. argv[arg_pos] = strdup("--use-dart-frontend"); start_kernel_isolate = true; ++arg_pos; } if (arg_pos == argc - 1 && strcmp(argv[arg_pos], "--benchmarks") == 0) { // "--benchmarks" is the last argument. run_filter = kAllBenchmarks; } else { // Last argument is the test name, the rest are vm flags. run_filter = argv[argc - 1]; // Remove the first value (executable) from the arguments and // exclude the last argument which is the test name. dart_argc = argc - 2; dart_argv = &argv[1]; } bin::Thread::InitOnce(); bin::TimerUtils::InitOnce(); bin::EventHandler::Start(); bool set_vm_flags_success = Flags::ProcessCommandLineFlags(dart_argc, dart_argv); ASSERT(set_vm_flags_success); const char* err_msg = Dart::InitOnce( dart::bin::vm_snapshot_data, dart::bin::vm_snapshot_instructions, CreateIsolateAndSetup /* create */, NULL /* shutdown */, NULL /* cleanup */, NULL /* thread_exit */, dart::bin::DartUtils::OpenFile, dart::bin::DartUtils::ReadFile, dart::bin::DartUtils::WriteFile, dart::bin::DartUtils::CloseFile, NULL /* entropy_source */, NULL /* get_service_assets */, start_kernel_isolate); ASSERT(err_msg == NULL); // Apply the filter to all registered tests. TestCaseBase::RunAll(); // Apply the filter to all registered benchmarks. Benchmark::RunAll(argv[0]); err_msg = Dart::Cleanup(); ASSERT(err_msg == NULL); bin::EventHandler::Stop(); TestCaseBase::RunAllRaw(); // Print a warning message if no tests or benchmarks were matched. if (run_matches == 0) { OS::PrintErr("No tests matched: %s\n", run_filter); return 1; } if (DynamicAssertionHelper::failed()) { return 255; } return 0; } } // namespace dart int main(int argc, const char** argv) { dart::bin::Platform::Exit(dart::Main(argc, argv)); } <|endoftext|>
<commit_before>// --------------------------------------------------------------------- // // Copyright (C) 2000 - 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/lac/vector.h> #include <deal.II/lac/la_vector.h> #include <deal.II/lac/la_parallel_vector.h> #include <deal.II/lac/la_parallel_block_vector.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/block_sparse_matrix.h> #include <deal.II/multigrid/mg_transfer.h> #include <deal.II/multigrid/mg_transfer_block.h> #include <deal.II/multigrid/mg_transfer_component.h> #include <deal.II/multigrid/mg_smoother.h> #include <deal.II/multigrid/mg_transfer_block.templates.h> #include <deal.II/multigrid/mg_transfer_component.templates.h> #include <deal.II/multigrid/multigrid.templates.h> DEAL_II_NAMESPACE_OPEN MGTransferBlockBase::MGTransferBlockBase () {} MGTransferBlockBase::MGTransferBlockBase ( const MGConstrainedDoFs &mg_c) : mg_constrained_dofs(&mg_c) {} MGTransferBlockBase::MGTransferBlockBase ( const ConstraintMatrix &/*c*/, const MGConstrainedDoFs &mg_c) : mg_constrained_dofs(&mg_c) {} template <typename number> MGTransferBlock<number>::MGTransferBlock () : memory(0, typeid(*this).name()) {} template <typename number> MGTransferBlock<number>::~MGTransferBlock () { if (memory != 0) memory = 0; } template <typename number> void MGTransferBlock<number>::initialize (const std::vector<number> &f, VectorMemory<Vector<number> > &mem) { factors = f; memory = &mem; } template <typename number> void MGTransferBlock<number>::prolongate ( const unsigned int to_level, BlockVector<number> &dst, const BlockVector<number> &src) const { Assert ((to_level >= 1) && (to_level<=prolongation_matrices.size()), ExcIndexRange (to_level, 1, prolongation_matrices.size()+1)); Assert (src.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(src.n_blocks(), this->n_mg_blocks)); Assert (dst.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(dst.n_blocks(), this->n_mg_blocks)); // Multiplicate with prolongation // matrix, but only those blocks // selected. for (unsigned int b=0; b<this->mg_block.size(); ++b) { if (this->selected[b]) prolongation_matrices[to_level-1]->block(b,b).vmult ( dst.block(this->mg_block[b]), src.block(this->mg_block[b])); } } template <typename number> void MGTransferBlock<number>::restrict_and_add ( const unsigned int from_level, BlockVector<number> &dst, const BlockVector<number> &src) const { Assert ((from_level >= 1) && (from_level<=prolongation_matrices.size()), ExcIndexRange (from_level, 1, prolongation_matrices.size()+1)); Assert (src.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(src.n_blocks(), this->n_mg_blocks)); Assert (dst.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(dst.n_blocks(), this->n_mg_blocks)); for (unsigned int b=0; b<this->mg_block.size(); ++b) { if (this->selected[b]) { if (factors.size() != 0) { Assert (memory != 0, ExcNotInitialized()); Vector<number> *aux = memory->alloc(); aux->reinit(dst.block(this->mg_block[b])); prolongation_matrices[from_level-1]->block(b,b).Tvmult ( *aux, src.block(this->mg_block[b])); dst.block(this->mg_block[b]).add(factors[b], *aux); memory->free(aux); } else { prolongation_matrices[from_level-1]->block(b,b).Tvmult_add ( dst.block(this->mg_block[b]), src.block(this->mg_block[b])); } } } } std::size_t MGTransferComponentBase::memory_consumption () const { std::size_t result = sizeof(*this); result += MemoryConsumption::memory_consumption(component_mask) - sizeof(ComponentMask); result += MemoryConsumption::memory_consumption(target_component) - sizeof(mg_target_component); result += MemoryConsumption::memory_consumption(sizes) - sizeof(sizes); result += MemoryConsumption::memory_consumption(component_start) - sizeof(component_start); result += MemoryConsumption::memory_consumption(mg_component_start) - sizeof(mg_component_start); result += MemoryConsumption::memory_consumption(prolongation_sparsities) - sizeof(prolongation_sparsities); result += MemoryConsumption::memory_consumption(prolongation_matrices) - sizeof(prolongation_matrices); //TODO:[GK] Add this. // result += MemoryConsumption::memory_consumption(copy_to_and_from_indices) // - sizeof(copy_to_and_from_indices); return result; } //TODO:[GK] Add all those little vectors. std::size_t MGTransferBlockBase::memory_consumption () const { std::size_t result = sizeof(*this); result += sizeof(unsigned int) * sizes.size(); result += MemoryConsumption::memory_consumption(selected) - sizeof(selected); result += MemoryConsumption::memory_consumption(mg_block) - sizeof(mg_block); result += MemoryConsumption::memory_consumption(block_start) - sizeof(block_start); result += MemoryConsumption::memory_consumption(mg_block_start) - sizeof(mg_block_start); result += MemoryConsumption::memory_consumption(prolongation_sparsities) - sizeof(prolongation_sparsities); result += MemoryConsumption::memory_consumption(prolongation_matrices) - sizeof(prolongation_matrices); //TODO:[GK] Add this. // result += MemoryConsumption::memory_consumption(copy_indices) // - sizeof(copy_indices); return result; } //----------------------------------------------------------------------// template<typename number> MGTransferSelect<number>::MGTransferSelect () {} template<typename number> MGTransferSelect<number>::MGTransferSelect (const ConstraintMatrix &c) : constraints(&c) {} template <typename number> MGTransferSelect<number>::~MGTransferSelect () {} template <typename number> void MGTransferSelect<number>::prolongate ( const unsigned int to_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((to_level >= 1) && (to_level<=prolongation_matrices.size()), ExcIndexRange (to_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[to_level-1]->block(mg_target_component[mg_selected_component], mg_target_component[mg_selected_component]) .vmult (dst, src); } template <typename number> void MGTransferSelect<number>::restrict_and_add ( const unsigned int from_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((from_level >= 1) && (from_level<=prolongation_matrices.size()), ExcIndexRange (from_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[from_level-1]->block(mg_target_component[mg_selected_component], mg_target_component[mg_selected_component]) .Tvmult_add (dst, src); } //----------------------------------------------------------------------// template <typename number> MGTransferBlockSelect<number>::MGTransferBlockSelect () {} template <typename number> MGTransferBlockSelect<number>::MGTransferBlockSelect ( const MGConstrainedDoFs &mg_c) : MGTransferBlockBase(mg_c) {} template <typename number> MGTransferBlockSelect<number>::MGTransferBlockSelect ( const ConstraintMatrix &/*c*/, const MGConstrainedDoFs &mg_c) : MGTransferBlockBase(mg_c) {} template <typename number> MGTransferBlockSelect<number>::~MGTransferBlockSelect () {} template <typename number> void MGTransferBlockSelect<number>::prolongate ( const unsigned int to_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((to_level >= 1) && (to_level<=prolongation_matrices.size()), ExcIndexRange (to_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[to_level-1]->block(selected_block, selected_block) .vmult (dst, src); } template <typename number> void MGTransferBlockSelect<number>::restrict_and_add ( const unsigned int from_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((from_level >= 1) && (from_level<=prolongation_matrices.size()), ExcIndexRange (from_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[from_level-1]->block(selected_block, selected_block) .Tvmult_add (dst, src); } // Explicit instantiations #include "multigrid.inst" template class MGTransferBlock<float>; template class MGTransferBlock<double>; template class MGTransferSelect<float>; template class MGTransferSelect<double>; template class MGTransferBlockSelect<float>; template class MGTransferBlockSelect<double>; DEAL_II_NAMESPACE_CLOSE <commit_msg>Initialize member variables.<commit_after>// --------------------------------------------------------------------- // // Copyright (C) 2000 - 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/lac/vector.h> #include <deal.II/lac/la_vector.h> #include <deal.II/lac/la_parallel_vector.h> #include <deal.II/lac/la_parallel_block_vector.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/block_sparse_matrix.h> #include <deal.II/multigrid/mg_transfer.h> #include <deal.II/multigrid/mg_transfer_block.h> #include <deal.II/multigrid/mg_transfer_component.h> #include <deal.II/multigrid/mg_smoother.h> #include <deal.II/multigrid/mg_transfer_block.templates.h> #include <deal.II/multigrid/mg_transfer_component.templates.h> #include <deal.II/multigrid/multigrid.templates.h> DEAL_II_NAMESPACE_OPEN MGTransferBlockBase::MGTransferBlockBase () : n_mg_blocks (0) {} MGTransferBlockBase::MGTransferBlockBase (const MGConstrainedDoFs &mg_c) : n_mg_blocks (0), mg_constrained_dofs(&mg_c) {} MGTransferBlockBase::MGTransferBlockBase (const ConstraintMatrix &/*c*/, const MGConstrainedDoFs &mg_c) : n_mg_blocks (0), mg_constrained_dofs(&mg_c) {} template <typename number> MGTransferBlock<number>::MGTransferBlock () : memory(0, typeid(*this).name()) {} template <typename number> MGTransferBlock<number>::~MGTransferBlock () { if (memory != 0) memory = 0; } template <typename number> void MGTransferBlock<number>::initialize (const std::vector<number> &f, VectorMemory<Vector<number> > &mem) { factors = f; memory = &mem; } template <typename number> void MGTransferBlock<number>::prolongate ( const unsigned int to_level, BlockVector<number> &dst, const BlockVector<number> &src) const { Assert ((to_level >= 1) && (to_level<=prolongation_matrices.size()), ExcIndexRange (to_level, 1, prolongation_matrices.size()+1)); Assert (src.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(src.n_blocks(), this->n_mg_blocks)); Assert (dst.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(dst.n_blocks(), this->n_mg_blocks)); // Multiplicate with prolongation // matrix, but only those blocks // selected. for (unsigned int b=0; b<this->mg_block.size(); ++b) { if (this->selected[b]) prolongation_matrices[to_level-1]->block(b,b).vmult ( dst.block(this->mg_block[b]), src.block(this->mg_block[b])); } } template <typename number> void MGTransferBlock<number>::restrict_and_add ( const unsigned int from_level, BlockVector<number> &dst, const BlockVector<number> &src) const { Assert ((from_level >= 1) && (from_level<=prolongation_matrices.size()), ExcIndexRange (from_level, 1, prolongation_matrices.size()+1)); Assert (src.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(src.n_blocks(), this->n_mg_blocks)); Assert (dst.n_blocks() == this->n_mg_blocks, ExcDimensionMismatch(dst.n_blocks(), this->n_mg_blocks)); for (unsigned int b=0; b<this->mg_block.size(); ++b) { if (this->selected[b]) { if (factors.size() != 0) { Assert (memory != 0, ExcNotInitialized()); Vector<number> *aux = memory->alloc(); aux->reinit(dst.block(this->mg_block[b])); prolongation_matrices[from_level-1]->block(b,b).Tvmult ( *aux, src.block(this->mg_block[b])); dst.block(this->mg_block[b]).add(factors[b], *aux); memory->free(aux); } else { prolongation_matrices[from_level-1]->block(b,b).Tvmult_add ( dst.block(this->mg_block[b]), src.block(this->mg_block[b])); } } } } std::size_t MGTransferComponentBase::memory_consumption () const { std::size_t result = sizeof(*this); result += MemoryConsumption::memory_consumption(component_mask) - sizeof(ComponentMask); result += MemoryConsumption::memory_consumption(target_component) - sizeof(mg_target_component); result += MemoryConsumption::memory_consumption(sizes) - sizeof(sizes); result += MemoryConsumption::memory_consumption(component_start) - sizeof(component_start); result += MemoryConsumption::memory_consumption(mg_component_start) - sizeof(mg_component_start); result += MemoryConsumption::memory_consumption(prolongation_sparsities) - sizeof(prolongation_sparsities); result += MemoryConsumption::memory_consumption(prolongation_matrices) - sizeof(prolongation_matrices); //TODO:[GK] Add this. // result += MemoryConsumption::memory_consumption(copy_to_and_from_indices) // - sizeof(copy_to_and_from_indices); return result; } //TODO:[GK] Add all those little vectors. std::size_t MGTransferBlockBase::memory_consumption () const { std::size_t result = sizeof(*this); result += sizeof(unsigned int) * sizes.size(); result += MemoryConsumption::memory_consumption(selected) - sizeof(selected); result += MemoryConsumption::memory_consumption(mg_block) - sizeof(mg_block); result += MemoryConsumption::memory_consumption(block_start) - sizeof(block_start); result += MemoryConsumption::memory_consumption(mg_block_start) - sizeof(mg_block_start); result += MemoryConsumption::memory_consumption(prolongation_sparsities) - sizeof(prolongation_sparsities); result += MemoryConsumption::memory_consumption(prolongation_matrices) - sizeof(prolongation_matrices); //TODO:[GK] Add this. // result += MemoryConsumption::memory_consumption(copy_indices) // - sizeof(copy_indices); return result; } //----------------------------------------------------------------------// template<typename number> MGTransferSelect<number>::MGTransferSelect () : selected_component (0), mg_selected_component (0) {} template<typename number> MGTransferSelect<number>::MGTransferSelect (const ConstraintMatrix &c) : selected_component (0), mg_selected_component (0), constraints(&c) {} template <typename number> MGTransferSelect<number>::~MGTransferSelect () {} template <typename number> void MGTransferSelect<number>::prolongate ( const unsigned int to_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((to_level >= 1) && (to_level<=prolongation_matrices.size()), ExcIndexRange (to_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[to_level-1]->block(mg_target_component[mg_selected_component], mg_target_component[mg_selected_component]) .vmult (dst, src); } template <typename number> void MGTransferSelect<number>::restrict_and_add ( const unsigned int from_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((from_level >= 1) && (from_level<=prolongation_matrices.size()), ExcIndexRange (from_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[from_level-1]->block(mg_target_component[mg_selected_component], mg_target_component[mg_selected_component]) .Tvmult_add (dst, src); } //----------------------------------------------------------------------// template <typename number> MGTransferBlockSelect<number>::MGTransferBlockSelect () : selected_block (0) {} template <typename number> MGTransferBlockSelect<number>::MGTransferBlockSelect (const MGConstrainedDoFs &mg_c) : MGTransferBlockBase(mg_c), selected_block (0) {} template <typename number> MGTransferBlockSelect<number>::MGTransferBlockSelect (const ConstraintMatrix &/*c*/, const MGConstrainedDoFs &mg_c) : MGTransferBlockBase(mg_c), selected_block (0) {} template <typename number> MGTransferBlockSelect<number>::~MGTransferBlockSelect () {} template <typename number> void MGTransferBlockSelect<number>::prolongate (const unsigned int to_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((to_level >= 1) && (to_level<=prolongation_matrices.size()), ExcIndexRange (to_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[to_level-1]->block(selected_block, selected_block) .vmult (dst, src); } template <typename number> void MGTransferBlockSelect<number>::restrict_and_add (const unsigned int from_level, Vector<number> &dst, const Vector<number> &src) const { Assert ((from_level >= 1) && (from_level<=prolongation_matrices.size()), ExcIndexRange (from_level, 1, prolongation_matrices.size()+1)); prolongation_matrices[from_level-1]->block(selected_block, selected_block) .Tvmult_add (dst, src); } // Explicit instantiations #include "multigrid.inst" template class MGTransferBlock<float>; template class MGTransferBlock<double>; template class MGTransferSelect<float>; template class MGTransferSelect<double>; template class MGTransferBlockSelect<float>; template class MGTransferBlockSelect<double>; DEAL_II_NAMESPACE_CLOSE <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: View.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBACCESS_VIEW_HXX #define DBACCESS_VIEW_HXX #include "connectivity/sdbcx/VView.hxx" /** === begin UNO includes === **/ #include <com/sun/star/sdbcx/XAlterView.hpp> #include <com/sun/star/sdb/tools/XViewAlteration.hpp> #include <com/sun/star/sdb/tools/XViewSupport.hpp> /** === end UNO includes === **/ #include <comphelper/uno3.hxx> #include <cppuhelper/implbase1.hxx> //........................................................................ namespace dbaccess { //........................................................................ //==================================================================== //= View //==================================================================== typedef ::connectivity::sdbcx::OView View_Base; typedef ::cppu::ImplHelper1< ::com::sun::star::sdbcx::XAlterView > View_IBASE; class View :public View_Base ,public View_IBASE { public: View( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, sal_Bool _bCaseSensitive, const ::rtl::OUString& _rCatalogName, const ::rtl::OUString& _rSchemaName, const ::rtl::OUString& _rName ); // UNO DECLARE_XINTERFACE() DECLARE_XTYPEPROVIDER() // XAlterView virtual void SAL_CALL alterCommand( const ::rtl::OUString& NewCommand ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); protected: virtual ~View(); protected: // OPropertyContainer virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const; private: ::com::sun::star::uno::Reference< ::com::sun::star::sdb::tools::XViewSupport> m_xViewSupport; sal_Int32 m_nCommandHandle; private: using View_Base::getFastPropertyValue; }; //........................................................................ } // namespace dbaccess //........................................................................ #endif // DBACCESS_VIEW_HXX <commit_msg>dba33e: remove unused header<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: View.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBACCESS_VIEW_HXX #define DBACCESS_VIEW_HXX #include "connectivity/sdbcx/VView.hxx" /** === begin UNO includes === **/ #include <com/sun/star/sdbcx/XAlterView.hpp> #include <com/sun/star/sdb/tools/XViewSupport.hpp> /** === end UNO includes === **/ #include <comphelper/uno3.hxx> #include <cppuhelper/implbase1.hxx> //........................................................................ namespace dbaccess { //........................................................................ //==================================================================== //= View //==================================================================== typedef ::connectivity::sdbcx::OView View_Base; typedef ::cppu::ImplHelper1< ::com::sun::star::sdbcx::XAlterView > View_IBASE; class View :public View_Base ,public View_IBASE { public: View( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, sal_Bool _bCaseSensitive, const ::rtl::OUString& _rCatalogName, const ::rtl::OUString& _rSchemaName, const ::rtl::OUString& _rName ); // UNO DECLARE_XINTERFACE() DECLARE_XTYPEPROVIDER() // XAlterView virtual void SAL_CALL alterCommand( const ::rtl::OUString& NewCommand ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); protected: virtual ~View(); protected: // OPropertyContainer virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& _rValue, sal_Int32 _nHandle ) const; private: ::com::sun::star::uno::Reference< ::com::sun::star::sdb::tools::XViewSupport> m_xViewSupport; sal_Int32 m_nCommandHandle; private: using View_Base::getFastPropertyValue; }; //........................................................................ } // namespace dbaccess //........................................................................ #endif // DBACCESS_VIEW_HXX <|endoftext|>
<commit_before>#include "Scene.h" Scene::Scene(void) { view_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f)); memset(&KeyStates, 0, sizeof(KeyStates)); // Init Test Objects test_zombie = new Zombie(this, 0.0f, 0.0f); player = new Player(this, 20.0f, 20.0f); // Init Objects AddObject(test_zombie); AddObject(new Obstacle(this, 15.0, 15.0, 7.00)); AddObject(new Obstacle(this, -12.0, -17.0, 9.00)); AddObject(new Obstacle(this, 12.0, -6.0, 5.00)); AddObject(new Obstacle(this, -16.0, 15.0, 6.00)); } Scene::~Scene(void) { } void Scene::Update(double delta_time) { for (unsigned int i = 0; i < objects.size(); i++) { objects[i]->Update(delta_time); } player->Update(delta_time); } void Scene::Draw(void) { for(unsigned int i = 0; i < objects.size(); i++) { objects[i]->Draw(); } player->Draw(); } void Scene::PlayerRotate(glm::vec2 heading) { player->Rotate(heading); } void Scene::PlayerShoot(glm::vec2 aim) { player->Shoot(aim); } void Scene::Key(unsigned char key) { if (KeyStates['r']) test_zombie->RandomPoint(); } void Scene::KeyState(unsigned char key, bool tf) { KeyStates[key] = tf; } void Scene::AddObject(GameEntity *entity) { objects.push_back(entity); } void Scene::RemoveObject(GameEntity *entity) { } ostream& operator<<(ostream &o, const Scene &gw) { o << "---------------- SCENE ---------------" << "\n"; o << "--------------------------------------" << endl; return o; } <commit_msg>player movement<commit_after>#include "Scene.h" Scene::Scene(void) { view_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f)); memset(&KeyStates, 0, sizeof(KeyStates)); // Init Test Objects test_zombie = new Zombie(this, 0.0f, 0.0f); player = new Player(this, 20.0f, 20.0f); // Init Objects AddObject(test_zombie); AddObject(new Obstacle(this, 15.0, 15.0, 7.00)); AddObject(new Obstacle(this, -12.0, -17.0, 9.00)); AddObject(new Obstacle(this, 12.0, -6.0, 5.00)); AddObject(new Obstacle(this, -16.0, 15.0, 6.00)); } Scene::~Scene(void) { } void Scene::Update(double delta_time) { for (unsigned int i = 0; i < objects.size(); i++) { objects[i]->Update(delta_time); } if (KeyStates['w']) player->Move(glm::vec2(0, 0.3), delta_time); if (KeyStates['s']) player->Move(glm::vec2(0, -0.3), delta_time); if (KeyStates['a']) player->Move(glm::vec2(-0.3, 0), delta_time); if (KeyStates['d']) player->Move(glm::vec2(0.3, 0), delta_time); player->Update(delta_time); } void Scene::Draw(void) { for(unsigned int i = 0; i < objects.size(); i++) { objects[i]->Draw(); } player->Draw(); } void Scene::PlayerRotate(glm::vec2 heading) { player->Rotate(heading); } void Scene::PlayerShoot(glm::vec2 aim) { player->Shoot(aim); } void Scene::Key(unsigned char key) { if (KeyStates['r']) test_zombie->RandomPoint(); } void Scene::KeyState(unsigned char key, bool tf) { KeyStates[key] = tf; } void Scene::AddObject(GameEntity *entity) { objects.push_back(entity); } void Scene::RemoveObject(GameEntity *entity) { } ostream& operator<<(ostream &o, const Scene &gw) { o << "---------------- SCENE ---------------" << "\n"; o << "--------------------------------------" << endl; return o; } <|endoftext|>