text
stringlengths
54
60.6k
<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/ui/webui/ntp/ntp_login_handler.h" #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_notifier.h" #include "base/prefs/pref_service.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/managed_mode/managed_mode.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "chrome/browser/web_resource/promo_resource_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/escape.h" #include "skia/ext/image_operations.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/webui/web_ui_util.h" using content::OpenURLParams; using content::Referrer; namespace { SkBitmap GetGAIAPictureForNTP(const gfx::Image& image) { // This value must match the width and height value of login-status-icon // in new_tab.css. const int kLength = 27; SkBitmap bmp = skia::ImageOperations::Resize(*image.ToSkBitmap(), skia::ImageOperations::RESIZE_BEST, kLength, kLength); gfx::Canvas canvas(gfx::Size(kLength, kLength), ui::SCALE_FACTOR_100P, false); canvas.DrawImageInt(gfx::ImageSkia::CreateFrom1xBitmap(bmp), 0, 0); // Draw a gray border on the inside of the icon. SkColor color = SkColorSetARGB(83, 0, 0, 0); canvas.DrawRect(gfx::Rect(0, 0, kLength - 1, kLength - 1), color); return canvas.ExtractImageRep().sk_bitmap(); } // Puts the |content| into a span with the given CSS class. string16 CreateSpanWithClass(const string16& content, const std::string& css_class) { return ASCIIToUTF16("<span class='" + css_class + "'>") + net::EscapeForHTML(content) + ASCIIToUTF16("</span>"); } } // namespace NTPLoginHandler::NTPLoginHandler() { } NTPLoginHandler::~NTPLoginHandler() { } void NTPLoginHandler::RegisterMessages() { PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); username_pref_.Init(prefs::kGoogleServicesUsername, pref_service, base::Bind(&NTPLoginHandler::UpdateLogin, base::Unretained(this))); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED, content::NotificationService::AllSources()); web_ui()->RegisterMessageCallback("initializeSyncLogin", base::Bind(&NTPLoginHandler::HandleInitializeSyncLogin, base::Unretained(this))); web_ui()->RegisterMessageCallback("showSyncLoginUI", base::Bind(&NTPLoginHandler::HandleShowSyncLoginUI, base::Unretained(this))); web_ui()->RegisterMessageCallback("loginMessageSeen", base::Bind(&NTPLoginHandler::HandleLoginMessageSeen, base::Unretained(this))); web_ui()->RegisterMessageCallback("showAdvancedLoginUI", base::Bind(&NTPLoginHandler::HandleShowAdvancedLoginUI, base::Unretained(this))); } void NTPLoginHandler::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED) { UpdateLogin(); } else { NOTREACHED(); } } void NTPLoginHandler::HandleInitializeSyncLogin(const ListValue* args) { UpdateLogin(); } void NTPLoginHandler::HandleShowSyncLoginUI(const ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetPrefs()->GetString( prefs::kGoogleServicesUsername); content::WebContents* web_contents = web_ui()->GetWebContents(); Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (!browser) return; if (username.empty()) { #if !defined(OS_ANDROID) // The user isn't signed in, show the sync promo. if (SyncPromoUI::ShouldShowSyncPromo(profile)) { chrome::ShowBrowserSignin(browser, SyncPromoUI::SOURCE_NTP_LINK); RecordInHistogram(NTP_SIGN_IN_PROMO_CLICKED); } #endif } else if (args->GetSize() == 4 && chrome::IsCommandEnabled(browser, IDC_SHOW_AVATAR_MENU)) { // The user is signed in, show the profiles menu. double x = 0; double y = 0; double width = 0; double height = 0; bool success = args->GetDouble(0, &x); DCHECK(success); success = args->GetDouble(1, &y); DCHECK(success); success = args->GetDouble(2, &width); DCHECK(success); success = args->GetDouble(3, &height); DCHECK(success); double zoom = WebKit::WebView::zoomLevelToZoomFactor(web_contents->GetZoomLevel()); gfx::Rect rect(x * zoom, y * zoom, width * zoom, height * zoom); browser->window()->ShowAvatarBubble(web_ui()->GetWebContents(), rect); ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::NTP_AVATAR_BUBBLE); } } void NTPLoginHandler::RecordInHistogram(int type) { // Invalid type to record. if (type < NTP_SIGN_IN_PROMO_VIEWED || type > NTP_SIGN_IN_PROMO_CLICKED) { NOTREACHED(); } else { UMA_HISTOGRAM_ENUMERATION("SyncPromo.NTPPromo", type, NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY); } } void NTPLoginHandler::HandleLoginMessageSeen(const ListValue* args) { Profile::FromWebUI(web_ui())->GetPrefs()->SetBoolean( prefs::kSyncPromoShowNTPBubble, false); NewTabUI* ntp_ui = NewTabUI::FromWebUIController(web_ui()->GetController()); ntp_ui->set_showing_sync_bubble(true); } void NTPLoginHandler::HandleShowAdvancedLoginUI(const ListValue* args) { Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); if (browser) chrome::ShowBrowserSignin(browser, SyncPromoUI::SOURCE_NTP_LINK); } void NTPLoginHandler::UpdateLogin() { Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetPrefs()->GetString( prefs::kGoogleServicesUsername); string16 header, sub_header; std::string icon_url; if (!username.empty()) { ProfileInfoCache& cache = g_browser_process->profile_manager()->GetProfileInfoCache(); size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath()); if (profile_index != std::string::npos) { // Only show the profile picture and full name for the single profile // case. In the multi-profile case the profile picture is visible in the // title bar and the full name can be ambiguous. if (cache.GetNumberOfProfiles() == 1) { string16 name = cache.GetGAIANameOfProfileAtIndex(profile_index); if (!name.empty()) header = CreateSpanWithClass(name, "profile-name"); const gfx::Image* image = cache.GetGAIAPictureOfProfileAtIndex(profile_index); if (image) icon_url = webui::GetBitmapDataUrl(GetGAIAPictureForNTP(*image)); } if (header.empty()) header = CreateSpanWithClass(UTF8ToUTF16(username), "profile-name"); } } else { #if !defined(OS_ANDROID) // Android uses a custom sync promo if (SyncPromoUI::ShouldShowSyncPromo(profile)) { string16 signed_in_link = l10n_util::GetStringUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_LINK); signed_in_link = CreateSpanWithClass(signed_in_link, "link-span"); header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_HEADER, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); sub_header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_SUB_HEADER, signed_in_link); // Record that the user was shown the promo. RecordInHistogram(NTP_SIGN_IN_PROMO_VIEWED); } #endif } StringValue header_value(header); StringValue sub_header_value(sub_header); StringValue icon_url_value(icon_url); base::FundamentalValue is_user_signed_in(!username.empty()); web_ui()->CallJavascriptFunction("ntp.updateLogin", header_value, sub_header_value, icon_url_value, is_user_signed_in); } // static bool NTPLoginHandler::ShouldShow(Profile* profile) { #if defined(OS_CHROMEOS) // For now we don't care about showing sync status on Chrome OS. The promo // UI and the avatar menu don't exist on that platform. return false; #else return !profile->IsOffTheRecord(); #endif } // static void NTPLoginHandler::GetLocalizedValues(Profile* profile, DictionaryValue* values) { PrefService* prefs = profile->GetPrefs(); std::string error_message = prefs->GetString(prefs::kSyncPromoErrorMessage); bool hide_sync = !prefs->GetBoolean(prefs::kSyncPromoShowNTPBubble); string16 message = hide_sync ? string16() : !error_message.empty() ? UTF8ToUTF16(error_message) : l10n_util::GetStringFUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_MESSAGE, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); values->SetString("login_status_message", message); values->SetString("login_status_url", hide_sync ? std::string() : chrome::kSyncLearnMoreURL); values->SetString("login_status_advanced", hide_sync || !error_message.empty() ? string16() : l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_ADVANCED)); values->SetString("login_status_dismiss", hide_sync ? string16() : l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_OK)); } <commit_msg>Prevent a crash when NewTabUI isn't available.<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/ui/webui/ntp/ntp_login_handler.h" #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_notifier.h" #include "base/prefs/pref_service.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/managed_mode/managed_mode.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/ntp/new_tab_ui.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "chrome/browser/web_resource/promo_resource_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/escape.h" #include "skia/ext/image_operations.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/webui/web_ui_util.h" using content::OpenURLParams; using content::Referrer; namespace { SkBitmap GetGAIAPictureForNTP(const gfx::Image& image) { // This value must match the width and height value of login-status-icon // in new_tab.css. const int kLength = 27; SkBitmap bmp = skia::ImageOperations::Resize(*image.ToSkBitmap(), skia::ImageOperations::RESIZE_BEST, kLength, kLength); gfx::Canvas canvas(gfx::Size(kLength, kLength), ui::SCALE_FACTOR_100P, false); canvas.DrawImageInt(gfx::ImageSkia::CreateFrom1xBitmap(bmp), 0, 0); // Draw a gray border on the inside of the icon. SkColor color = SkColorSetARGB(83, 0, 0, 0); canvas.DrawRect(gfx::Rect(0, 0, kLength - 1, kLength - 1), color); return canvas.ExtractImageRep().sk_bitmap(); } // Puts the |content| into a span with the given CSS class. string16 CreateSpanWithClass(const string16& content, const std::string& css_class) { return ASCIIToUTF16("<span class='" + css_class + "'>") + net::EscapeForHTML(content) + ASCIIToUTF16("</span>"); } } // namespace NTPLoginHandler::NTPLoginHandler() { } NTPLoginHandler::~NTPLoginHandler() { } void NTPLoginHandler::RegisterMessages() { PrefService* pref_service = Profile::FromWebUI(web_ui())->GetPrefs(); username_pref_.Init(prefs::kGoogleServicesUsername, pref_service, base::Bind(&NTPLoginHandler::UpdateLogin, base::Unretained(this))); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED, content::NotificationService::AllSources()); web_ui()->RegisterMessageCallback("initializeSyncLogin", base::Bind(&NTPLoginHandler::HandleInitializeSyncLogin, base::Unretained(this))); web_ui()->RegisterMessageCallback("showSyncLoginUI", base::Bind(&NTPLoginHandler::HandleShowSyncLoginUI, base::Unretained(this))); web_ui()->RegisterMessageCallback("loginMessageSeen", base::Bind(&NTPLoginHandler::HandleLoginMessageSeen, base::Unretained(this))); web_ui()->RegisterMessageCallback("showAdvancedLoginUI", base::Bind(&NTPLoginHandler::HandleShowAdvancedLoginUI, base::Unretained(this))); } void NTPLoginHandler::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == chrome::NOTIFICATION_PROFILE_CACHED_INFO_CHANGED) { UpdateLogin(); } else { NOTREACHED(); } } void NTPLoginHandler::HandleInitializeSyncLogin(const ListValue* args) { UpdateLogin(); } void NTPLoginHandler::HandleShowSyncLoginUI(const ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetPrefs()->GetString( prefs::kGoogleServicesUsername); content::WebContents* web_contents = web_ui()->GetWebContents(); Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (!browser) return; if (username.empty()) { #if !defined(OS_ANDROID) // The user isn't signed in, show the sync promo. if (SyncPromoUI::ShouldShowSyncPromo(profile)) { chrome::ShowBrowserSignin(browser, SyncPromoUI::SOURCE_NTP_LINK); RecordInHistogram(NTP_SIGN_IN_PROMO_CLICKED); } #endif } else if (args->GetSize() == 4 && chrome::IsCommandEnabled(browser, IDC_SHOW_AVATAR_MENU)) { // The user is signed in, show the profiles menu. double x = 0; double y = 0; double width = 0; double height = 0; bool success = args->GetDouble(0, &x); DCHECK(success); success = args->GetDouble(1, &y); DCHECK(success); success = args->GetDouble(2, &width); DCHECK(success); success = args->GetDouble(3, &height); DCHECK(success); double zoom = WebKit::WebView::zoomLevelToZoomFactor(web_contents->GetZoomLevel()); gfx::Rect rect(x * zoom, y * zoom, width * zoom, height * zoom); browser->window()->ShowAvatarBubble(web_ui()->GetWebContents(), rect); ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::NTP_AVATAR_BUBBLE); } } void NTPLoginHandler::RecordInHistogram(int type) { // Invalid type to record. if (type < NTP_SIGN_IN_PROMO_VIEWED || type > NTP_SIGN_IN_PROMO_CLICKED) { NOTREACHED(); } else { UMA_HISTOGRAM_ENUMERATION("SyncPromo.NTPPromo", type, NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY); } } void NTPLoginHandler::HandleLoginMessageSeen(const ListValue* args) { Profile::FromWebUI(web_ui())->GetPrefs()->SetBoolean( prefs::kSyncPromoShowNTPBubble, false); NewTabUI* ntp_ui = NewTabUI::FromWebUIController(web_ui()->GetController()); // When instant extended is enabled, there may not be a NewTabUI object. if (ntp_ui) ntp_ui->set_showing_sync_bubble(true); } void NTPLoginHandler::HandleShowAdvancedLoginUI(const ListValue* args) { Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); if (browser) chrome::ShowBrowserSignin(browser, SyncPromoUI::SOURCE_NTP_LINK); } void NTPLoginHandler::UpdateLogin() { Profile* profile = Profile::FromWebUI(web_ui()); std::string username = profile->GetPrefs()->GetString( prefs::kGoogleServicesUsername); string16 header, sub_header; std::string icon_url; if (!username.empty()) { ProfileInfoCache& cache = g_browser_process->profile_manager()->GetProfileInfoCache(); size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath()); if (profile_index != std::string::npos) { // Only show the profile picture and full name for the single profile // case. In the multi-profile case the profile picture is visible in the // title bar and the full name can be ambiguous. if (cache.GetNumberOfProfiles() == 1) { string16 name = cache.GetGAIANameOfProfileAtIndex(profile_index); if (!name.empty()) header = CreateSpanWithClass(name, "profile-name"); const gfx::Image* image = cache.GetGAIAPictureOfProfileAtIndex(profile_index); if (image) icon_url = webui::GetBitmapDataUrl(GetGAIAPictureForNTP(*image)); } if (header.empty()) header = CreateSpanWithClass(UTF8ToUTF16(username), "profile-name"); } } else { #if !defined(OS_ANDROID) // Android uses a custom sync promo if (SyncPromoUI::ShouldShowSyncPromo(profile)) { string16 signed_in_link = l10n_util::GetStringUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_LINK); signed_in_link = CreateSpanWithClass(signed_in_link, "link-span"); header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_HEADER, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); sub_header = l10n_util::GetStringFUTF16( IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_SUB_HEADER, signed_in_link); // Record that the user was shown the promo. RecordInHistogram(NTP_SIGN_IN_PROMO_VIEWED); } #endif } StringValue header_value(header); StringValue sub_header_value(sub_header); StringValue icon_url_value(icon_url); base::FundamentalValue is_user_signed_in(!username.empty()); web_ui()->CallJavascriptFunction("ntp.updateLogin", header_value, sub_header_value, icon_url_value, is_user_signed_in); } // static bool NTPLoginHandler::ShouldShow(Profile* profile) { #if defined(OS_CHROMEOS) // For now we don't care about showing sync status on Chrome OS. The promo // UI and the avatar menu don't exist on that platform. return false; #else return !profile->IsOffTheRecord(); #endif } // static void NTPLoginHandler::GetLocalizedValues(Profile* profile, DictionaryValue* values) { PrefService* prefs = profile->GetPrefs(); std::string error_message = prefs->GetString(prefs::kSyncPromoErrorMessage); bool hide_sync = !prefs->GetBoolean(prefs::kSyncPromoShowNTPBubble); string16 message = hide_sync ? string16() : !error_message.empty() ? UTF8ToUTF16(error_message) : l10n_util::GetStringFUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_MESSAGE, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); values->SetString("login_status_message", message); values->SetString("login_status_url", hide_sync ? std::string() : chrome::kSyncLearnMoreURL); values->SetString("login_status_advanced", hide_sync || !error_message.empty() ? string16() : l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_ADVANCED)); values->SetString("login_status_dismiss", hide_sync ? string16() : l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_OK)); } <|endoftext|>
<commit_before>#include <mystdlib.h> #include "incopengl.hpp" #include <myadt.hpp> #include <meshing.hpp> #include <csg.hpp> #include <stlgeom.hpp> #include <visual.hpp> #include "vscsg.hpp" namespace netgen { /* *********************** Draw Geometry **************** */ extern shared_ptr<Mesh> mesh; extern Array<SpecialPoint> specpoints; extern Array<Box<3> > boxes; VisualSceneGeometry :: VisualSceneGeometry () : VisualScene() { selsurf = 0; } VisualSceneGeometry :: ~VisualSceneGeometry () { ; } void VisualSceneGeometry :: SelectSurface (int aselsurf) { selsurf = aselsurf; DrawScene(); } void VisualSceneGeometry :: DrawScene () { cout << "vs-csg::Draw" << endl; if (changeval != geometry->GetChangeVal()) BuildScene(); changeval = geometry->GetChangeVal(); glClearColor(backcolor, backcolor, backcolor, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SetLight(); glPushMatrix(); glMultMatrixd (transformationmat); SetClippingPlane (); glShadeModel (GL_SMOOTH); glDisable (GL_COLOR_MATERIAL); glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* float mat_spec_col[] = { 1, 1, 1, 1 }; glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, mat_spec_col); */ double shine = vispar.shininess; double transp = vispar.transp; glMaterialf (GL_FRONT_AND_BACK, GL_SHININESS, shine); glLogicOp (GL_COPY); glEnable (GL_NORMALIZE); for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { const TopLevelObject * tlo = geometry -> GetTopLevelObject (i); if (tlo->GetVisible() && !tlo->GetTransparent()) { float mat_col[] = { float(tlo->GetRed()), float(tlo->GetGreen()), float(tlo->GetBlue()), 1 }; glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_col); glCallList (trilists[i]); } } glPolygonOffset (1, 1); glEnable (GL_POLYGON_OFFSET_FILL); glLogicOp (GL_NOOP); for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { const TopLevelObject * tlo = geometry -> GetTopLevelObject (i); if (tlo->GetVisible() && tlo->GetTransparent()) { float mat_col[] = { float(tlo->GetRed()), float(tlo->GetGreen()), float(tlo->GetBlue()), float(transp) }; glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_col); glCallList (trilists[i]); } } glDisable (GL_POLYGON_OFFSET_FILL); glPopMatrix(); glDisable(GL_CLIP_PLANE0); DrawCoordinateCross (); DrawNetgenLogo (); glFinish(); } void VisualSceneGeometry :: BuildScene (int zoomall) { cout << "vs-csg::Build" << endl; VisualScene::BuildScene(zoomall); // setting light ... Box<3> box; int hasp = 0; for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { const TriangleApproximation & ta = *geometry->GetTriApprox(i); if (!&ta) continue; for (int j = 0; j < ta.GetNP(); j++) { if (hasp) box.Add (ta.GetPoint(j)); else { hasp = 1; box.Set (ta.GetPoint(j)); } } } if (hasp) { center = box.Center(); rad = box.Diam() / 2; } else { center = Point3d(0,0,0); rad = 1; } CalcTransformationMatrices(); for (int i = 0; i < trilists.Size(); i++) glDeleteLists (trilists[i], 1); trilists.SetSize(0); for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { trilists.Append (glGenLists (1)); glNewList (trilists.Last(), GL_COMPILE); glEnable (GL_NORMALIZE); const TriangleApproximation & ta = *geometry->GetTriApprox(i); if (&ta) { glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_DOUBLE, 0, &ta.GetPoint(0)(0)); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_DOUBLE, 0, &ta.GetNormal(0)(0)); for (int j = 0; j < ta.GetNT(); j++) glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, & (ta.GetTriangle(j)[0])); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); /* for (int j = 0; j < ta.GetNT(); j++) { glBegin (GL_TRIANGLES); for (int k = 0; k < 3; k++) { int pi = ta.GetTriangle(j)[k]; glNormal3dv (ta.GetNormal(pi)); glVertex3dv (ta.GetPoint(pi)); cout << "v = " << ta.GetPoint(pi) << endl; } glEnd (); } */ } glEndList (); } } VisualSceneSpecPoints :: VisualSceneSpecPoints () : VisualScene() { ; } VisualSceneSpecPoints :: ~VisualSceneSpecPoints () { ; } void VisualSceneSpecPoints :: DrawScene () { if (!mesh) { VisualScene::DrawScene(); return; } if (changeval != specpoints.Size()) BuildScene(); changeval = specpoints.Size(); glClearColor(backcolor, backcolor, backcolor, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable (GL_COLOR_MATERIAL); glColor3f (1.0f, 1.0f, 1.0f); glLineWidth (1.0f); glPushMatrix(); glMultMatrixd (transformationmat); // glEnable (GL_COLOR); // glDisable (GL_COLOR_MATERIAL); if (vispar.drawedtangents) { glColor3d (1, 0, 0); glBegin (GL_LINES); for (int i = 1; i <= specpoints.Size(); i++) { const Point3d p1 = specpoints.Get(i).p; const Point3d p2 = specpoints.Get(i).p + len * specpoints.Get(i).v; glVertex3d (p1.X(), p1.Y(), p1.Z()); glVertex3d (p2.X(), p2.Y(), p2.Z()); } glEnd(); } if (vispar.drawededges) { glColor3d (1, 0, 0); glBegin (GL_LINES); for (int i = 1; i <= mesh->GetNSeg(); i++) { const Segment & seg = mesh -> LineSegment (i); glVertex3dv ( (*mesh)[seg[0]] ); glVertex3dv ( (*mesh)[seg[1]] ); // glVertex3dv ( &(*mesh)[seg[0]].X() ); // glVertex3dv ( &(*mesh)[seg[1]].X() ); } glEnd(); } glColor3d (1, 0, 0); glBegin (GL_LINES); int edges[12][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7 }, { 0, 2 }, { 1, 3 }, { 4, 6 }, { 5, 7 }, { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } }; for (int i = 0; i < boxes.Size(); i++) { for (int j = 0; j < 12; j++) { glVertex3dv ( boxes[i].GetPointNr(edges[j][0]) ); glVertex3dv ( boxes[i].GetPointNr(edges[j][1]) ); } /* glVertex3dv ( boxes[i].PMin() ); glVertex3dv ( boxes[i].PMax() ); */ } glEnd(); if (vispar.drawededgenrs) { glEnable (GL_COLOR_MATERIAL); GLfloat textcol[3] = { GLfloat(1 - backcolor), GLfloat(1 - backcolor), GLfloat(1 - backcolor) }; glColor3fv (textcol); glNormal3d (0, 0, 1); glPushAttrib (GL_LIST_BIT); // glListBase (fontbase); char buf[20]; for (int i = 1; i <= mesh->GetNSeg(); i++) { const Segment & seg = mesh -> LineSegment (i); const Point3d p1 = mesh -> Point (seg[0]); const Point3d p2 = mesh -> Point (seg[1]); const Point3d p = Center (p1, p2); glRasterPos3d (p.X(), p.Y(), p.Z()); sprintf (buf, "%d", seg.edgenr); // glCallLists (GLsizei(strlen (buf)), GL_UNSIGNED_BYTE, buf); MyOpenGLText (buf); } glPopAttrib (); glDisable (GL_COLOR_MATERIAL); } if (vispar.drawedpoints) { glColor3d (0, 0, 1); /* glPointSize( 3.0 ); float range[2]; glGetFloatv(GL_POINT_SIZE_RANGE, &range[0]); cout << "max ptsize = " << range[0] << "-" << range[1] << endl; glBegin( GL_POINTS ); for (int i = 1; i <= mesh -> GetNP(); i++) { const Point3d & p = mesh -> Point(i); if (i % 2) glVertex3f( p.X(), p.Y(), p.Z()); } glEnd(); */ static GLubyte knoedel[] = { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, }; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glDisable (GL_COLOR_MATERIAL); glDisable (GL_LIGHTING); glDisable (GL_CLIP_PLANE0); for (int i = 1; i <= mesh -> GetNP(); i++) { const Point3d & p = mesh -> Point(i); glRasterPos3d (p.X(), p.Y(), p.Z()); glBitmap (7, 7, 3, 3, 0, 0, &knoedel[0]); } } if (vispar.drawedpointnrs) { glEnable (GL_COLOR_MATERIAL); GLfloat textcol[3] = { GLfloat(1 - backcolor), GLfloat(1 - backcolor), GLfloat(1 - backcolor) }; glColor3fv (textcol); glNormal3d (0, 0, 1); glPushAttrib (GL_LIST_BIT); // glListBase (fontbase); char buf[20]; for (int i = 1; i <= mesh->GetNP(); i++) { const Point3d & p = mesh->Point(i); glRasterPos3d (p.X(), p.Y(), p.Z()); sprintf (buf, "%d", i); // glCallLists (GLsizei(strlen (buf)), GL_UNSIGNED_BYTE, buf); MyOpenGLText (buf); } glPopAttrib (); glDisable (GL_COLOR_MATERIAL); } glPopMatrix(); if (vispar.drawcoordinatecross) DrawCoordinateCross (); DrawNetgenLogo (); glFinish(); } void VisualSceneSpecPoints :: BuildScene (int zoomall) { if (!mesh) { VisualScene::BuildScene(zoomall); return; } Box3d box; if (mesh->GetNSeg()) { box.SetPoint (mesh->Point (mesh->LineSegment(1)[0])); for (int i = 1; i <= mesh->GetNSeg(); i++) { box.AddPoint (mesh->Point (mesh->LineSegment(i)[0])); box.AddPoint (mesh->Point (mesh->LineSegment(i)[1])); } } else if (specpoints.Size() >= 2) { box.SetPoint (specpoints.Get(1).p); for (int i = 2; i <= specpoints.Size(); i++) box.AddPoint (specpoints.Get(i).p); } else { box = Box3d (Point3d (0,0,0), Point3d (1,1,1)); } if (zoomall == 2 && ((vispar.centerpoint >= 1 && vispar.centerpoint <= mesh->GetNP()) || vispar.use_center_coords)) { if (vispar.use_center_coords) { center.X() = vispar.centerx; center.Y() = vispar.centery; center.Z() = vispar.centerz; } else center = mesh->Point (vispar.centerpoint); } else center = Center (box.PMin(), box.PMax()); rad = 0.5 * Dist (box.PMin(), box.PMax()); CalcTransformationMatrices(); } } #ifdef NG_PYTHON #include <boost/python.hpp> #include <../general/ngpython.hpp> namespace bp = boost::python; void ExportCSGVis() { using namespace netgen; ModuleScope module("csgvis"); bp::class_<VisualSceneGeometry, shared_ptr<VisualSceneGeometry>> ("VisualSceneGeometry", bp::no_init) .def("Draw", &VisualSceneGeometry::DrawScene) ; bp::def("VS", FunctionPointer ([](CSGeometry & geom) { geom.FindIdenticSurfaces(1e-6); geom.CalcTriangleApproximation(0.01, 20); auto vs = make_shared<VisualSceneGeometry>(); vs->SetGeometry(&geom); return vs; })); bp::def("MouseMove", FunctionPointer ([](VisualSceneGeometry &vsgeom, int oldx, int oldy, int newx, int newy, char mode) { vsgeom.MouseMove(oldx, oldy, newx, newy, mode); })); } BOOST_PYTHON_MODULE(libcsgvis) { ExportCSGVis(); } #endif <commit_msg>remove debug output<commit_after>#include <mystdlib.h> #include "incopengl.hpp" #include <myadt.hpp> #include <meshing.hpp> #include <csg.hpp> #include <stlgeom.hpp> #include <visual.hpp> #include "vscsg.hpp" namespace netgen { /* *********************** Draw Geometry **************** */ extern shared_ptr<Mesh> mesh; extern Array<SpecialPoint> specpoints; extern Array<Box<3> > boxes; VisualSceneGeometry :: VisualSceneGeometry () : VisualScene() { selsurf = 0; } VisualSceneGeometry :: ~VisualSceneGeometry () { ; } void VisualSceneGeometry :: SelectSurface (int aselsurf) { selsurf = aselsurf; DrawScene(); } void VisualSceneGeometry :: DrawScene () { if (changeval != geometry->GetChangeVal()) BuildScene(); changeval = geometry->GetChangeVal(); glClearColor(backcolor, backcolor, backcolor, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); SetLight(); glPushMatrix(); glMultMatrixd (transformationmat); SetClippingPlane (); glShadeModel (GL_SMOOTH); glDisable (GL_COLOR_MATERIAL); glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* float mat_spec_col[] = { 1, 1, 1, 1 }; glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, mat_spec_col); */ double shine = vispar.shininess; double transp = vispar.transp; glMaterialf (GL_FRONT_AND_BACK, GL_SHININESS, shine); glLogicOp (GL_COPY); glEnable (GL_NORMALIZE); for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { const TopLevelObject * tlo = geometry -> GetTopLevelObject (i); if (tlo->GetVisible() && !tlo->GetTransparent()) { float mat_col[] = { float(tlo->GetRed()), float(tlo->GetGreen()), float(tlo->GetBlue()), 1 }; glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_col); glCallList (trilists[i]); } } glPolygonOffset (1, 1); glEnable (GL_POLYGON_OFFSET_FILL); glLogicOp (GL_NOOP); for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { const TopLevelObject * tlo = geometry -> GetTopLevelObject (i); if (tlo->GetVisible() && tlo->GetTransparent()) { float mat_col[] = { float(tlo->GetRed()), float(tlo->GetGreen()), float(tlo->GetBlue()), float(transp) }; glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_col); glCallList (trilists[i]); } } glDisable (GL_POLYGON_OFFSET_FILL); glPopMatrix(); glDisable(GL_CLIP_PLANE0); DrawCoordinateCross (); DrawNetgenLogo (); glFinish(); } void VisualSceneGeometry :: BuildScene (int zoomall) { VisualScene::BuildScene(zoomall); // setting light ... Box<3> box; int hasp = 0; for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { const TriangleApproximation & ta = *geometry->GetTriApprox(i); if (!&ta) continue; for (int j = 0; j < ta.GetNP(); j++) { if (hasp) box.Add (ta.GetPoint(j)); else { hasp = 1; box.Set (ta.GetPoint(j)); } } } if (hasp) { center = box.Center(); rad = box.Diam() / 2; } else { center = Point3d(0,0,0); rad = 1; } CalcTransformationMatrices(); for (int i = 0; i < trilists.Size(); i++) glDeleteLists (trilists[i], 1); trilists.SetSize(0); for (int i = 0; i < geometry->GetNTopLevelObjects(); i++) { trilists.Append (glGenLists (1)); glNewList (trilists.Last(), GL_COMPILE); glEnable (GL_NORMALIZE); const TriangleApproximation & ta = *geometry->GetTriApprox(i); if (&ta) { glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_DOUBLE, 0, &ta.GetPoint(0)(0)); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_DOUBLE, 0, &ta.GetNormal(0)(0)); for (int j = 0; j < ta.GetNT(); j++) glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, & (ta.GetTriangle(j)[0])); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); /* for (int j = 0; j < ta.GetNT(); j++) { glBegin (GL_TRIANGLES); for (int k = 0; k < 3; k++) { int pi = ta.GetTriangle(j)[k]; glNormal3dv (ta.GetNormal(pi)); glVertex3dv (ta.GetPoint(pi)); cout << "v = " << ta.GetPoint(pi) << endl; } glEnd (); } */ } glEndList (); } } VisualSceneSpecPoints :: VisualSceneSpecPoints () : VisualScene() { ; } VisualSceneSpecPoints :: ~VisualSceneSpecPoints () { ; } void VisualSceneSpecPoints :: DrawScene () { if (!mesh) { VisualScene::DrawScene(); return; } if (changeval != specpoints.Size()) BuildScene(); changeval = specpoints.Size(); glClearColor(backcolor, backcolor, backcolor, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable (GL_COLOR_MATERIAL); glColor3f (1.0f, 1.0f, 1.0f); glLineWidth (1.0f); glPushMatrix(); glMultMatrixd (transformationmat); // glEnable (GL_COLOR); // glDisable (GL_COLOR_MATERIAL); if (vispar.drawedtangents) { glColor3d (1, 0, 0); glBegin (GL_LINES); for (int i = 1; i <= specpoints.Size(); i++) { const Point3d p1 = specpoints.Get(i).p; const Point3d p2 = specpoints.Get(i).p + len * specpoints.Get(i).v; glVertex3d (p1.X(), p1.Y(), p1.Z()); glVertex3d (p2.X(), p2.Y(), p2.Z()); } glEnd(); } if (vispar.drawededges) { glColor3d (1, 0, 0); glBegin (GL_LINES); for (int i = 1; i <= mesh->GetNSeg(); i++) { const Segment & seg = mesh -> LineSegment (i); glVertex3dv ( (*mesh)[seg[0]] ); glVertex3dv ( (*mesh)[seg[1]] ); // glVertex3dv ( &(*mesh)[seg[0]].X() ); // glVertex3dv ( &(*mesh)[seg[1]].X() ); } glEnd(); } glColor3d (1, 0, 0); glBegin (GL_LINES); int edges[12][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7 }, { 0, 2 }, { 1, 3 }, { 4, 6 }, { 5, 7 }, { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } }; for (int i = 0; i < boxes.Size(); i++) { for (int j = 0; j < 12; j++) { glVertex3dv ( boxes[i].GetPointNr(edges[j][0]) ); glVertex3dv ( boxes[i].GetPointNr(edges[j][1]) ); } /* glVertex3dv ( boxes[i].PMin() ); glVertex3dv ( boxes[i].PMax() ); */ } glEnd(); if (vispar.drawededgenrs) { glEnable (GL_COLOR_MATERIAL); GLfloat textcol[3] = { GLfloat(1 - backcolor), GLfloat(1 - backcolor), GLfloat(1 - backcolor) }; glColor3fv (textcol); glNormal3d (0, 0, 1); glPushAttrib (GL_LIST_BIT); // glListBase (fontbase); char buf[20]; for (int i = 1; i <= mesh->GetNSeg(); i++) { const Segment & seg = mesh -> LineSegment (i); const Point3d p1 = mesh -> Point (seg[0]); const Point3d p2 = mesh -> Point (seg[1]); const Point3d p = Center (p1, p2); glRasterPos3d (p.X(), p.Y(), p.Z()); sprintf (buf, "%d", seg.edgenr); // glCallLists (GLsizei(strlen (buf)), GL_UNSIGNED_BYTE, buf); MyOpenGLText (buf); } glPopAttrib (); glDisable (GL_COLOR_MATERIAL); } if (vispar.drawedpoints) { glColor3d (0, 0, 1); /* glPointSize( 3.0 ); float range[2]; glGetFloatv(GL_POINT_SIZE_RANGE, &range[0]); cout << "max ptsize = " << range[0] << "-" << range[1] << endl; glBegin( GL_POINTS ); for (int i = 1; i <= mesh -> GetNP(); i++) { const Point3d & p = mesh -> Point(i); if (i % 2) glVertex3f( p.X(), p.Y(), p.Z()); } glEnd(); */ static GLubyte knoedel[] = { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, }; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glDisable (GL_COLOR_MATERIAL); glDisable (GL_LIGHTING); glDisable (GL_CLIP_PLANE0); for (int i = 1; i <= mesh -> GetNP(); i++) { const Point3d & p = mesh -> Point(i); glRasterPos3d (p.X(), p.Y(), p.Z()); glBitmap (7, 7, 3, 3, 0, 0, &knoedel[0]); } } if (vispar.drawedpointnrs) { glEnable (GL_COLOR_MATERIAL); GLfloat textcol[3] = { GLfloat(1 - backcolor), GLfloat(1 - backcolor), GLfloat(1 - backcolor) }; glColor3fv (textcol); glNormal3d (0, 0, 1); glPushAttrib (GL_LIST_BIT); // glListBase (fontbase); char buf[20]; for (int i = 1; i <= mesh->GetNP(); i++) { const Point3d & p = mesh->Point(i); glRasterPos3d (p.X(), p.Y(), p.Z()); sprintf (buf, "%d", i); // glCallLists (GLsizei(strlen (buf)), GL_UNSIGNED_BYTE, buf); MyOpenGLText (buf); } glPopAttrib (); glDisable (GL_COLOR_MATERIAL); } glPopMatrix(); if (vispar.drawcoordinatecross) DrawCoordinateCross (); DrawNetgenLogo (); glFinish(); } void VisualSceneSpecPoints :: BuildScene (int zoomall) { if (!mesh) { VisualScene::BuildScene(zoomall); return; } Box3d box; if (mesh->GetNSeg()) { box.SetPoint (mesh->Point (mesh->LineSegment(1)[0])); for (int i = 1; i <= mesh->GetNSeg(); i++) { box.AddPoint (mesh->Point (mesh->LineSegment(i)[0])); box.AddPoint (mesh->Point (mesh->LineSegment(i)[1])); } } else if (specpoints.Size() >= 2) { box.SetPoint (specpoints.Get(1).p); for (int i = 2; i <= specpoints.Size(); i++) box.AddPoint (specpoints.Get(i).p); } else { box = Box3d (Point3d (0,0,0), Point3d (1,1,1)); } if (zoomall == 2 && ((vispar.centerpoint >= 1 && vispar.centerpoint <= mesh->GetNP()) || vispar.use_center_coords)) { if (vispar.use_center_coords) { center.X() = vispar.centerx; center.Y() = vispar.centery; center.Z() = vispar.centerz; } else center = mesh->Point (vispar.centerpoint); } else center = Center (box.PMin(), box.PMax()); rad = 0.5 * Dist (box.PMin(), box.PMax()); CalcTransformationMatrices(); } } #ifdef NG_PYTHON #include <boost/python.hpp> #include <../general/ngpython.hpp> namespace bp = boost::python; void ExportCSGVis() { using namespace netgen; ModuleScope module("csgvis"); bp::class_<VisualSceneGeometry, shared_ptr<VisualSceneGeometry>> ("VisualSceneGeometry", bp::no_init) .def("Draw", &VisualSceneGeometry::DrawScene) ; bp::def("VS", FunctionPointer ([](CSGeometry & geom) { geom.FindIdenticSurfaces(1e-6); geom.CalcTriangleApproximation(0.01, 20); auto vs = make_shared<VisualSceneGeometry>(); vs->SetGeometry(&geom); return vs; })); bp::def("MouseMove", FunctionPointer ([](VisualSceneGeometry &vsgeom, int oldx, int oldy, int newx, int newy, char mode) { vsgeom.MouseMove(oldx, oldy, newx, newy, mode); })); } BOOST_PYTHON_MODULE(libcsgvis) { ExportCSGVis(); } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB * */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <yaml-cpp/yaml.h> #include <boost/program_options.hpp> #include <unordered_map> #include <regex> #include "config.hh" #include "core/file.hh" #include "core/reactor.hh" #include "core/shared_ptr.hh" #include "core/fstream.hh" #include "core/do_with.hh" #include "core/print.hh" #include "log.hh" #include <boost/any.hpp> static logging::logger logger("config"); db::config::config() : // Initialize members to defaults. #define _mk_init(name, type, deflt, status, desc, ...) \ name(deflt), _make_config_values(_mk_init) _dummy(0) {} namespace bpo = boost::program_options; // Special "validator" for boost::program_options to allow reading options // into an unordered_map<string, string> (we have in config.hh a bunch of // those). This validator allows the parameter of each option to look like // 'key=value'. It also allows multiple occurrences of this option to add // multiple entries into the map. "String" can be any time which can be // converted from std::string, e.g., sstring. template<typename String> static void validate(boost::any& out, const std::vector<std::string>& in, std::unordered_map<String, String>*, int) { if (out.empty()) { out = boost::any(std::unordered_map<String, String>()); } auto* p = boost::any_cast<std::unordered_map<String, String>>(&out); for (const auto& s : in) { auto i = s.find_first_of('='); if (i == std::string::npos) { throw boost::program_options::invalid_option_value(s); } (*p)[String(s.substr(0, i))] = String(s.substr(i+1)); } } namespace YAML { /* * Add converters as needed here... */ template<> struct convert<sstring> { static Node encode(sstring rhs) { auto p = rhs.c_str(); return convert<const char *>::encode(p); } static bool decode(const Node& node, sstring& rhs) { std::string tmp; if (!convert<std::string>::decode(node, tmp)) { return false; } rhs = tmp; return true; } }; template <> struct convert<db::config::string_list> { static Node encode(const db::config::string_list& rhs) { Node node(NodeType::Sequence); for (auto& s : rhs) { node.push_back(convert<sstring>::encode(s)); } return node; } static bool decode(const Node& node, db::config::string_list& rhs) { if (!node.IsSequence()) { return false; } rhs.clear(); for (auto& n : node) { sstring tmp; if (!convert<sstring>::decode(n,tmp)) { return false; } rhs.push_back(tmp); } return true; } }; template<> struct convert<db::string_map> { static Node encode(const db::string_map& rhs) { Node node(NodeType::Map); for (auto& p : rhs) { node.force_insert(p.first, p.second); } return node; } static bool decode(const Node& node, db::string_map& rhs) { if (!node.IsMap()) { return false; } rhs.clear(); for (auto& n : node) { rhs[n.first.as<sstring>()] = n.second.as<sstring>(); } return true; } }; template<> struct convert<db::config::seed_provider_type> { static Node encode(const db::config::seed_provider_type& rhs) { throw std::runtime_error("should not reach"); } static bool decode(const Node& node, db::config::seed_provider_type& rhs) { if (!node.IsSequence()) { return false; } rhs = db::config::seed_provider_type(); for (auto& n : node) { if (!n.IsMap()) { continue; } for (auto& n2 : n) { if (n2.first.as<sstring>() == "class_name") { rhs.class_name = n2.second.as<sstring>(); } if (n2.first.as<sstring>() == "parameters") { auto v = n2.second.as<std::vector<db::config::string_map>>(); if (!v.empty()) { rhs.parameters = v.front(); } } } } return true; } }; } namespace db { template<typename... Args> std::basic_ostream<Args...> & operator<<(std::basic_ostream<Args...> & os, const db::config::string_map & map) { int n = 0; for (auto& e : map) { if (n > 0) { os << ":"; } os << e.first << "=" << e.second; } return os; } template<typename... Args> std::basic_istream<Args...> & operator>>(std::basic_istream<Args...> & is, db::config::string_map & map) { std::string str; is >> str; std::regex colon(":"); std::sregex_token_iterator s(str.begin(), str.end(), colon, -1); std::sregex_token_iterator e; while (s != e) { sstring p = std::string(*s++); auto i = p.find('='); auto k = p.substr(0, i); auto v = i == sstring::npos ? sstring() : p.substr(i + 1, p.size()); map.emplace(std::make_pair(k, v)); }; return is; } } /* * Helper type to do compile time exclusion of Unused/invalid options from * command line. * * Only opts marked "used" should get a boost::opt * */ template<typename T, db::config::value_status S> struct do_value_opt; template<typename T> struct do_value_opt<T, db::config::value_status::Used> { template<typename Func> void operator()(Func&& func, const char* name, const T& dflt, T * dst, db::config::config_source & src, const char* desc) const { func(name, dflt, dst, src, desc); } }; template<> struct do_value_opt<db::config::seed_provider_type, db::config::value_status::Used> { using seed_provider_type = db::config::seed_provider_type; template<typename Func> void operator()(Func&& func, const char* name, const seed_provider_type& dflt, seed_provider_type * dst, db::config::config_source & src, const char* desc) const { func((sstring(name) + "_class_name").c_str(), dflt.class_name, &dst->class_name, src, desc); func((sstring(name) + "_parameters").c_str(), dflt.parameters, &dst->parameters, src, desc); } }; template<typename T> struct do_value_opt<T, db::config::value_status::Unused> { template<typename... Args> void operator()(Args&&... args) const {} }; template<typename T> struct do_value_opt<T, db::config::value_status::Invalid> { template<typename... Args> void operator()(Args&&... args) const {} }; bpo::options_description db::config::get_options_description() { bpo::options_description opts("Urchin options"); auto init = opts.add_options(); add_options(init); return std::move(opts); } /* * Our own bpo::typed_valye. * Only difference is that we _don't_ apply defaults (they are already applied) * Needed to make aliases work properly. */ template<class T, class charT = char> class typed_value_ex : public bpo::typed_value<T, charT> { public: typedef bpo::typed_value<T, charT> _Super; typed_value_ex(T* store_to) : _Super(store_to) {} bool apply_default(boost::any& value_store) const override { return false; } }; template<class T> inline typed_value_ex<T>* value_ex(T* v) { typed_value_ex<T>* r = new typed_value_ex<T>(v); return r; } template<class T> inline typed_value_ex<std::vector<T>>* value_ex(std::vector<T>* v) { auto r = new typed_value_ex<std::vector<T>>(v); r->multitoken(); return r; } bpo::options_description_easy_init& db::config::add_options(bpo::options_description_easy_init& init) { auto opt_add = [&init](const char* name, const auto& dflt, auto* dst, auto& src, const char* desc) mutable { sstring tmp(name); std::replace(tmp.begin(), tmp.end(), '_', '-'); init(tmp.c_str(), value_ex(dst)->default_value(dflt)->notifier([&src](auto) mutable { src = config_source::CommandLine; }) , desc); }; // Add all used opts as command line opts #define _add_boost_opt(name, type, deflt, status, desc, ...) \ do_value_opt<type, value_status::status>()(opt_add, #name, type( deflt ), &name._value, name._source, desc); _make_config_values(_add_boost_opt) auto alias_add = [&init](const char* name, auto& dst, const char* desc) mutable { init(name, value_ex(&dst._value)->notifier([&dst](auto& v) mutable { dst._source = config_source::CommandLine; }) , desc); }; // Handle "old" syntax with "aliases" alias_add("datadir", data_file_directories, "alias for 'data-file-directories'"); alias_add("thrift-port", rpc_port, "alias for 'rpc-port'"); alias_add("cql-port", native_transport_port, "alias for 'native-transport-port'"); return init; } // Virtual dispatch to convert yaml->data type. struct handle_yaml { virtual ~handle_yaml() {}; virtual void operator()(const YAML::Node&) = 0; virtual db::config::value_status status() const = 0; virtual db::config::config_source source() const = 0; }; template<typename T, db::config::value_status S> struct handle_yaml_impl : public handle_yaml { typedef db::config::value<T, S> value_type; handle_yaml_impl(value_type& v, db::config::config_source& src) : _dst(v), _src(src) {} void operator()(const YAML::Node& node) override { _dst(node.as<T>()); _src = db::config::config_source::SettingsFile; } db::config::value_status status() const override { return _dst.status(); } db::config::config_source source() const override { return _src; } value_type& _dst; db::config::config_source& _src; }; void db::config::read_from_yaml(const sstring& yaml) { read_from_yaml(yaml.c_str()); } void db::config::read_from_yaml(const char* yaml) { std::unordered_map<sstring, std::unique_ptr<handle_yaml>> values; #define _add_yaml_opt(name, type, deflt, status, desc, ...) \ values.emplace(#name, std::make_unique<handle_yaml_impl<type, value_status::status>>(name, name._source)); _make_config_values(_add_yaml_opt) /* * Note: this is not very "half-fault" tolerant. I.e. there could be * yaml syntax errors that origin handles and still sets the options * where as we don't... * There are no exhaustive attempts at converting, we rely on syntax of * file mapping to the data type... */ auto doc = YAML::Load(yaml); for (auto node : doc) { auto label = node.first.as<sstring>(); auto i = values.find(label); if (i == values.end()) { logger.warn("Unknown option {} ignored.", label); continue; } if (i->second->source() > config_source::SettingsFile) { logger.debug("Option {} already set by commandline. ignored.", label); continue; } switch (i->second->status()) { case value_status::Invalid: logger.warn("Option {} is not applicable. Ignoring.", label); continue; case value_status::Unused: logger.warn("Option {} is not (yet) used.", label); break; default: break; } if (node.second.IsNull()) { logger.debug("Option {}, empty value. Skipping.", label); continue; } // Still, a syntax error is an error warning, not a fail try { (*i->second)(node.second); } catch (...) { logger.error("Option {}, exception while converting value.", label); } } for (auto& p : values) { if (p.second->status() > value_status::Used) { continue; } if (p.second->source() > config_source::None) { continue; } logger.debug("Option {} not set", p.first); } } future<> db::config::read_from_file(file f) { return f.size().then([this, f](size_t s) { return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) { return in.read_exactly(s).then([this](temporary_buffer<char> buf) { read_from_yaml(sstring(buf.begin(), buf.end())); }); }); }); } future<> db::config::read_from_file(const sstring& filename) { return open_file_dma(filename, open_flags::ro).then([this](file f) { return read_from_file(std::move(f)); }); } boost::filesystem::path db::config::get_conf_dir() { using namespace boost::filesystem; path confdir; auto* cd = std::getenv("SCYLLA_CONF"); if (cd != nullptr) { confdir = path(cd); } else { auto* p = std::getenv("SCYLLA_HOME"); if (p != nullptr) { confdir = path(p); } confdir /= "conf"; } return confdir; } void db::config::check_experimental(const sstring& what) const { if (!experimental()) { throw std::runtime_error(sprint("%s is currently disabled. Start Scylla with --experimental=on to enable.", what)); } } <commit_msg>config: adjust boost::program_options validator to work with db::string_map<commit_after>/* * Copyright (C) 2015 ScyllaDB * */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <yaml-cpp/yaml.h> #include <boost/program_options.hpp> #include <unordered_map> #include <regex> #include "config.hh" #include "core/file.hh" #include "core/reactor.hh" #include "core/shared_ptr.hh" #include "core/fstream.hh" #include "core/do_with.hh" #include "core/print.hh" #include "log.hh" #include <boost/any.hpp> static logging::logger logger("config"); db::config::config() : // Initialize members to defaults. #define _mk_init(name, type, deflt, status, desc, ...) \ name(deflt), _make_config_values(_mk_init) _dummy(0) {} namespace bpo = boost::program_options; namespace db { // Special "validator" for boost::program_options to allow reading options // into an unordered_map<string, string> (we have in config.hh a bunch of // those). This validator allows the parameter of each option to look like // 'key=value'. It also allows multiple occurrences of this option to add // multiple entries into the map. "String" can be any time which can be // converted from std::string, e.g., sstring. static void validate(boost::any& out, const std::vector<std::string>& in, db::string_map*, int) { if (out.empty()) { out = boost::any(db::string_map()); } auto* p = boost::any_cast<db::string_map>(&out); for (const auto& s : in) { auto i = s.find_first_of('='); if (i == std::string::npos) { throw boost::program_options::invalid_option_value(s); } (*p)[sstring(s.substr(0, i))] = sstring(s.substr(i+1)); } } } namespace YAML { /* * Add converters as needed here... */ template<> struct convert<sstring> { static Node encode(sstring rhs) { auto p = rhs.c_str(); return convert<const char *>::encode(p); } static bool decode(const Node& node, sstring& rhs) { std::string tmp; if (!convert<std::string>::decode(node, tmp)) { return false; } rhs = tmp; return true; } }; template <> struct convert<db::config::string_list> { static Node encode(const db::config::string_list& rhs) { Node node(NodeType::Sequence); for (auto& s : rhs) { node.push_back(convert<sstring>::encode(s)); } return node; } static bool decode(const Node& node, db::config::string_list& rhs) { if (!node.IsSequence()) { return false; } rhs.clear(); for (auto& n : node) { sstring tmp; if (!convert<sstring>::decode(n,tmp)) { return false; } rhs.push_back(tmp); } return true; } }; template<> struct convert<db::string_map> { static Node encode(const db::string_map& rhs) { Node node(NodeType::Map); for (auto& p : rhs) { node.force_insert(p.first, p.second); } return node; } static bool decode(const Node& node, db::string_map& rhs) { if (!node.IsMap()) { return false; } rhs.clear(); for (auto& n : node) { rhs[n.first.as<sstring>()] = n.second.as<sstring>(); } return true; } }; template<> struct convert<db::config::seed_provider_type> { static Node encode(const db::config::seed_provider_type& rhs) { throw std::runtime_error("should not reach"); } static bool decode(const Node& node, db::config::seed_provider_type& rhs) { if (!node.IsSequence()) { return false; } rhs = db::config::seed_provider_type(); for (auto& n : node) { if (!n.IsMap()) { continue; } for (auto& n2 : n) { if (n2.first.as<sstring>() == "class_name") { rhs.class_name = n2.second.as<sstring>(); } if (n2.first.as<sstring>() == "parameters") { auto v = n2.second.as<std::vector<db::config::string_map>>(); if (!v.empty()) { rhs.parameters = v.front(); } } } } return true; } }; } namespace db { template<typename... Args> std::basic_ostream<Args...> & operator<<(std::basic_ostream<Args...> & os, const db::config::string_map & map) { int n = 0; for (auto& e : map) { if (n > 0) { os << ":"; } os << e.first << "=" << e.second; } return os; } template<typename... Args> std::basic_istream<Args...> & operator>>(std::basic_istream<Args...> & is, db::config::string_map & map) { std::string str; is >> str; std::regex colon(":"); std::sregex_token_iterator s(str.begin(), str.end(), colon, -1); std::sregex_token_iterator e; while (s != e) { sstring p = std::string(*s++); auto i = p.find('='); auto k = p.substr(0, i); auto v = i == sstring::npos ? sstring() : p.substr(i + 1, p.size()); map.emplace(std::make_pair(k, v)); }; return is; } } /* * Helper type to do compile time exclusion of Unused/invalid options from * command line. * * Only opts marked "used" should get a boost::opt * */ template<typename T, db::config::value_status S> struct do_value_opt; template<typename T> struct do_value_opt<T, db::config::value_status::Used> { template<typename Func> void operator()(Func&& func, const char* name, const T& dflt, T * dst, db::config::config_source & src, const char* desc) const { func(name, dflt, dst, src, desc); } }; template<> struct do_value_opt<db::config::seed_provider_type, db::config::value_status::Used> { using seed_provider_type = db::config::seed_provider_type; template<typename Func> void operator()(Func&& func, const char* name, const seed_provider_type& dflt, seed_provider_type * dst, db::config::config_source & src, const char* desc) const { func((sstring(name) + "_class_name").c_str(), dflt.class_name, &dst->class_name, src, desc); func((sstring(name) + "_parameters").c_str(), dflt.parameters, &dst->parameters, src, desc); } }; template<typename T> struct do_value_opt<T, db::config::value_status::Unused> { template<typename... Args> void operator()(Args&&... args) const {} }; template<typename T> struct do_value_opt<T, db::config::value_status::Invalid> { template<typename... Args> void operator()(Args&&... args) const {} }; bpo::options_description db::config::get_options_description() { bpo::options_description opts("Urchin options"); auto init = opts.add_options(); add_options(init); return std::move(opts); } /* * Our own bpo::typed_valye. * Only difference is that we _don't_ apply defaults (they are already applied) * Needed to make aliases work properly. */ template<class T, class charT = char> class typed_value_ex : public bpo::typed_value<T, charT> { public: typedef bpo::typed_value<T, charT> _Super; typed_value_ex(T* store_to) : _Super(store_to) {} bool apply_default(boost::any& value_store) const override { return false; } }; template<class T> inline typed_value_ex<T>* value_ex(T* v) { typed_value_ex<T>* r = new typed_value_ex<T>(v); return r; } template<class T> inline typed_value_ex<std::vector<T>>* value_ex(std::vector<T>* v) { auto r = new typed_value_ex<std::vector<T>>(v); r->multitoken(); return r; } bpo::options_description_easy_init& db::config::add_options(bpo::options_description_easy_init& init) { auto opt_add = [&init](const char* name, const auto& dflt, auto* dst, auto& src, const char* desc) mutable { sstring tmp(name); std::replace(tmp.begin(), tmp.end(), '_', '-'); init(tmp.c_str(), value_ex(dst)->default_value(dflt)->notifier([&src](auto) mutable { src = config_source::CommandLine; }) , desc); }; // Add all used opts as command line opts #define _add_boost_opt(name, type, deflt, status, desc, ...) \ do_value_opt<type, value_status::status>()(opt_add, #name, type( deflt ), &name._value, name._source, desc); _make_config_values(_add_boost_opt) auto alias_add = [&init](const char* name, auto& dst, const char* desc) mutable { init(name, value_ex(&dst._value)->notifier([&dst](auto& v) mutable { dst._source = config_source::CommandLine; }) , desc); }; // Handle "old" syntax with "aliases" alias_add("datadir", data_file_directories, "alias for 'data-file-directories'"); alias_add("thrift-port", rpc_port, "alias for 'rpc-port'"); alias_add("cql-port", native_transport_port, "alias for 'native-transport-port'"); return init; } // Virtual dispatch to convert yaml->data type. struct handle_yaml { virtual ~handle_yaml() {}; virtual void operator()(const YAML::Node&) = 0; virtual db::config::value_status status() const = 0; virtual db::config::config_source source() const = 0; }; template<typename T, db::config::value_status S> struct handle_yaml_impl : public handle_yaml { typedef db::config::value<T, S> value_type; handle_yaml_impl(value_type& v, db::config::config_source& src) : _dst(v), _src(src) {} void operator()(const YAML::Node& node) override { _dst(node.as<T>()); _src = db::config::config_source::SettingsFile; } db::config::value_status status() const override { return _dst.status(); } db::config::config_source source() const override { return _src; } value_type& _dst; db::config::config_source& _src; }; void db::config::read_from_yaml(const sstring& yaml) { read_from_yaml(yaml.c_str()); } void db::config::read_from_yaml(const char* yaml) { std::unordered_map<sstring, std::unique_ptr<handle_yaml>> values; #define _add_yaml_opt(name, type, deflt, status, desc, ...) \ values.emplace(#name, std::make_unique<handle_yaml_impl<type, value_status::status>>(name, name._source)); _make_config_values(_add_yaml_opt) /* * Note: this is not very "half-fault" tolerant. I.e. there could be * yaml syntax errors that origin handles and still sets the options * where as we don't... * There are no exhaustive attempts at converting, we rely on syntax of * file mapping to the data type... */ auto doc = YAML::Load(yaml); for (auto node : doc) { auto label = node.first.as<sstring>(); auto i = values.find(label); if (i == values.end()) { logger.warn("Unknown option {} ignored.", label); continue; } if (i->second->source() > config_source::SettingsFile) { logger.debug("Option {} already set by commandline. ignored.", label); continue; } switch (i->second->status()) { case value_status::Invalid: logger.warn("Option {} is not applicable. Ignoring.", label); continue; case value_status::Unused: logger.warn("Option {} is not (yet) used.", label); break; default: break; } if (node.second.IsNull()) { logger.debug("Option {}, empty value. Skipping.", label); continue; } // Still, a syntax error is an error warning, not a fail try { (*i->second)(node.second); } catch (...) { logger.error("Option {}, exception while converting value.", label); } } for (auto& p : values) { if (p.second->status() > value_status::Used) { continue; } if (p.second->source() > config_source::None) { continue; } logger.debug("Option {} not set", p.first); } } future<> db::config::read_from_file(file f) { return f.size().then([this, f](size_t s) { return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) { return in.read_exactly(s).then([this](temporary_buffer<char> buf) { read_from_yaml(sstring(buf.begin(), buf.end())); }); }); }); } future<> db::config::read_from_file(const sstring& filename) { return open_file_dma(filename, open_flags::ro).then([this](file f) { return read_from_file(std::move(f)); }); } boost::filesystem::path db::config::get_conf_dir() { using namespace boost::filesystem; path confdir; auto* cd = std::getenv("SCYLLA_CONF"); if (cd != nullptr) { confdir = path(cd); } else { auto* p = std::getenv("SCYLLA_HOME"); if (p != nullptr) { confdir = path(p); } confdir /= "conf"; } return confdir; } void db::config::check_experimental(const sstring& what) const { if (!experimental()) { throw std::runtime_error(sprint("%s is currently disabled. Start Scylla with --experimental=on to enable.", what)); } } <|endoftext|>
<commit_before>#include <pluginlib/class_list_macros.h> #include <kdl_parser/kdl_parser.hpp> #include <math.h> #include <lwr_controllers/computed_torque_controller.h> namespace lwr_controllers { ComputedTorqueController::ComputedTorqueController() {} ComputedTorqueController::~ComputedTorqueController() {} bool ComputedTorqueController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { KinematicChainControllerBase<hardware_interface::EffortJointInterface>::init(robot, n); id_solver_.reset( new KDL::ChainDynParam( kdl_chain_, gravity_) ); cmd_states_.resize(kdl_chain_.getNrOfJoints()); tau_cmd_.resize(kdl_chain_.getNrOfJoints()); Kp_.resize(kdl_chain_.getNrOfJoints()); Kv_.resize(kdl_chain_.getNrOfJoints()); M_.resize(kdl_chain_.getNrOfJoints()); C_.resize(kdl_chain_.getNrOfJoints()); G_.resize(kdl_chain_.getNrOfJoints()); joint_initial_states_.resize(kdl_chain_.getNrOfJoints()); current_cmd_.resize(kdl_chain_.getNrOfJoints()); sub_posture_ = nh_.subscribe("command", 1, &ComputedTorqueController::command, this); sub_gains_ = nh_.subscribe("set_gains", 1, &ComputedTorqueController::set_gains, this); return true; } void ComputedTorqueController::starting(const ros::Time& time) { // get joint positions for(size_t i=0; i<joint_handles_.size(); i++) { Kp_(i) = 300.0; Kv_(i) = 0.7; joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); joint_msr_states_.qdotdot(i) = 0.0; joint_des_states_.q(i) = joint_msr_states_.q(i); } lambda = 0.1; // lower values: flatter cmd_flag_ = 0; step_ = 0; ROS_INFO(" Number of joints in handle = %lu", joint_handles_.size() ); } void ComputedTorqueController::update(const ros::Time& time, const ros::Duration& period) { // get joint positions for(size_t i=0; i<joint_handles_.size(); i++) { joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); joint_msr_states_.qdotdot(i) = 0.0; } if(cmd_flag_) { if(step_ == 0) { joint_initial_states_ = joint_msr_states_.q; } // reaching desired joint position using a hyperbolic tangent function double th = tanh(M_PI-lambda*step_); double ch = cosh(M_PI-lambda*step_); double sh2 = 1.0/(ch*ch); for(size_t i=0; i<joint_handles_.size(); i++) { // TODO: take into account also initial/final velocity and acceleration current_cmd_(i) = cmd_states_(i) - joint_initial_states_(i); joint_des_states_.q(i) = current_cmd_(i)*0.5*(1.0-th) + joint_initial_states_(i); joint_des_states_.qdot(i) = current_cmd_(i)*0.5*lambda*sh2; joint_des_states_.qdotdot(i) = current_cmd_(i)*lambda*lambda*sh2*th; } ++step_; if(joint_des_states_.q == cmd_states_) { cmd_flag_ = 0; //reset command flag step_ = 0; ROS_INFO("Posture OK"); } } // computing Inertia, Coriolis and Gravity matrices id_solver_->JntToMass(joint_msr_states_.q, M_); id_solver_->JntToCoriolis(joint_msr_states_.q, joint_msr_states_.qdot, C_); id_solver_->JntToGravity(joint_msr_states_.q, G_); // PID controller KDL::JntArray pid_cmd_(joint_handles_.size()); // compensation of Coriolis and Gravity KDL::JntArray cg_cmd_(joint_handles_.size()); for(size_t i=0; i<joint_handles_.size(); i++) { // control law pid_cmd_(i) = joint_des_states_.qdotdot(i) + Kv_(i)*(joint_des_states_.qdot(i) - joint_msr_states_.qdot(i)) + Kp_(i)*(joint_des_states_.q(i) - joint_msr_states_.q(i)); cg_cmd_(i) = C_(i)*joint_msr_states_.qdot(i) + G_(i); } KDL::Multiply(M_,pid_cmd_,tau_cmd_); KDL::Add(tau_cmd_,cg_cmd_,tau_cmd_); for(size_t i=0; i<joint_handles_.size(); i++) { joint_handles_[i].setCommand(tau_cmd_(i)); } } void ComputedTorqueController::command(const std_msgs::Float64MultiArray::ConstPtr &msg) { if(msg->data.size() == 0) ROS_INFO("Desired configuration must be of dimension %lu", joint_handles_.size()); else if(msg->data.size() != joint_handles_.size()) { ROS_ERROR("Posture message had the wrong size: %u", (unsigned int)msg->data.size()); return; } else { for (unsigned int i = 0; i<joint_handles_.size(); i++) cmd_states_(i) = msg->data[i]; cmd_flag_ = 1; // when a new command is set, steps should be reset to avoid jumps in the update step_ = 0; } } void ComputedTorqueController::set_gains(const std_msgs::Float64MultiArray::ConstPtr &msg) { if(msg->data.size() == 2*joint_handles_.size()) { for(unsigned int i = 0; i < joint_handles_.size(); i++) { Kp_(i) = msg->data[i]; Kv_(i) = msg->data[i + joint_handles_.size()]; } } else ROS_INFO("Number of Joint handles = %lu", joint_handles_.size()); ROS_INFO("Num of Joint handles = %lu, dimension of message = %lu", joint_handles_.size(), msg->data.size()); ROS_INFO("New gains Kp: %.1lf, %.1lf, %.1lf %.1lf, %.1lf, %.1lf, %.1lf", Kp_(0), Kp_(1), Kp_(2), Kp_(3), Kp_(4), Kp_(5), Kp_(6)); ROS_INFO("New gains Kv: %.1lf, %.1lf, %.1lf %.1lf, %.1lf, %.1lf, %.1lf", Kv_(0), Kv_(1), Kv_(2), Kv_(3), Kv_(4), Kv_(5), Kv_(6)); } } PLUGINLIB_EXPORT_CLASS(lwr_controllers::ComputedTorqueController, controller_interface::ControllerBase) <commit_msg>using Eigen multiplication instead of KDL, as it was not compiling in kinetic<commit_after>#include <pluginlib/class_list_macros.h> #include <kdl_parser/kdl_parser.hpp> #include <math.h> #include <lwr_controllers/computed_torque_controller.h> namespace lwr_controllers { ComputedTorqueController::ComputedTorqueController() {} ComputedTorqueController::~ComputedTorqueController() {} bool ComputedTorqueController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n) { KinematicChainControllerBase<hardware_interface::EffortJointInterface>::init(robot, n); id_solver_.reset( new KDL::ChainDynParam( kdl_chain_, gravity_) ); cmd_states_.resize(kdl_chain_.getNrOfJoints()); tau_cmd_.resize(kdl_chain_.getNrOfJoints()); Kp_.resize(kdl_chain_.getNrOfJoints()); Kv_.resize(kdl_chain_.getNrOfJoints()); M_.resize(kdl_chain_.getNrOfJoints()); C_.resize(kdl_chain_.getNrOfJoints()); G_.resize(kdl_chain_.getNrOfJoints()); joint_initial_states_.resize(kdl_chain_.getNrOfJoints()); current_cmd_.resize(kdl_chain_.getNrOfJoints()); sub_posture_ = nh_.subscribe("command", 1, &ComputedTorqueController::command, this); sub_gains_ = nh_.subscribe("set_gains", 1, &ComputedTorqueController::set_gains, this); return true; } void ComputedTorqueController::starting(const ros::Time& time) { // get joint positions for(size_t i=0; i<joint_handles_.size(); i++) { Kp_(i) = 300.0; Kv_(i) = 0.7; joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); joint_msr_states_.qdotdot(i) = 0.0; joint_des_states_.q(i) = joint_msr_states_.q(i); } lambda = 0.1; // lower values: flatter cmd_flag_ = 0; step_ = 0; ROS_INFO(" Number of joints in handle = %lu", joint_handles_.size() ); } void ComputedTorqueController::update(const ros::Time& time, const ros::Duration& period) { // get joint positions for(size_t i=0; i<joint_handles_.size(); i++) { joint_msr_states_.q(i) = joint_handles_[i].getPosition(); joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity(); joint_msr_states_.qdotdot(i) = 0.0; } if(cmd_flag_) { if(step_ == 0) { joint_initial_states_ = joint_msr_states_.q; } // reaching desired joint position using a hyperbolic tangent function double th = tanh(M_PI-lambda*step_); double ch = cosh(M_PI-lambda*step_); double sh2 = 1.0/(ch*ch); for(size_t i=0; i<joint_handles_.size(); i++) { // TODO: take into account also initial/final velocity and acceleration current_cmd_(i) = cmd_states_(i) - joint_initial_states_(i); joint_des_states_.q(i) = current_cmd_(i)*0.5*(1.0-th) + joint_initial_states_(i); joint_des_states_.qdot(i) = current_cmd_(i)*0.5*lambda*sh2; joint_des_states_.qdotdot(i) = current_cmd_(i)*lambda*lambda*sh2*th; } ++step_; if(joint_des_states_.q == cmd_states_) { cmd_flag_ = 0; //reset command flag step_ = 0; ROS_INFO("Posture OK"); } } // computing Inertia, Coriolis and Gravity matrices id_solver_->JntToMass(joint_msr_states_.q, M_); id_solver_->JntToCoriolis(joint_msr_states_.q, joint_msr_states_.qdot, C_); id_solver_->JntToGravity(joint_msr_states_.q, G_); // PID controller KDL::JntArray pid_cmd_(joint_handles_.size()); // compensation of Coriolis and Gravity KDL::JntArray cg_cmd_(joint_handles_.size()); for(size_t i=0; i<joint_handles_.size(); i++) { // control law pid_cmd_(i) = joint_des_states_.qdotdot(i) + Kv_(i)*(joint_des_states_.qdot(i) - joint_msr_states_.qdot(i)) + Kp_(i)*(joint_des_states_.q(i) - joint_msr_states_.q(i)); cg_cmd_(i) = C_(i)*joint_msr_states_.qdot(i) + G_(i); } tau_cmd_.data = M_.data * pid_cmd_.data; KDL::Add(tau_cmd_,cg_cmd_,tau_cmd_); for(size_t i=0; i<joint_handles_.size(); i++) { joint_handles_[i].setCommand(tau_cmd_(i)); } } void ComputedTorqueController::command(const std_msgs::Float64MultiArray::ConstPtr &msg) { if(msg->data.size() == 0) ROS_INFO("Desired configuration must be of dimension %lu", joint_handles_.size()); else if(msg->data.size() != joint_handles_.size()) { ROS_ERROR("Posture message had the wrong size: %u", (unsigned int)msg->data.size()); return; } else { for (unsigned int i = 0; i<joint_handles_.size(); i++) cmd_states_(i) = msg->data[i]; cmd_flag_ = 1; // when a new command is set, steps should be reset to avoid jumps in the update step_ = 0; } } void ComputedTorqueController::set_gains(const std_msgs::Float64MultiArray::ConstPtr &msg) { if(msg->data.size() == 2*joint_handles_.size()) { for(unsigned int i = 0; i < joint_handles_.size(); i++) { Kp_(i) = msg->data[i]; Kv_(i) = msg->data[i + joint_handles_.size()]; } } else ROS_INFO("Number of Joint handles = %lu", joint_handles_.size()); ROS_INFO("Num of Joint handles = %lu, dimension of message = %lu", joint_handles_.size(), msg->data.size()); ROS_INFO("New gains Kp: %.1lf, %.1lf, %.1lf %.1lf, %.1lf, %.1lf, %.1lf", Kp_(0), Kp_(1), Kp_(2), Kp_(3), Kp_(4), Kp_(5), Kp_(6)); ROS_INFO("New gains Kv: %.1lf, %.1lf, %.1lf %.1lf, %.1lf, %.1lf, %.1lf", Kv_(0), Kv_(1), Kv_(2), Kv_(3), Kv_(4), Kv_(5), Kv_(6)); } } PLUGINLIB_EXPORT_CLASS(lwr_controllers::ComputedTorqueController, controller_interface::ControllerBase) <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (people-users@projects.maemo.org) ** ** This file is part of contactsd. ** ** If you have questions regarding the use of this file, please contact ** Nokia at people-users@projects.maemo.org. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QTest> #include <QFile> #include <QContactFetchByIdRequest> #include <QContactAvatar> #include <QContactOnlineAccount> #include <QContactPhoneNumber> #include <QContactAddress> #include <QContactPresence> #include <QContactEmailAddress> #include <QContactGlobalPresence> #include "test-expectation.h" #include "debug.h" // --- TestExpectation --- void TestExpectation::verify(Event event, const QList<QContactLocalId> &contactIds) { new TestFetchContacts(contactIds, event, this); } void TestExpectation::verify(Event event, const QList<QContact> &contacts) { Q_UNUSED(event); Q_UNUSED(contacts); emitFinished(); } void TestExpectation::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { Q_UNUSED(event); Q_UNUSED(contactIds); Q_UNUSED(error); QVERIFY2(false, "Error fetching contacts"); emitFinished(); } void TestExpectation::emitFinished() { Q_EMIT finished(); } // --- TestFetchContacts --- TestFetchContacts::TestFetchContacts(const QList<QContactLocalId> &contactIds, Event event, TestExpectation *exp) : QObject(exp), mContactIds(contactIds), mEvent(event), mExp(exp) { QContactFetchByIdRequest *request = new QContactFetchByIdRequest(); connect(request, SIGNAL(resultsAvailable()), SLOT(onContactsFetched())); request->setManager(mExp->contactManager()); request->setLocalIds(contactIds); QVERIFY(request->start()); } void TestFetchContacts::onContactsFetched() { QContactFetchByIdRequest *req = qobject_cast<QContactFetchByIdRequest *>(sender()); if (req == 0 || !req->isFinished()) { return; } if (req->error() == QContactManager::NoError) { mExp->verify(mEvent, req->contacts()); } else { mExp->verify(mEvent, mContactIds, req->error()); } deleteLater(); req->deleteLater(); } // --- TestExpectationInit --- void TestExpectationInit::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].localId(), contactManager()->selfContactId()); emitFinished(); } // --- TestExpectationCleanup --- TestExpectationCleanup::TestExpectationCleanup(int nContacts) : mNContacts(nContacts), mSelfChanged(false) { } void TestExpectationCleanup::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].localId(), contactManager()->selfContactId()); mNContacts--; mSelfChanged = true; maybeEmitFinished(); } void TestExpectationCleanup::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { QCOMPARE(event, EventRemoved); QCOMPARE(error, QContactManager::DoesNotExistError); mNContacts -= contactIds.count(); maybeEmitFinished(); } void TestExpectationCleanup::maybeEmitFinished() { QVERIFY(mNContacts >= 0); if (mNContacts == 0 && mSelfChanged) { emitFinished(); } } // --- TestExpectationContact --- TestExpectationContact::TestExpectationContact(Event event, QString accountUri): mAccountUri(accountUri), mEvent(event), mFlags(0), mPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET), mContactInfo(0) { } void TestExpectationContact::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, mEvent); QCOMPARE(contacts.count(), 1); mContact = contacts[0]; verify(contacts[0]); emitFinished(); } void TestExpectationContact::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { QCOMPARE(event, EventRemoved); QCOMPARE(contactIds.count(), 1); QCOMPARE(error, QContactManager::DoesNotExistError); emitFinished(); } void TestExpectationContact::verify(QContact contact) { debug() << contact; if (!mAccountUri.isEmpty()) { const QString uri = QString("telepathy:%1!%2").arg(ACCOUNT_PATH).arg(mAccountUri); QList<QContactOnlineAccount> details = contact.details<QContactOnlineAccount>("DetailUri", uri); QCOMPARE(details.count(), 1); QCOMPARE(details[0].value("AccountPath"), QString(ACCOUNT_PATH)); } if (mFlags & VerifyAlias) { QString label = contact.detail<QContactDisplayLabel>().label(); QCOMPARE(label, mAlias); } if (mFlags & VerifyPresence) { QContactPresence::PresenceState presence; if (mAccountUri.isEmpty()) { QContactGlobalPresence presenceDetail = contact.detail<QContactGlobalPresence>(); presence = presenceDetail.presenceState(); } else { const QString uri = QString("presence:%1!%2").arg(ACCOUNT_PATH).arg(mAccountUri); QList<QContactPresence> details = contact.details<QContactPresence>("DetailUri", uri); QCOMPARE(details.count(), 1); presence = details[0].presenceState(); } switch (mPresence) { case TP_TESTS_CONTACTS_CONNECTION_STATUS_AVAILABLE: QCOMPARE(presence, QContactPresence::PresenceAvailable); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_BUSY: QCOMPARE(presence, QContactPresence::PresenceBusy); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_AWAY: QCOMPARE(presence, QContactPresence::PresenceAway); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE: QCOMPARE(presence, QContactPresence::PresenceOffline); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN: case TP_TESTS_CONTACTS_CONNECTION_STATUS_ERROR: case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET: QCOMPARE(presence, QContactPresence::PresenceUnknown); break; } } if (mFlags & VerifyAvatar) { QString avatarFileName = contact.detail<QContactAvatar>().imageUrl().path(); if (mAvatarData.isEmpty()) { QVERIFY2(avatarFileName.isEmpty(), "Expected empty avatar filename"); } else { QFile file(avatarFileName); file.open(QIODevice::ReadOnly); QCOMPARE(file.readAll(), mAvatarData); file.close(); } } if (mFlags & VerifyAuthorization) { const QString uri = QString("presence:%1!%2").arg(ACCOUNT_PATH).arg(mAccountUri); QList<QContactPresence> details = contact.details<QContactPresence>("DetailUri", uri); QCOMPARE(details.count(), 1); QCOMPARE(details[0].value("AuthStatusFrom"), mSubscriptionState); QCOMPARE(details[0].value("AuthStatusTo"), mPublishState); } if (mFlags & VerifyInfo) { uint nMatchedField = 0; Q_FOREACH (const QContactDetail &detail, contact.details()) { if (detail.definitionName() == "PhoneNumber") { QContactPhoneNumber phoneNumber = static_cast<QContactPhoneNumber>(detail); verifyContactInfo("tel", QStringList() << phoneNumber.number()); nMatchedField++; } else if (detail.definitionName() == "Address") { QContactAddress address = static_cast<QContactAddress>(detail); verifyContactInfo("adr", QStringList() << address.postOfficeBox() << QString("unmapped") // extended address is not mapped << address.street() << address.locality() << address.region() << address.postcode() << address.country()); nMatchedField++; } else if (detail.definitionName() == "EmailAddress") { QContactEmailAddress emailAddress = static_cast<QContactEmailAddress >(detail); verifyContactInfo("email", QStringList() << emailAddress.emailAddress()); nMatchedField++; } } if (mContactInfo != NULL) { QCOMPARE(nMatchedField, mContactInfo->len); } } if (mFlags & VerifyLocalId) { QCOMPARE(contact.localId(), mLocalId); } } void TestExpectationContact::verifyContactInfo(QString name, const QStringList values) const { QVERIFY2(mContactInfo != NULL, "Found ContactInfo field, was expecting none"); bool found = false; for (uint i = 0; i < mContactInfo->len; i++) { gchar *c_name; gchar **c_parameters; gchar **c_values; tp_value_array_unpack((GValueArray*) g_ptr_array_index(mContactInfo, i), 3, &c_name, &c_parameters, &c_values); /* if c_values_len < values.count() it could still be OK if all * additional values are empty. */ gint c_values_len = g_strv_length(c_values); if (QString(c_name) != name || c_values_len > values.count()) { continue; } bool match = true; for (int j = 0; j < values.count(); j++) { if (values[j] == QString("unmapped")) { continue; } if ((j < c_values_len && values[j] != QString(c_values[j])) || (j >= c_values_len && !values[j].isEmpty())) { match = false; break; } } if (match) { found = true; break; } } QVERIFY2(found, "Unexpected ContactInfo field"); } // --- TestExpectationDisconnect --- TestExpectationDisconnect::TestExpectationDisconnect(int nContacts) : TestExpectationContact(EventChanged), mNContacts(nContacts), mSelfChanged(false) { } void TestExpectationDisconnect::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); Q_FOREACH (const QContact contact, contacts) { if (contact.localId() == contactManager()->selfContactId()) { verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE); mSelfChanged = true; } else { verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN); } TestExpectationContact::verify(contact); } mNContacts -= contacts.count(); QVERIFY(mNContacts >= 0); if (mNContacts == 0 && mSelfChanged) { emitFinished(); } } // --- TestExpectationMerge --- TestExpectationMerge::TestExpectationMerge(const QContactLocalId masterId, const QList<QContactLocalId> mergeIds, const QList<TestExpectationContact *> expectations) : mMasterId(masterId), mMergeIds(mergeIds), mGotMergedContact(false), mContactExpectations(expectations) { } void TestExpectationMerge::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].localId(), mMasterId); mGotMergedContact = true; Q_FOREACH (TestExpectationContact *exp, mContactExpectations) { exp->verify(contacts[0]); } maybeEmitFinished(); } void TestExpectationMerge::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { QCOMPARE(event, EventRemoved); QCOMPARE(error, QContactManager::DoesNotExistError); Q_FOREACH (QContactLocalId localId, contactIds) { QVERIFY(mMergeIds.contains(localId)); mMergeIds.removeOne(localId); } maybeEmitFinished(); } void TestExpectationMerge::maybeEmitFinished() { if (mMergeIds.isEmpty() && mGotMergedContact) { emitFinished(); } } <commit_msg>Ignore contactsAdded signal emitted at contactsd startup for the voicemail contact<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (people-users@projects.maemo.org) ** ** This file is part of contactsd. ** ** If you have questions regarding the use of this file, please contact ** Nokia at people-users@projects.maemo.org. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QTest> #include <QFile> #include <QContactFetchByIdRequest> #include <QContactAvatar> #include <QContactOnlineAccount> #include <QContactPhoneNumber> #include <QContactAddress> #include <QContactPresence> #include <QContactEmailAddress> #include <QContactGlobalPresence> #include <QContactTag> #include "test-expectation.h" #include "debug.h" // --- TestExpectation --- void TestExpectation::verify(Event event, const QList<QContactLocalId> &contactIds) { new TestFetchContacts(contactIds, event, this); } void TestExpectation::verify(Event event, const QList<QContact> &contacts) { Q_UNUSED(event); Q_UNUSED(contacts); emitFinished(); } void TestExpectation::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { Q_UNUSED(event); Q_UNUSED(contactIds); Q_UNUSED(error); QVERIFY2(false, "Error fetching contacts"); emitFinished(); } void TestExpectation::emitFinished() { Q_EMIT finished(); } // --- TestFetchContacts --- TestFetchContacts::TestFetchContacts(const QList<QContactLocalId> &contactIds, Event event, TestExpectation *exp) : QObject(exp), mContactIds(contactIds), mEvent(event), mExp(exp) { QContactFetchByIdRequest *request = new QContactFetchByIdRequest(); connect(request, SIGNAL(resultsAvailable()), SLOT(onContactsFetched())); request->setManager(mExp->contactManager()); request->setLocalIds(contactIds); QVERIFY(request->start()); } void TestFetchContacts::onContactsFetched() { QContactFetchByIdRequest *req = qobject_cast<QContactFetchByIdRequest *>(sender()); if (req == 0 || !req->isFinished()) { return; } if (req->error() == QContactManager::NoError) { mExp->verify(mEvent, req->contacts()); } else { mExp->verify(mEvent, mContactIds, req->error()); } deleteLater(); req->deleteLater(); } // --- TestExpectationInit --- void TestExpectationInit::verify(Event event, const QList<QContact> &contacts) { // For some reason VoiceMail contact gets added at init sometimes. Ignore it. if (event ==EventAdded) { QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].detail<QContactTag>().tag(), QLatin1String("voicemail")); return; } QCOMPARE(event, EventChanged); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].localId(), contactManager()->selfContactId()); emitFinished(); } // --- TestExpectationCleanup --- TestExpectationCleanup::TestExpectationCleanup(int nContacts) : mNContacts(nContacts), mSelfChanged(false) { } void TestExpectationCleanup::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].localId(), contactManager()->selfContactId()); mNContacts--; mSelfChanged = true; maybeEmitFinished(); } void TestExpectationCleanup::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { QCOMPARE(event, EventRemoved); QCOMPARE(error, QContactManager::DoesNotExistError); mNContacts -= contactIds.count(); maybeEmitFinished(); } void TestExpectationCleanup::maybeEmitFinished() { QVERIFY(mNContacts >= 0); if (mNContacts == 0 && mSelfChanged) { emitFinished(); } } // --- TestExpectationContact --- TestExpectationContact::TestExpectationContact(Event event, QString accountUri): mAccountUri(accountUri), mEvent(event), mFlags(0), mPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET), mContactInfo(0) { } void TestExpectationContact::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, mEvent); QCOMPARE(contacts.count(), 1); mContact = contacts[0]; verify(contacts[0]); emitFinished(); } void TestExpectationContact::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { QCOMPARE(event, EventRemoved); QCOMPARE(contactIds.count(), 1); QCOMPARE(error, QContactManager::DoesNotExistError); emitFinished(); } void TestExpectationContact::verify(QContact contact) { debug() << contact; if (!mAccountUri.isEmpty()) { const QString uri = QString("telepathy:%1!%2").arg(ACCOUNT_PATH).arg(mAccountUri); QList<QContactOnlineAccount> details = contact.details<QContactOnlineAccount>("DetailUri", uri); QCOMPARE(details.count(), 1); QCOMPARE(details[0].value("AccountPath"), QString(ACCOUNT_PATH)); } if (mFlags & VerifyAlias) { QString label = contact.detail<QContactDisplayLabel>().label(); QCOMPARE(label, mAlias); } if (mFlags & VerifyPresence) { QContactPresence::PresenceState presence; if (mAccountUri.isEmpty()) { QContactGlobalPresence presenceDetail = contact.detail<QContactGlobalPresence>(); presence = presenceDetail.presenceState(); } else { const QString uri = QString("presence:%1!%2").arg(ACCOUNT_PATH).arg(mAccountUri); QList<QContactPresence> details = contact.details<QContactPresence>("DetailUri", uri); QCOMPARE(details.count(), 1); presence = details[0].presenceState(); } switch (mPresence) { case TP_TESTS_CONTACTS_CONNECTION_STATUS_AVAILABLE: QCOMPARE(presence, QContactPresence::PresenceAvailable); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_BUSY: QCOMPARE(presence, QContactPresence::PresenceBusy); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_AWAY: QCOMPARE(presence, QContactPresence::PresenceAway); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE: QCOMPARE(presence, QContactPresence::PresenceOffline); break; case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN: case TP_TESTS_CONTACTS_CONNECTION_STATUS_ERROR: case TP_TESTS_CONTACTS_CONNECTION_STATUS_UNSET: QCOMPARE(presence, QContactPresence::PresenceUnknown); break; } } if (mFlags & VerifyAvatar) { QString avatarFileName = contact.detail<QContactAvatar>().imageUrl().path(); if (mAvatarData.isEmpty()) { QVERIFY2(avatarFileName.isEmpty(), "Expected empty avatar filename"); } else { QFile file(avatarFileName); file.open(QIODevice::ReadOnly); QCOMPARE(file.readAll(), mAvatarData); file.close(); } } if (mFlags & VerifyAuthorization) { const QString uri = QString("presence:%1!%2").arg(ACCOUNT_PATH).arg(mAccountUri); QList<QContactPresence> details = contact.details<QContactPresence>("DetailUri", uri); QCOMPARE(details.count(), 1); QCOMPARE(details[0].value("AuthStatusFrom"), mSubscriptionState); QCOMPARE(details[0].value("AuthStatusTo"), mPublishState); } if (mFlags & VerifyInfo) { uint nMatchedField = 0; Q_FOREACH (const QContactDetail &detail, contact.details()) { if (detail.definitionName() == "PhoneNumber") { QContactPhoneNumber phoneNumber = static_cast<QContactPhoneNumber>(detail); verifyContactInfo("tel", QStringList() << phoneNumber.number()); nMatchedField++; } else if (detail.definitionName() == "Address") { QContactAddress address = static_cast<QContactAddress>(detail); verifyContactInfo("adr", QStringList() << address.postOfficeBox() << QString("unmapped") // extended address is not mapped << address.street() << address.locality() << address.region() << address.postcode() << address.country()); nMatchedField++; } else if (detail.definitionName() == "EmailAddress") { QContactEmailAddress emailAddress = static_cast<QContactEmailAddress >(detail); verifyContactInfo("email", QStringList() << emailAddress.emailAddress()); nMatchedField++; } } if (mContactInfo != NULL) { QCOMPARE(nMatchedField, mContactInfo->len); } } if (mFlags & VerifyLocalId) { QCOMPARE(contact.localId(), mLocalId); } } void TestExpectationContact::verifyContactInfo(QString name, const QStringList values) const { QVERIFY2(mContactInfo != NULL, "Found ContactInfo field, was expecting none"); bool found = false; for (uint i = 0; i < mContactInfo->len; i++) { gchar *c_name; gchar **c_parameters; gchar **c_values; tp_value_array_unpack((GValueArray*) g_ptr_array_index(mContactInfo, i), 3, &c_name, &c_parameters, &c_values); /* if c_values_len < values.count() it could still be OK if all * additional values are empty. */ gint c_values_len = g_strv_length(c_values); if (QString(c_name) != name || c_values_len > values.count()) { continue; } bool match = true; for (int j = 0; j < values.count(); j++) { if (values[j] == QString("unmapped")) { continue; } if ((j < c_values_len && values[j] != QString(c_values[j])) || (j >= c_values_len && !values[j].isEmpty())) { match = false; break; } } if (match) { found = true; break; } } QVERIFY2(found, "Unexpected ContactInfo field"); } // --- TestExpectationDisconnect --- TestExpectationDisconnect::TestExpectationDisconnect(int nContacts) : TestExpectationContact(EventChanged), mNContacts(nContacts), mSelfChanged(false) { } void TestExpectationDisconnect::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); Q_FOREACH (const QContact contact, contacts) { if (contact.localId() == contactManager()->selfContactId()) { verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_OFFLINE); mSelfChanged = true; } else { verifyPresence(TP_TESTS_CONTACTS_CONNECTION_STATUS_UNKNOWN); } TestExpectationContact::verify(contact); } mNContacts -= contacts.count(); QVERIFY(mNContacts >= 0); if (mNContacts == 0 && mSelfChanged) { emitFinished(); } } // --- TestExpectationMerge --- TestExpectationMerge::TestExpectationMerge(const QContactLocalId masterId, const QList<QContactLocalId> mergeIds, const QList<TestExpectationContact *> expectations) : mMasterId(masterId), mMergeIds(mergeIds), mGotMergedContact(false), mContactExpectations(expectations) { } void TestExpectationMerge::verify(Event event, const QList<QContact> &contacts) { QCOMPARE(event, EventChanged); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts[0].localId(), mMasterId); mGotMergedContact = true; Q_FOREACH (TestExpectationContact *exp, mContactExpectations) { exp->verify(contacts[0]); } maybeEmitFinished(); } void TestExpectationMerge::verify(Event event, const QList<QContactLocalId> &contactIds, QContactManager::Error error) { QCOMPARE(event, EventRemoved); QCOMPARE(error, QContactManager::DoesNotExistError); Q_FOREACH (QContactLocalId localId, contactIds) { QVERIFY(mMergeIds.contains(localId)); mMergeIds.removeOne(localId); } maybeEmitFinished(); } void TestExpectationMerge::maybeEmitFinished() { if (mMergeIds.isEmpty() && mGotMergedContact) { emitFinished(); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/blob_store.h" namespace rocksdb { using namespace std; // BlobChunk bool BlobChunk::ImmediatelyBefore(const BlobChunk& chunk) const { // overlapping!? assert(!Overlap(chunk)); // size == 0 is a marker, not a block return size != 0 && bucket_id == chunk.bucket_id && offset + size == chunk.offset; } bool BlobChunk::Overlap(const BlobChunk &chunk) const { return size != 0 && chunk.size != 0 && bucket_id == chunk.bucket_id && ((offset >= chunk.offset && offset < chunk.offset + chunk.size) || (chunk.offset >= offset && chunk.offset < offset + size)); } // Blob string Blob::ToString() const { string ret; for (auto chunk : chunks) { PutFixed32(&ret, chunk.bucket_id); PutFixed32(&ret, chunk.offset); PutFixed32(&ret, chunk.size); } return ret; } Blob::Blob(const std::string& blob) { for (uint32_t i = 0; i < blob.size(); ) { uint32_t t[3] = {0}; for (int j = 0; j < 3 && i + sizeof(uint32_t) - 1 < blob.size(); ++j, i += sizeof(uint32_t)) { t[j] = DecodeFixed32(blob.data() + i); } chunks.push_back(BlobChunk(t[0], t[1], t[2])); } } // FreeList FreeList::FreeList() { // We add (0, 0, 0) blob because it makes our life easier and // code cleaner. (0, 0, 0) is always in the list so we can // guarantee that free_chunks_list_ != nullptr, which avoids // lots of unnecessary ifs free_chunks_list_ = (FreeChunk *)malloc(sizeof(FreeChunk)); free_chunks_list_->chunk = BlobChunk(0, 0, 0); free_chunks_list_->next = nullptr; } FreeList::~FreeList() { while (free_chunks_list_ != nullptr) { FreeChunk* t = free_chunks_list_; free_chunks_list_ = free_chunks_list_->next; free(t); } } Status FreeList::Free(const Blob& blob) { MutexLock l(&mutex_); // add it back to the free list for (auto chunk : blob.chunks) { FreeChunk* itr = free_chunks_list_; // find a node AFTER which we'll add the block for ( ; itr->next != nullptr && itr->next->chunk <= chunk; itr = itr->next) { } // try to merge with previous block if (itr->chunk.ImmediatelyBefore(chunk)) { // merge itr->chunk.size += chunk.size; } else { // Insert the block after itr FreeChunk* t = (FreeChunk*)malloc(sizeof(FreeChunk)); if (t == nullptr) { throw runtime_error("Malloc failed"); } t->chunk = chunk; t->next = itr->next; itr->next = t; itr = t; } // try to merge with the next block if (itr->next != nullptr && itr->chunk.ImmediatelyBefore(itr->next->chunk)) { FreeChunk *tobedeleted = itr->next; itr->chunk.size += itr->next->chunk.size; itr->next = itr->next->next; free(tobedeleted); } } return Status::OK(); } Status FreeList::Allocate(uint32_t blocks, Blob* blob) { MutexLock l(&mutex_); FreeChunk** best_fit_node = nullptr; // Find the smallest free chunk whose size is greater or equal to blocks for (FreeChunk** itr = &free_chunks_list_; (*itr) != nullptr; itr = &((*itr)->next)) { if ((*itr)->chunk.size >= blocks && (best_fit_node == nullptr || (*best_fit_node)->chunk.size > (*itr)->chunk.size)) { best_fit_node = itr; } } if (best_fit_node == nullptr || *best_fit_node == nullptr) { // Not enough memory return Status::Incomplete(""); } blob->SetOneChunk((*best_fit_node)->chunk.bucket_id, (*best_fit_node)->chunk.offset, blocks); if ((*best_fit_node)->chunk.size > blocks) { // just shorten best_fit_node (*best_fit_node)->chunk.offset += blocks; (*best_fit_node)->chunk.size -= blocks; } else { assert(blocks == (*best_fit_node)->chunk.size); // delete best_fit_node FreeChunk* t = *best_fit_node; (*best_fit_node) = (*best_fit_node)->next; free(t); } return Status::OK(); } bool FreeList::Overlap(const Blob &blob) const { MutexLock l(&mutex_); for (auto chunk : blob.chunks) { for (auto itr = free_chunks_list_; itr != nullptr; itr = itr->next) { if (itr->chunk.Overlap(chunk)) { return true; } } } return false; } // BlobStore BlobStore::BlobStore(const string& directory, uint64_t block_size, uint32_t blocks_per_bucket, Env* env) : directory_(directory), block_size_(block_size), blocks_per_bucket_(blocks_per_bucket), env_(env) { env_->CreateDirIfMissing(directory_); storage_options_.use_mmap_writes = false; storage_options_.use_mmap_reads = false; CreateNewBucket(); } BlobStore::~BlobStore() { // TODO we don't care about recovery for now } Status BlobStore::Put(const char* value, uint64_t size, Blob* blob) { // convert size to number of blocks Status s = Allocate((size + block_size_ - 1) / block_size_, blob); if (!s.ok()) { return s; } uint64_t offset = 0; // in bytes, not blocks for (auto chunk : blob->chunks) { uint64_t write_size = min(chunk.size * block_size_, size); assert(chunk.bucket_id < buckets_.size()); s = buckets_[chunk.bucket_id].get()->Write(chunk.offset * block_size_, Slice(value + offset, write_size)); if (!s.ok()) { Delete(*blob); return s; } offset += write_size; size -= write_size; if (write_size < chunk.size * block_size_) { // if we have any space left in the block, fill it up with zeros string zero_string(chunk.size * block_size_ - write_size, 0); s = buckets_[chunk.bucket_id].get()->Write(chunk.offset * block_size_ + write_size, Slice(zero_string)); } } if (size > 0) { Delete(*blob); return Status::IOError("Tried to write more data than fits in the blob"); } return Status::OK(); } Status BlobStore::Get(const Blob& blob, string* value) const { // assert that it doesn't overlap with free list // it will get compiled out for release assert(!free_list_.Overlap(blob)); uint32_t total_size = 0; // in blocks for (auto chunk : blob.chunks) { total_size += chunk.size; } assert(total_size > 0); value->resize(total_size * block_size_); uint64_t offset = 0; // in bytes, not blocks for (auto chunk : blob.chunks) { Slice result; assert(chunk.bucket_id < buckets_.size()); Status s; s = buckets_[chunk.bucket_id].get()->Read(chunk.offset * block_size_, chunk.size * block_size_, &result, &value->at(offset)); if (!s.ok() || result.size() < chunk.size * block_size_) { value->clear(); return Status::IOError("Could not read in from file"); } offset += chunk.size * block_size_; } // remove the '\0's at the end of the string value->erase(find(value->begin(), value->end(), '\0'), value->end()); return Status::OK(); } Status BlobStore::Delete(const Blob& blob) { return free_list_.Free(blob); } Status BlobStore::Allocate(uint32_t blocks, Blob* blob) { // TODO we don't currently support fragmented blobs MutexLock l(&allocate_mutex_); assert(blocks <= blocks_per_bucket_); Status s; s = free_list_.Allocate(blocks, blob); if (!s.ok()) { CreateNewBucket(); s = free_list_.Allocate(blocks, blob); } return s; } Status BlobStore::CreateNewBucket() { int new_bucket_id; new_bucket_id = buckets_.size(); buckets_.push_back(unique_ptr<RandomRWFile>()); char fname[200]; sprintf(fname, "%s/%d.bs", directory_.c_str(), new_bucket_id); Status s = env_->NewRandomRWFile(string(fname), &buckets_[new_bucket_id], storage_options_); if (!s.ok()) { buckets_.erase(buckets_.begin() + new_bucket_id); return s; } s = buckets_[new_bucket_id].get()->Allocate( 0, block_size_ * blocks_per_bucket_); if (!s.ok()) { buckets_.erase(buckets_.begin() + new_bucket_id); return s; } return free_list_.Free(Blob(new_bucket_id, 0, blocks_per_bucket_)); } } // namespace rocksdb <commit_msg>tmpfs does not support fallocate<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/blob_store.h" namespace rocksdb { using namespace std; // BlobChunk bool BlobChunk::ImmediatelyBefore(const BlobChunk& chunk) const { // overlapping!? assert(!Overlap(chunk)); // size == 0 is a marker, not a block return size != 0 && bucket_id == chunk.bucket_id && offset + size == chunk.offset; } bool BlobChunk::Overlap(const BlobChunk &chunk) const { return size != 0 && chunk.size != 0 && bucket_id == chunk.bucket_id && ((offset >= chunk.offset && offset < chunk.offset + chunk.size) || (chunk.offset >= offset && chunk.offset < offset + size)); } // Blob string Blob::ToString() const { string ret; for (auto chunk : chunks) { PutFixed32(&ret, chunk.bucket_id); PutFixed32(&ret, chunk.offset); PutFixed32(&ret, chunk.size); } return ret; } Blob::Blob(const std::string& blob) { for (uint32_t i = 0; i < blob.size(); ) { uint32_t t[3] = {0}; for (int j = 0; j < 3 && i + sizeof(uint32_t) - 1 < blob.size(); ++j, i += sizeof(uint32_t)) { t[j] = DecodeFixed32(blob.data() + i); } chunks.push_back(BlobChunk(t[0], t[1], t[2])); } } // FreeList FreeList::FreeList() { // We add (0, 0, 0) blob because it makes our life easier and // code cleaner. (0, 0, 0) is always in the list so we can // guarantee that free_chunks_list_ != nullptr, which avoids // lots of unnecessary ifs free_chunks_list_ = (FreeChunk *)malloc(sizeof(FreeChunk)); free_chunks_list_->chunk = BlobChunk(0, 0, 0); free_chunks_list_->next = nullptr; } FreeList::~FreeList() { while (free_chunks_list_ != nullptr) { FreeChunk* t = free_chunks_list_; free_chunks_list_ = free_chunks_list_->next; free(t); } } Status FreeList::Free(const Blob& blob) { MutexLock l(&mutex_); // add it back to the free list for (auto chunk : blob.chunks) { FreeChunk* itr = free_chunks_list_; // find a node AFTER which we'll add the block for ( ; itr->next != nullptr && itr->next->chunk <= chunk; itr = itr->next) { } // try to merge with previous block if (itr->chunk.ImmediatelyBefore(chunk)) { // merge itr->chunk.size += chunk.size; } else { // Insert the block after itr FreeChunk* t = (FreeChunk*)malloc(sizeof(FreeChunk)); if (t == nullptr) { throw runtime_error("Malloc failed"); } t->chunk = chunk; t->next = itr->next; itr->next = t; itr = t; } // try to merge with the next block if (itr->next != nullptr && itr->chunk.ImmediatelyBefore(itr->next->chunk)) { FreeChunk *tobedeleted = itr->next; itr->chunk.size += itr->next->chunk.size; itr->next = itr->next->next; free(tobedeleted); } } return Status::OK(); } Status FreeList::Allocate(uint32_t blocks, Blob* blob) { MutexLock l(&mutex_); FreeChunk** best_fit_node = nullptr; // Find the smallest free chunk whose size is greater or equal to blocks for (FreeChunk** itr = &free_chunks_list_; (*itr) != nullptr; itr = &((*itr)->next)) { if ((*itr)->chunk.size >= blocks && (best_fit_node == nullptr || (*best_fit_node)->chunk.size > (*itr)->chunk.size)) { best_fit_node = itr; } } if (best_fit_node == nullptr || *best_fit_node == nullptr) { // Not enough memory return Status::Incomplete(""); } blob->SetOneChunk((*best_fit_node)->chunk.bucket_id, (*best_fit_node)->chunk.offset, blocks); if ((*best_fit_node)->chunk.size > blocks) { // just shorten best_fit_node (*best_fit_node)->chunk.offset += blocks; (*best_fit_node)->chunk.size -= blocks; } else { assert(blocks == (*best_fit_node)->chunk.size); // delete best_fit_node FreeChunk* t = *best_fit_node; (*best_fit_node) = (*best_fit_node)->next; free(t); } return Status::OK(); } bool FreeList::Overlap(const Blob &blob) const { MutexLock l(&mutex_); for (auto chunk : blob.chunks) { for (auto itr = free_chunks_list_; itr != nullptr; itr = itr->next) { if (itr->chunk.Overlap(chunk)) { return true; } } } return false; } // BlobStore BlobStore::BlobStore(const string& directory, uint64_t block_size, uint32_t blocks_per_bucket, Env* env) : directory_(directory), block_size_(block_size), blocks_per_bucket_(blocks_per_bucket), env_(env) { env_->CreateDirIfMissing(directory_); storage_options_.use_mmap_writes = false; storage_options_.use_mmap_reads = false; CreateNewBucket(); } BlobStore::~BlobStore() { // TODO we don't care about recovery for now } Status BlobStore::Put(const char* value, uint64_t size, Blob* blob) { // convert size to number of blocks Status s = Allocate((size + block_size_ - 1) / block_size_, blob); if (!s.ok()) { return s; } uint64_t offset = 0; // in bytes, not blocks for (auto chunk : blob->chunks) { uint64_t write_size = min(chunk.size * block_size_, size); assert(chunk.bucket_id < buckets_.size()); s = buckets_[chunk.bucket_id].get()->Write(chunk.offset * block_size_, Slice(value + offset, write_size)); if (!s.ok()) { Delete(*blob); return s; } offset += write_size; size -= write_size; if (write_size < chunk.size * block_size_) { // if we have any space left in the block, fill it up with zeros string zero_string(chunk.size * block_size_ - write_size, 0); s = buckets_[chunk.bucket_id].get()->Write(chunk.offset * block_size_ + write_size, Slice(zero_string)); } } if (size > 0) { Delete(*blob); return Status::IOError("Tried to write more data than fits in the blob"); } return Status::OK(); } Status BlobStore::Get(const Blob& blob, string* value) const { // assert that it doesn't overlap with free list // it will get compiled out for release assert(!free_list_.Overlap(blob)); uint32_t total_size = 0; // in blocks for (auto chunk : blob.chunks) { total_size += chunk.size; } assert(total_size > 0); value->resize(total_size * block_size_); uint64_t offset = 0; // in bytes, not blocks for (auto chunk : blob.chunks) { Slice result; assert(chunk.bucket_id < buckets_.size()); Status s; s = buckets_[chunk.bucket_id].get()->Read(chunk.offset * block_size_, chunk.size * block_size_, &result, &value->at(offset)); if (!s.ok() || result.size() < chunk.size * block_size_) { value->clear(); return Status::IOError("Could not read in from file"); } offset += chunk.size * block_size_; } // remove the '\0's at the end of the string value->erase(find(value->begin(), value->end(), '\0'), value->end()); return Status::OK(); } Status BlobStore::Delete(const Blob& blob) { return free_list_.Free(blob); } Status BlobStore::Allocate(uint32_t blocks, Blob* blob) { // TODO we don't currently support fragmented blobs MutexLock l(&allocate_mutex_); assert(blocks <= blocks_per_bucket_); Status s; s = free_list_.Allocate(blocks, blob); if (!s.ok()) { s = CreateNewBucket(); if (!s.ok()) { return s; } s = free_list_.Allocate(blocks, blob); } return s; } Status BlobStore::CreateNewBucket() { int new_bucket_id; new_bucket_id = buckets_.size(); buckets_.push_back(unique_ptr<RandomRWFile>()); char fname[200]; sprintf(fname, "%s/%d.bs", directory_.c_str(), new_bucket_id); Status s = env_->NewRandomRWFile(string(fname), &buckets_[new_bucket_id], storage_options_); if (!s.ok()) { buckets_.erase(buckets_.begin() + new_bucket_id); return s; } // tmpfs does not support allocate buckets_[new_bucket_id].get()->Allocate(0, block_size_ * blocks_per_bucket_); return free_list_.Free(Blob(new_bucket_id, 0, blocks_per_bucket_)); } } // namespace rocksdb <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2018 Inviwo Foundation * 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 <modules/basegl/processors/background.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/image/imagegl.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/inviwoopengl.h> namespace inviwo { const ProcessorInfo Background::processorInfo_{ "org.inviwo.Background", // Class identifier "Background", // Display name "Image Operation", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo Background::getProcessorInfo() const { return processorInfo_; } Background::Background() : Processor() , inport_("inport") , outport_("outport") , backgroundStyle_("backgroundStyle", "Style", {{"linearGradientVertical", "Linear gradient (Vertical)", BackgroundStyle::LinearVertical}, {"linearGradientHorizontal", "Linear gradient (Horizontal)", BackgroundStyle::LinearHorizontal}, { "linearGradientSpherical", "Linear gradient (Spherical)", BackgroundStyle::LinearSpherical }, {"uniformColor", "Uniform color", BackgroundStyle::Uniform}, {"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}}, 0, InvalidationLevel::InvalidResources) , bgColor1_("bgColor1", "Color 1", vec4(0.0f, 0.0f, 0.0f, 1.0f)) , bgColor2_("bgColor2", "Color 2", vec4(1.0f)) , checkerBoardSize_("checkerBoardSize", "Checker Board Size", ivec2(10, 10), ivec2(1, 1), ivec2(256, 256)) , switchColors_("switchColors", "Switch Colors", InvalidationLevel::Valid) , blendMode_("blendMode", "Blend mode", {{"backtofront", "Back To Front (Pre-multiplied)", BlendMode::BackToFront}, {"alphamixing", "Alpha Mixing", BlendMode::AlphaMixing}}, 0, InvalidationLevel::InvalidResources) , shader_("background.frag", false) { addPort(inport_); addPort(outport_); inport_.setOptional(true); addProperty(backgroundStyle_); bgColor1_.setSemantics(PropertySemantics::Color); addProperty(bgColor1_); bgColor2_.setSemantics(PropertySemantics::Color); addProperty(bgColor2_); addProperty(checkerBoardSize_); addProperty(switchColors_); addProperty(blendMode_); switchColors_.onChange([&]() { vec4 tmp = bgColor1_.get(); bgColor1_.set(bgColor2_.get()); bgColor2_.set(tmp); }); shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); } Background::~Background() = default; void Background::initializeResources() { std::string bgStyleValue; switch (backgroundStyle_.get()) { default: case BackgroundStyle::LinearVertical: // linear gradient bgStyleValue = "linearGradientVertical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearHorizontal: // linear gradient bgStyleValue = "linearGradientHorizontal(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearSpherical: // linear spherical gradient bgStyleValue = "linearGradientSpherical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::Uniform: // uniform color bgStyleValue = "bgColor1"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::CheckerBoard: // checker board bgStyleValue = "checkerBoard(texCoord)"; checkerBoardSize_.setVisible(true); break; } shader_.getFragmentShaderObject()->addShaderDefine("BACKGROUND_STYLE_FUNCTION", bgStyleValue); if (inport_.hasData()) { shader_.getFragmentShaderObject()->addShaderDefine("SRC_COLOR", "texture(inportColor, texCoord)"); // set shader inputs to match number of available color layers updateShaderInputs(); shader_.getFragmentShaderObject()->addShaderDefine("PICKING_LAYER"); shader_.getFragmentShaderObject()->addShaderDefine("DEPTH_LAYER"); hadData_ = true; } else { shader_.getFragmentShaderObject()->addShaderDefine("SRC_COLOR", "vec4(0)"); shader_.getFragmentShaderObject()->removeShaderDefine("PICKING_LAYER"); shader_.getFragmentShaderObject()->removeShaderDefine("DEPTH_LAYER"); hadData_ = false; } std::string blendfunc = ""; switch (blendMode_.get()) { case BlendMode::BackToFront: blendfunc = "blendBackToFront"; break; default: case BlendMode::AlphaMixing: blendfunc = "blendAlphaCompositing"; break; } shader_.getFragmentShaderObject()->addShaderDefine("BLENDFUNC", blendfunc); shader_.build(); } void Background::process() { if (inport_.hasData() != hadData_) initializeResources(); if (inport_.hasData()) { // Check data format, make sure we always have 4 channels auto inDataFromat = inport_.getData()->getDataFormat(); auto format = DataFormatBase::get(inDataFromat->getNumericType(), 4, inDataFromat->getSize() * 8 / inDataFromat->getComponents()); if (outport_.getData()->getDataFormat() != format) { outport_.setData(std::make_shared<Image>(outport_.getDimensions(), format)); } } utilgl::activateTarget(outport_, ImageType::AllLayers); shader_.activate(); if (inport_.hasData()) { TextureUnitContainer textureUnits; auto image = inport_.getData(); utilgl::bindAndSetUniforms(shader_, textureUnits, inport_, ImageType::AllLayers); { // bind all additional color layers const auto numColorLayers = image->getNumberOfColorLayers(); auto imageGL = image->getRepresentation<ImageGL>(); for (size_t i = 1; i < numColorLayers; ++i) { TextureUnit texUnit; imageGL->getColorLayerGL(i)->bindTexture(texUnit.getEnum()); shader_.setUniform("color" + toString<size_t>(i), texUnit.getUnitNumber()); textureUnits.push_back(std::move(texUnit)); } } } utilgl::setUniforms(shader_, outport_, bgColor1_, bgColor2_, checkerBoardSize_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void Background::updateShaderInputs() { const auto numColorLayers = inport_.getData()->getNumberOfColorLayers(); if (numColorLayers > 1) { // location 0 is reserved for FragData0, location 1 for PickingData size_t outputLocation = 2; std::stringstream ssUniform; ssUniform << "\n"; for (size_t i = 1; i < numColorLayers; ++i) { ssUniform << "layout(location = " << outputLocation++ << ") out vec4 FragData" << i << ";\n"; } for (size_t i = 1; i < numColorLayers; ++i) { ssUniform << "uniform sampler2D color" << i << ";\n"; } shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS", ssUniform.str()); std::stringstream ssWrite; for (size_t i = 1; i < numColorLayers; ++i) { ssWrite << "FragData" << i << " = texture(color" << i << ", texCoord.xy);"; if(i<numColorLayers-1){ ssWrite << " \\"; } ssWrite << "\n"; } shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE", ssWrite.str()); shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYERS"); } else { shader_.getFragmentShaderObject()->removeShaderDefine("ADDITIONAL_COLOR_LAYERS"); shader_.getFragmentShaderObject()->removeShaderDefine( "ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS"); shader_.getFragmentShaderObject()->removeShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE"); } } } // namespace <commit_msg>BaseGL: fix for #236 * replaced hasData() with isReady()<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2018 Inviwo Foundation * 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 <modules/basegl/processors/background.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/image/imagegl.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/inviwoopengl.h> namespace inviwo { const ProcessorInfo Background::processorInfo_{ "org.inviwo.Background", // Class identifier "Background", // Display name "Image Operation", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo Background::getProcessorInfo() const { return processorInfo_; } Background::Background() : Processor() , inport_("inport") , outport_("outport") , backgroundStyle_("backgroundStyle", "Style", {{"linearGradientVertical", "Linear gradient (Vertical)", BackgroundStyle::LinearVertical}, {"linearGradientHorizontal", "Linear gradient (Horizontal)", BackgroundStyle::LinearHorizontal}, { "linearGradientSpherical", "Linear gradient (Spherical)", BackgroundStyle::LinearSpherical }, {"uniformColor", "Uniform color", BackgroundStyle::Uniform}, {"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}}, 0, InvalidationLevel::InvalidResources) , bgColor1_("bgColor1", "Color 1", vec4(0.0f, 0.0f, 0.0f, 1.0f)) , bgColor2_("bgColor2", "Color 2", vec4(1.0f)) , checkerBoardSize_("checkerBoardSize", "Checker Board Size", ivec2(10, 10), ivec2(1, 1), ivec2(256, 256)) , switchColors_("switchColors", "Switch Colors", InvalidationLevel::Valid) , blendMode_("blendMode", "Blend mode", {{"backtofront", "Back To Front (Pre-multiplied)", BlendMode::BackToFront}, {"alphamixing", "Alpha Mixing", BlendMode::AlphaMixing}}, 0, InvalidationLevel::InvalidResources) , shader_("background.frag", false) { addPort(inport_); addPort(outport_); inport_.setOptional(true); addProperty(backgroundStyle_); bgColor1_.setSemantics(PropertySemantics::Color); addProperty(bgColor1_); bgColor2_.setSemantics(PropertySemantics::Color); addProperty(bgColor2_); addProperty(checkerBoardSize_); addProperty(switchColors_); addProperty(blendMode_); switchColors_.onChange([&]() { vec4 tmp = bgColor1_.get(); bgColor1_.set(bgColor2_.get()); bgColor2_.set(tmp); }); shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); } Background::~Background() = default; void Background::initializeResources() { std::string bgStyleValue; switch (backgroundStyle_.get()) { default: case BackgroundStyle::LinearVertical: // linear gradient bgStyleValue = "linearGradientVertical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearHorizontal: // linear gradient bgStyleValue = "linearGradientHorizontal(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearSpherical: // linear spherical gradient bgStyleValue = "linearGradientSpherical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::Uniform: // uniform color bgStyleValue = "bgColor1"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::CheckerBoard: // checker board bgStyleValue = "checkerBoard(texCoord)"; checkerBoardSize_.setVisible(true); break; } shader_.getFragmentShaderObject()->addShaderDefine("BACKGROUND_STYLE_FUNCTION", bgStyleValue); if (inport_.isReady()) { shader_.getFragmentShaderObject()->addShaderDefine("SRC_COLOR", "texture(inportColor, texCoord)"); // set shader inputs to match number of available color layers updateShaderInputs(); shader_.getFragmentShaderObject()->addShaderDefine("PICKING_LAYER"); shader_.getFragmentShaderObject()->addShaderDefine("DEPTH_LAYER"); hadData_ = true; } else { shader_.getFragmentShaderObject()->addShaderDefine("SRC_COLOR", "vec4(0)"); shader_.getFragmentShaderObject()->removeShaderDefine("PICKING_LAYER"); shader_.getFragmentShaderObject()->removeShaderDefine("DEPTH_LAYER"); hadData_ = false; } std::string blendfunc = ""; switch (blendMode_.get()) { case BlendMode::BackToFront: blendfunc = "blendBackToFront"; break; default: case BlendMode::AlphaMixing: blendfunc = "blendAlphaCompositing"; break; } shader_.getFragmentShaderObject()->addShaderDefine("BLENDFUNC", blendfunc); shader_.build(); } void Background::process() { if (inport_.isReady() != hadData_) initializeResources(); if (inport_.isReady()) { // Check data format, make sure we always have 4 channels auto inDataFromat = inport_.getData()->getDataFormat(); auto format = DataFormatBase::get(inDataFromat->getNumericType(), 4, inDataFromat->getSize() * 8 / inDataFromat->getComponents()); if (outport_.getData()->getDataFormat() != format) { outport_.setData(std::make_shared<Image>(outport_.getDimensions(), format)); } } utilgl::activateTarget(outport_, ImageType::AllLayers); shader_.activate(); if (inport_.isReady()) { TextureUnitContainer textureUnits; auto image = inport_.getData(); utilgl::bindAndSetUniforms(shader_, textureUnits, inport_, ImageType::AllLayers); { // bind all additional color layers const auto numColorLayers = image->getNumberOfColorLayers(); auto imageGL = image->getRepresentation<ImageGL>(); for (size_t i = 1; i < numColorLayers; ++i) { TextureUnit texUnit; imageGL->getColorLayerGL(i)->bindTexture(texUnit.getEnum()); shader_.setUniform("color" + toString<size_t>(i), texUnit.getUnitNumber()); textureUnits.push_back(std::move(texUnit)); } } } utilgl::setUniforms(shader_, outport_, bgColor1_, bgColor2_, checkerBoardSize_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void Background::updateShaderInputs() { const auto numColorLayers = inport_.getData()->getNumberOfColorLayers(); if (numColorLayers > 1) { // location 0 is reserved for FragData0, location 1 for PickingData size_t outputLocation = 2; std::stringstream ssUniform; ssUniform << "\n"; for (size_t i = 1; i < numColorLayers; ++i) { ssUniform << "layout(location = " << outputLocation++ << ") out vec4 FragData" << i << ";\n"; } for (size_t i = 1; i < numColorLayers; ++i) { ssUniform << "uniform sampler2D color" << i << ";\n"; } shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS", ssUniform.str()); std::stringstream ssWrite; for (size_t i = 1; i < numColorLayers; ++i) { ssWrite << "FragData" << i << " = texture(color" << i << ", texCoord.xy);"; if(i<numColorLayers-1){ ssWrite << " \\"; } ssWrite << "\n"; } shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE", ssWrite.str()); shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYERS"); } else { shader_.getFragmentShaderObject()->removeShaderDefine("ADDITIONAL_COLOR_LAYERS"); shader_.getFragmentShaderObject()->removeShaderDefine( "ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS"); shader_.getFragmentShaderObject()->removeShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE"); } } } // namespace <|endoftext|>
<commit_before>// // Level.cpp // ShooterInhertiance // // Created by Marco Gillies on 04/03/2016. // // #include "Level.hpp" #include "ofMain.h" #include "Player.hpp" #include "Enemy.hpp" #include "HealthPickup.hpp" #include "WeaponPickup.hpp" #include "Weapon.hpp" #include "GameOver.hpp" // just calls get Current game state and casts the result to a level // (returns null if the current game state is not a level Level *Level::getCurrentLevel() { Level * currentLevel = dynamic_cast<Level *>(GameState::getCurrentGameState()); return currentLevel; } Level::Level (int enemies, int pickups) :GameState(), numEnemies(enemies), numPickups(pickups), state(not_started) { } Level::~Level() { end(); } // delete all game object at the end of the level void Level::end(){ for(GameObject *go : gameObjects){ delete go; } // removes all contents of the vector // NB does not delete content gameObjects.clear(); } // randomly create game objects at when the level start void Level::start() { state = playing; ofBackground(0, 0, 100); // create a player Player *player = new Player(20, ofGetHeight()/2); player->addWeapon(Weapon(1, 2, 0.1)); gameObjects.push_back(player); // create enemies for (int i = 0; i < numEnemies; i++){ Enemy *enemy = new Enemy(ofRandom(50, 2*ofGetWidth()), // x ofRandom(0, ofGetHeight()), //y ofRandom(5, 20), //health ofRandom(0, 1.0), //speed ofRandom(1,20));//damage gameObjects.push_back(enemy); } // create pickups, randomly choosing between weapon and health pickups for (int i = 0; i < numPickups; i++){ if(ofRandom(1.0) > 0.5f){ HealthPickup *pickup= new HealthPickup(ofRandom(50, ofGetWidth()), // x ofRandom(0, ofGetHeight()), //y ofRandom(5, 20)); //health gameObjects.push_back(pickup); } else { Weapon weapon (ofRandom(1, 10), // damage ofRandom(0, 3.0f), //speed ofRandom(0.0f, 1.0f)); // reload time WeaponPickup *pickup= new WeaponPickup(ofRandom(50, ofGetWidth()), // x ofRandom(0, ofGetHeight()), //y weapon); gameObjects.push_back(pickup); } } } // this draws all of the game objects void Level::draw() { // draw all game objects for (GameObject *go : gameObjects){ go->draw(); } // perform collision between all game objects for(int i = 0; i < gameObjects.size()-1; i++){ // only do game objects after 1 in the inner // loop so you don't collide 2 objects twice for (int j = i+1; j < gameObjects.size(); j++){ gameObjects[i]->collide((gameObjects[j])); } } // remove all dead objects // only do this after the two loops to avoid // invalidated iterators auto toremove = std::remove_if(gameObjects.begin(), gameObjects.end(), [](GameObject *go){ bool dead = !go->isAlive(); // delete any dead game objects if(dead){ delete go; } return dead; }); gameObjects.erase(toremove, gameObjects.end()); // if we are in the faild state go to gamover // only do this after the main loops to avoid // acting on deleted objects if(state == failed){ GameState::setGameState(GameState::getNumGameStates()); //GameOver::goToGameOver(); state = not_started; } // if we have completed the level go to the // next on, or back to the start // screen if we have completed all levels if(state == complete){ GameState::nextGameState(); if(getCurrentLevel() == nullptr){ GameState::setGameState(0); } state = not_started; } } // pass on the keypress to all of the game objects void Level::keyPressed(int key) { for (int i = 0; i < gameObjects.size(); i++){ gameObjects[i]->keyPressed(key); } } <commit_msg>deleting game objects properly<commit_after>// // Level.cpp // ShooterInhertiance // // Created by Marco Gillies on 04/03/2016. // // #include "Level.hpp" #include "ofMain.h" #include "Player.hpp" #include "Enemy.hpp" #include "HealthPickup.hpp" #include "WeaponPickup.hpp" #include "Weapon.hpp" #include "GameOver.hpp" // just calls get Current game state and casts the result to a level // (returns null if the current game state is not a level Level *Level::getCurrentLevel() { Level * currentLevel = dynamic_cast<Level *>(GameState::getCurrentGameState()); return currentLevel; } Level::Level (int enemies, int pickups) :GameState(), numEnemies(enemies), numPickups(pickups), state(not_started) { } Level::~Level() { end(); } // delete all game object at the end of the level void Level::end(){ for(GameObject *go : gameObjects){ delete go; } // removes all contents of the vector // NB does not delete content gameObjects.clear(); } // randomly create game objects at when the level start void Level::start() { state = playing; ofBackground(0, 0, 100); // create a player Player *player = new Player(20, ofGetHeight()/2); player->addWeapon(Weapon(1, 2, 0.1)); gameObjects.push_back(player); // create enemies for (int i = 0; i < numEnemies; i++){ Enemy *enemy = new Enemy(ofRandom(50, 2*ofGetWidth()), // x ofRandom(0, ofGetHeight()), //y ofRandom(5, 20), //health ofRandom(0, 1.0), //speed ofRandom(1,20));//damage gameObjects.push_back(enemy); } // create pickups, randomly choosing between weapon and health pickups for (int i = 0; i < numPickups; i++){ if(ofRandom(1.0) > 0.5f){ HealthPickup *pickup= new HealthPickup(ofRandom(50, ofGetWidth()), // x ofRandom(0, ofGetHeight()), //y ofRandom(5, 20)); //health gameObjects.push_back(pickup); } else { Weapon weapon (ofRandom(1, 10), // damage ofRandom(0, 3.0f), //speed ofRandom(0.0f, 1.0f)); // reload time WeaponPickup *pickup= new WeaponPickup(ofRandom(50, ofGetWidth()), // x ofRandom(0, ofGetHeight()), //y weapon); gameObjects.push_back(pickup); } } } // this draws all of the game objects void Level::draw() { // draw all game objects for (GameObject *go : gameObjects){ go->draw(); } // perform collision between all game objects for(int i = 0; i < gameObjects.size()-1; i++){ // only do game objects after 1 in the inner // loop so you don't collide 2 objects twice for (int j = i+1; j < gameObjects.size(); j++){ gameObjects[i]->collide((gameObjects[j])); } } // remove all dead objects // only do this after the two loops to avoid // invalidated iterators auto toremove = std::remove_if(gameObjects.begin(), gameObjects.end(), [](GameObject *go){ bool dead = !go->isAlive(); // delete any dead game objects if(dead){ delete go; } return dead; }); gameObjects.erase(toremove, gameObjects.end()); // if we are in the faild state go to gamover // only do this after the main loops to avoid // acting on deleted objects if(state == failed){ //GameState::setGameState(GameState::getNumGameStates()-1); GameOver::goToGameOver(); state = not_started; } // if we have completed the level go to the // next on, or back to the start // screen if we have completed all levels if(state == complete){ GameState::nextGameState(); if(getCurrentLevel() == nullptr){ GameState::setGameState(0); } state = not_started; } } // pass on the keypress to all of the game objects void Level::keyPressed(int key) { for (int i = 0; i < gameObjects.size(); i++){ gameObjects[i]->keyPressed(key); } } <|endoftext|>
<commit_before>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // #include "util/statistics.h" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include "rocksdb/statistics.h" #include "port/likely.h" #include <algorithm> #include <cstdio> namespace rocksdb { std::shared_ptr<Statistics> CreateDBStatistics() { return std::make_shared<StatisticsImpl>(nullptr, false); } StatisticsImpl::StatisticsImpl( std::shared_ptr<Statistics> stats, bool enable_internal_stats) : stats_shared_(stats), stats_(stats.get()), enable_internal_stats_(enable_internal_stats) { } StatisticsImpl::~StatisticsImpl() {} uint64_t StatisticsImpl::getTickerCount(uint32_t tickerType) const { MutexLock lock(&aggregate_lock_); assert( enable_internal_stats_ ? tickerType < INTERNAL_TICKER_ENUM_MAX : tickerType < TICKER_ENUM_MAX); uint64_t thread_local_sum = 0; tickers_[tickerType].thread_value->Fold( [](void* curr_ptr, void* res) { auto* sum_ptr = static_cast<uint64_t*>(res); *sum_ptr += static_cast<std::atomic_uint_fast64_t*>(curr_ptr)->load(); }, &thread_local_sum); return thread_local_sum + tickers_[tickerType].merged_sum.load(); } void StatisticsImpl::histogramData(uint32_t histogramType, HistogramData* const data) const { assert( enable_internal_stats_ ? histogramType < INTERNAL_HISTOGRAM_ENUM_MAX : histogramType < HISTOGRAM_ENUM_MAX); // Return its own ticker version histograms_[histogramType].Data(data); } std::string StatisticsImpl::getHistogramString(uint32_t histogramType) const { assert(enable_internal_stats_ ? histogramType < INTERNAL_HISTOGRAM_ENUM_MAX : histogramType < HISTOGRAM_ENUM_MAX); return histograms_[histogramType].ToString(); } StatisticsImpl::ThreadTickerInfo* StatisticsImpl::getThreadTickerInfo( uint32_t tickerType) { auto info_ptr = static_cast<ThreadTickerInfo*>(tickers_[tickerType].thread_value->Get()); if (info_ptr == nullptr) { info_ptr = new ThreadTickerInfo(0 /* value */, &tickers_[tickerType].merged_sum); tickers_[tickerType].thread_value->Reset(info_ptr); } return info_ptr; } void StatisticsImpl::setTickerCount(uint32_t tickerType, uint64_t count) { { MutexLock lock(&aggregate_lock_); assert(enable_internal_stats_ ? tickerType < INTERNAL_TICKER_ENUM_MAX : tickerType < TICKER_ENUM_MAX); if (tickerType < TICKER_ENUM_MAX || enable_internal_stats_) { tickers_[tickerType].thread_value->Fold( [](void* curr_ptr, void* res) { static_cast<std::atomic<uint64_t>*>(curr_ptr)->store(0); }, nullptr /* res */); tickers_[tickerType].merged_sum.store(count); } } if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->setTickerCount(tickerType, count); } } void StatisticsImpl::recordTick(uint32_t tickerType, uint64_t count) { assert( enable_internal_stats_ ? tickerType < INTERNAL_TICKER_ENUM_MAX : tickerType < TICKER_ENUM_MAX); if (tickerType < TICKER_ENUM_MAX || enable_internal_stats_) { auto info_ptr = getThreadTickerInfo(tickerType); info_ptr->value.fetch_add(count); } if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->recordTick(tickerType, count); } } void StatisticsImpl::measureTime(uint32_t histogramType, uint64_t value) { assert( enable_internal_stats_ ? histogramType < INTERNAL_HISTOGRAM_ENUM_MAX : histogramType < HISTOGRAM_ENUM_MAX); if (histogramType < HISTOGRAM_ENUM_MAX || enable_internal_stats_) { histograms_[histogramType].Add(value); } if (stats_ && histogramType < HISTOGRAM_ENUM_MAX) { stats_->measureTime(histogramType, value); } } namespace { // a buffer size used for temp string buffers const int kBufferSize = 200; } // namespace std::string StatisticsImpl::ToString() const { std::string res; res.reserve(20000); for (const auto& t : TickersNameMap) { if (t.first < TICKER_ENUM_MAX || enable_internal_stats_) { char buffer[kBufferSize]; snprintf(buffer, kBufferSize, "%s COUNT : %" PRIu64 "\n", t.second.c_str(), getTickerCount(t.first)); res.append(buffer); } } for (const auto& h : HistogramsNameMap) { if (h.first < HISTOGRAM_ENUM_MAX || enable_internal_stats_) { char buffer[kBufferSize]; HistogramData hData; histogramData(h.first, &hData); snprintf( buffer, kBufferSize, "%s statistics Percentiles :=> 50 : %f 95 : %f 99 : %f\n", h.second.c_str(), hData.median, hData.percentile95, hData.percentile99); res.append(buffer); } } res.shrink_to_fit(); return res; } bool StatisticsImpl::HistEnabledForType(uint32_t type) const { if (LIKELY(!enable_internal_stats_)) { return type < HISTOGRAM_ENUM_MAX; } return true; } } // namespace rocksdb <commit_msg>Relax consistency for thread-local ticker stats<commit_after>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // #include "util/statistics.h" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include "rocksdb/statistics.h" #include "port/likely.h" #include <algorithm> #include <cstdio> namespace rocksdb { std::shared_ptr<Statistics> CreateDBStatistics() { return std::make_shared<StatisticsImpl>(nullptr, false); } StatisticsImpl::StatisticsImpl( std::shared_ptr<Statistics> stats, bool enable_internal_stats) : stats_shared_(stats), stats_(stats.get()), enable_internal_stats_(enable_internal_stats) { } StatisticsImpl::~StatisticsImpl() {} uint64_t StatisticsImpl::getTickerCount(uint32_t tickerType) const { MutexLock lock(&aggregate_lock_); assert( enable_internal_stats_ ? tickerType < INTERNAL_TICKER_ENUM_MAX : tickerType < TICKER_ENUM_MAX); uint64_t thread_local_sum = 0; tickers_[tickerType].thread_value->Fold( [](void* curr_ptr, void* res) { auto* sum_ptr = static_cast<uint64_t*>(res); *sum_ptr += static_cast<std::atomic_uint_fast64_t*>(curr_ptr)->load( std::memory_order_relaxed); }, &thread_local_sum); return thread_local_sum + tickers_[tickerType].merged_sum.load(std::memory_order_relaxed); } void StatisticsImpl::histogramData(uint32_t histogramType, HistogramData* const data) const { assert( enable_internal_stats_ ? histogramType < INTERNAL_HISTOGRAM_ENUM_MAX : histogramType < HISTOGRAM_ENUM_MAX); // Return its own ticker version histograms_[histogramType].Data(data); } std::string StatisticsImpl::getHistogramString(uint32_t histogramType) const { assert(enable_internal_stats_ ? histogramType < INTERNAL_HISTOGRAM_ENUM_MAX : histogramType < HISTOGRAM_ENUM_MAX); return histograms_[histogramType].ToString(); } StatisticsImpl::ThreadTickerInfo* StatisticsImpl::getThreadTickerInfo( uint32_t tickerType) { auto info_ptr = static_cast<ThreadTickerInfo*>(tickers_[tickerType].thread_value->Get()); if (info_ptr == nullptr) { info_ptr = new ThreadTickerInfo(0 /* value */, &tickers_[tickerType].merged_sum); tickers_[tickerType].thread_value->Reset(info_ptr); } return info_ptr; } void StatisticsImpl::setTickerCount(uint32_t tickerType, uint64_t count) { { MutexLock lock(&aggregate_lock_); assert(enable_internal_stats_ ? tickerType < INTERNAL_TICKER_ENUM_MAX : tickerType < TICKER_ENUM_MAX); if (tickerType < TICKER_ENUM_MAX || enable_internal_stats_) { tickers_[tickerType].thread_value->Fold( [](void* curr_ptr, void* res) { static_cast<std::atomic<uint64_t>*>(curr_ptr)->store( 0, std::memory_order_relaxed); }, nullptr /* res */); tickers_[tickerType].merged_sum.store(count, std::memory_order_relaxed); } } if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->setTickerCount(tickerType, count); } } void StatisticsImpl::recordTick(uint32_t tickerType, uint64_t count) { assert( enable_internal_stats_ ? tickerType < INTERNAL_TICKER_ENUM_MAX : tickerType < TICKER_ENUM_MAX); if (tickerType < TICKER_ENUM_MAX || enable_internal_stats_) { auto info_ptr = getThreadTickerInfo(tickerType); info_ptr->value.fetch_add(count, std::memory_order_relaxed); } if (stats_ && tickerType < TICKER_ENUM_MAX) { stats_->recordTick(tickerType, count); } } void StatisticsImpl::measureTime(uint32_t histogramType, uint64_t value) { assert( enable_internal_stats_ ? histogramType < INTERNAL_HISTOGRAM_ENUM_MAX : histogramType < HISTOGRAM_ENUM_MAX); if (histogramType < HISTOGRAM_ENUM_MAX || enable_internal_stats_) { histograms_[histogramType].Add(value); } if (stats_ && histogramType < HISTOGRAM_ENUM_MAX) { stats_->measureTime(histogramType, value); } } namespace { // a buffer size used for temp string buffers const int kBufferSize = 200; } // namespace std::string StatisticsImpl::ToString() const { std::string res; res.reserve(20000); for (const auto& t : TickersNameMap) { if (t.first < TICKER_ENUM_MAX || enable_internal_stats_) { char buffer[kBufferSize]; snprintf(buffer, kBufferSize, "%s COUNT : %" PRIu64 "\n", t.second.c_str(), getTickerCount(t.first)); res.append(buffer); } } for (const auto& h : HistogramsNameMap) { if (h.first < HISTOGRAM_ENUM_MAX || enable_internal_stats_) { char buffer[kBufferSize]; HistogramData hData; histogramData(h.first, &hData); snprintf( buffer, kBufferSize, "%s statistics Percentiles :=> 50 : %f 95 : %f 99 : %f\n", h.second.c_str(), hData.median, hData.percentile95, hData.percentile99); res.append(buffer); } } res.shrink_to_fit(); return res; } bool StatisticsImpl::HistEnabledForType(uint32_t type) const { if (LIKELY(!enable_internal_stats_)) { return type < HISTOGRAM_ENUM_MAX; } return true; } } // namespace rocksdb <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include <boost/circular_buffer.hpp> namespace utils { template<typename T> class histogram { public: int64_t count; T min; T max; T sum; double mean; double variance; boost::circular_buffer<T> sample; histogram(size_t size = 1024) : count(0), min(0), max(0), sum(0), mean(0), variance(0), sample( size) { } void mark(T value) { if (count == 0 || value < min) { min = value; } if (count == 0 || value > max) { max = value; } if (count == 0) { mean = value; variance = 0; } else { double old_m = mean; double old_s = variance; mean = old_m + ((value - old_m) / (count + 1)); variance = old_s + ((value - old_m) * (value - mean)); } sum += value; count++; sample.push_back(value); } }; using ihistogram = histogram<int64_t>; } <commit_msg>Utils: Support sample based histogram<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include <boost/circular_buffer.hpp> #include "latency.hh" namespace utils { class ihistogram { public: // count holds all the events int64_t count; // total holds only the events we sample int64_t total; int64_t min; int64_t max; int64_t sum; double mean; double variance; int64_t sample_mask; boost::circular_buffer<int64_t> sample; ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80) : count(0), total(0), min(0), max(0), sum(0), mean(0), variance(0), sample_mask(_sample_mask), sample( size) { } void mark(int64_t value) { if (total == 0 || value < min) { min = value; } if (total == 0 || value > max) { max = value; } if (total == 0) { mean = value; variance = 0; } else { double old_m = mean; double old_s = variance; mean = old_m + ((value - old_m) / (total + 1)); variance = old_s + ((value - old_m) * (value - mean)); } sum += value; total++; count++; sample.push_back(value); } void mark(latency_counter& lc) { if (lc.is_start()) { mark(lc.stop().latency_in_nano()); } else { count++; } } /** * Return true if the current event should be sample. * In the typical case, there is no need to use this method * Call set_latency, that would start a latency object if needed. */ bool should_sample() const { return total & sample_mask; } /** * Set the latency according to the sample rate. */ ihistogram& set_latency(latency_counter& lc) { if (should_sample()) { lc.start(); } return *this; } /** * Allow to use the histogram as a counter * Increment the total number of events without * sampling the value. */ ihistogram& inc() { count++; return *this; } }; } <|endoftext|>
<commit_before>#ifndef USTR_MEM_POOL_TCC_ #define USTR_MEM_POOL_TCC_ namespace ustr { template<class T, size_t block_size> inline typename MemoryPool<T, block_size>::size_type MemoryPool<T, block_size>::pad_pointer(data_pointer p, size_type align) { uintptr_t result = reinterpret_cast<uintptr_t>(p); return ((align - result) % align); } template<class T, size_t block_size> typename MemoryPool<T, block_size>::MemoryPool() noexcept : cur_block_(nullptr), cur_slot_(nullptr), last_slot_(nullptr), free_slot_(nullptr) {} template<class T, size_t block_size> MemoryPool::~MemoryPool() noexcept { slot_pointer curr = cur_block_; while(curr != nullptr){ slot_pointer prev = curr->next; operator delete ( reinterpret_cast<void *>(curr) ); curr = prev; } } template <class T, size_t block_size> inline typename MemoryPool<T, block_size>::pointer MemoryPool<T, block_size>::address(reference x) noexcept { return &x; } template <class T, size_t block_size> inline typename MemoryPool<T, block_size>::const_pointer MemoryPool<T, block_size>::address(const_reference x) noexcept { return &x; } template<class T, size_t block_size> void MemoryPool<T,block_size>::allocate_block() { data_pointer new_block = reinterpret_cast<data_pointer>(operator new(block_size)); reinterpret_cast<slot_pointer>(new_block)->next = cur_block_; cur_block_ = reinterpret_cast<slot_pointer>(new_block); data_pointer body = new_block + sizeof(slot_pointer); size_type body_padding = pad_pointer(body, alignof(slot_type)); cur_slot_ = reinterpret_cast<slot_pointer>(body + body_padding); last_slot_ = reinterpret_cast<slot_pointer>(new_block + block_size - sizeof(slot_type) + 1); } template<class T, size_t block_size> inline typename MemoryPool<T, block_size>::pointer MemoryPool<T, block_size>::allocate(size_type n, const pointer hint) { if(n == 1 && free_slots != nullptr){ pointer result = reinterpret_cast<pointer>(free_slots); free_slots = free_slots->next; reinterpret_cast<slot_type>(result)->next = nullptr; return result; } if(current_slot + n >= last_slot){ allocate_block(); } /* Link the block memory into list*/ /* Convinience for free*/ slot_pointer p = current_slot; for(size_type i = 0; i < n - 1; i++){ (p + i)->next = (p + i + 1); } (p + n)->next = nullptr; pointer result = reinterpret_cast<pointer>(current_slot); current_slot += n; return result; } }//namespace ustr #endif <commit_msg>Update mem_pool.tcc<commit_after>#ifndef USTR_MEM_POOL_TCC_ #define USTR_MEM_POOL_TCC_ namespace ustr { template<class T, size_t block_size> inline typename MemoryPool<T, block_size>::size_type MemoryPool<T, block_size>::pad_pointer(data_pointer p, size_type align) { uintptr_t result = reinterpret_cast<uintptr_t>(p); return ((align - result) % align); } template<class T, size_t block_size> typename MemoryPool<T, block_size>::MemoryPool() noexcept : cur_block_(nullptr), cur_slot_(nullptr), last_slot_(nullptr), free_slot_(nullptr) {} template<class T, size_t block_size> MemoryPool::~MemoryPool() noexcept { slot_pointer curr = cur_block_; while(curr != nullptr){ slot_pointer prev = curr->next; operator delete ( reinterpret_cast<void *>(curr) ); curr = prev; } } template <class T, size_t block_size> inline typename MemoryPool<T, block_size>::pointer MemoryPool<T, block_size>::address(reference x) noexcept { return &x; } template <class T, size_t block_size> inline typename MemoryPool<T, block_size>::const_pointer MemoryPool<T, block_size>::address(const_reference x) noexcept { return &x; } template<class T, size_t block_size> void MemoryPool<T,block_size>::allocate_block() { data_pointer new_block = reinterpret_cast<data_pointer>(operator new(block_size)); reinterpret_cast<slot_pointer>(new_block)->next = cur_block_; cur_block_ = reinterpret_cast<slot_pointer>(new_block); data_pointer body = new_block + sizeof(slot_pointer); size_type body_padding = pad_pointer(body, alignof(slot_type)); cur_slot_ = reinterpret_cast<slot_pointer>(body + body_padding); last_slot_ = reinterpret_cast<slot_pointer>(new_block + block_size - sizeof(slot_type) + 1); } template<class T, size_t block_size> inline typename MemoryPool<T, block_size>::pointer MemoryPool<T, block_size>::allocate(size_type n, const pointer hint) { if(n == 1 && free_slots != nullptr){ pointer result = reinterpret_cast<pointer>(free_slots); free_slots = free_slots->next; reinterpret_cast<slot_type>(result)->next = nullptr; return result; } if(current_slot + n >= last_slot){ allocate_block(); } /* Link the block memory into list*/ /* Convinience for free*/ slot_pointer p = current_slot; for(size_type i = 0; i < n - 1; i++){ (p + i)->next = (p + i + 1); } (p + n)->next = nullptr; pointer result = reinterpret_cast<pointer>(current_slot); current_slot += n; return result; } template<class T, size_t block_size> inline void MemoryPool<T,block_size>::deallocate(pointer ptr, size_type n) { if(!ptr) return; slot_pointer head = reinterpret_cast<slot_pointer>(p); slot_pointer p = head; while(p->next) p = p->next; p->next = free_slot_; free_slot_ = head; } template<class T, size_t block_size> inline typename MemoryPool<T, block_size>::size_type MemoryPool<T, block_size>::max_size() const noexcept { size_type max_block = -1 / block_size; return (block_size - sizeof(data_pointer)) / sizeof(slot_type) * max_block; } template<typename T, size_type block_size> template<typename U, class... Args> inline void MemoryPool<T, block_size>::construct(U *p, Args&&... args) { new(p) U (std::forward<Args>(args)...); } template<class T, size_type block_size> template<class U> inline void MemoryPool<T, block_size>::destroy(U *p) { p->~U(); } template<class T, size_t block_size> template<class... Args> inline typename MemoryPool<T,block_size>::pointer MemoryPool<T,block_size>::new_element(Args&&... args) { pointer p = allocate(); construct<value_type>(p, std::forward<Args>(args)...); return p; } template<class T, size_t block_size> inline void MemoryPool<T, block_size>::delete_element(pointer p) { if(!p) return; p->~value_type(); deallocate(p); } }//namespace ustr #endif <|endoftext|>
<commit_before>// #include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sys/stat.h> #include <math.h> #include <algorithm> #include <string.h> #include <stdint.h> #include <sstream> #include <iomanip> #include <gdal/gdal_priv.h> #include <gdal/cpl_conv.h> #include <gdal/ogr_spatialref.h> using namespace std; //to compile: c++ raster_math.cpp -o raster_math -lgdal // ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt int main(int argc, char* argv[]) { //passing arguments if (argc != 2){cout << "Use <program name> <tile id>" << endl; return 1;} string agb_name=argv[1]; string tile_id = argv[1]; string forestmodel_name = tile_id + "_res_forest_model.tif"; string bgc_name = tile_id + "_bgc.tif"; string agc_name = tile_id + "_carbon.tif"; string loss_name = tile_id + "_loss.tif"; string peat_name = tile_id + "_res_peatland_drainage_proj.tif"; string burn_name = tile_id + "_res_peatland_drainage_proj.tif"; string hist_name = tile_id + "_res_hwsd_histosoles.tif"; string ecozone_name = tile_id + "_res_fao_ecozones_bor_tem_tro.tif"; string climate_name = tile_id + "_res_climate_zone.tif"; //either parse this var from inputs or send it in string out_name1="test1.tif"; string out_name2 = "test2.tif"; //setting variables int x, y; int xsize, ysize; double GeoTransform[6]; double ulx, uly; double pixelsize; //initialize GDAL for reading GDALAllRegister(); GDALDataset *INGDAL; GDALRasterBand *INBAND; GDALDataset *INGDAL2; GDALRasterBand *INBAND2; GDALDataset *INGDAL3; GDALRasterBand *INBAND3; GDALDataset *INGDAL4; GDALRasterBand *INBAND4; GDALDataset *INGDAL5; GDALRasterBand *INBAND5; GDALDataset *INGDAL6; GDALRasterBand *INBAND6; GDALDataset *INGDAL7; GDALRasterBand *INBAND7; GDALDataset *INGDAL8; GDALRasterBand *INBAND8; GDALDataset *INGDAL9; GDALRasterBand *INBAND9; //open file and get extent and projection INGDAL = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly ); INBAND = INGDAL->GetRasterBand(1); INGDAL2 = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly ); INBAND2 = INGDAL2->GetRasterBand(1); INGDAL3 = (GDALDataset *) GDALOpen(forestmodel_name.c_str(), GA_ReadOnly ); INBAND3 = INGDAL3->GetRasterBand(1); INGDAL4 = (GDALDataset *) GDALOpen(loss_name.c_str(), GA_ReadOnly ); INBAND4 = INGDAL4->GetRasterBand(1); INGDAL5 = (GDALDataset *) GDALOpen(peat_name.c_str(), GA_ReadOnly ); INBAND5 = INGDAL5->GetRasterBand(1); INGDAL6 = (GDALDataset *) GDALOpen(burn_name.c_str(), GA_ReadOnly ); INBAND6 = INGDAL6->GetRasterBand(1); INGDAL7 = (GDALDataset *) GDALOpen(hist_name.c_str(), GA_ReadOnly ); INBAND7 = INGDAL7->GetRasterBand(1); INGDAL8 = (GDALDataset *) GDALOpen(ecozone_name.c_str(), GA_ReadOnly ); INBAND8 = INGDAL8->GetRasterBand(1); INGDAL9 = (GDALDataset *) GDALOpen(climate_name.c_str(), GA_ReadOnly ); INBAND9 = INGDAL9->GetRasterBand(1); xsize=INBAND3->GetXSize(); ysize=INBAND3->GetYSize(); INGDAL->GetGeoTransform(GeoTransform); ulx=GeoTransform[0]; uly=GeoTransform[3]; pixelsize=GeoTransform[1]; cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl; //initialize GDAL for writing GDALDriver *OUTDRIVER; GDALDataset *OUTGDAL; GDALDataset *OUTGDAL2; GDALRasterBand *OUTBAND1; GDALRasterBand *OUTBAND2; OGRSpatialReference oSRS; char *OUTPRJ = NULL; char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" ); OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF"); if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );}; oSRS.SetWellKnownGeogCS( "WGS84" ); oSRS.exportToWkt( &OUTPRJ ); double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize }; OUTGDAL = OUTDRIVER->Create( out_name1.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND1 = OUTGDAL->GetRasterBand(1); OUTBAND1->SetNoDataValue(-9999); OUTGDAL2 = OUTDRIVER->Create( out_name2.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL2->SetProjection(OUTPRJ); OUTBAND2 = OUTGDAL2->GetRasterBand(1); OUTBAND2->SetNoDataValue(-9999); //read/write data float agb_data[xsize]; float agc_data[xsize]; float bgc_data[xsize]; float loss_data[xsize]; float peat_data[xsize]; float forestmodel_data[xsize]; float burn_data[xsize]; float hist_data[xsize]; float ecozone_data[xsize]; float climate_data[xsize]; float out_data1[xsize]; float out_data2[xsize]; for(y=37644; y<37647; y++) { //for (y=0; y<ysize; y++) { //for (y=0; y<ysize; y++) { INBAND->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0); INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, forestmodel_data, xsize, 1, GDT_Float32, 0, 0); INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0); INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, peat_data, xsize, 1, GDT_Float32, 0, 0); INBAND6->RasterIO(GF_Read, 0, y, xsize, 1, burn_data, xsize, 1, GDT_Float32, 0, 0); INBAND7->RasterIO(GF_Read, 0, y, xsize, 1, hist_data, xsize, 1, GDT_Float32, 0, 0); INBAND8->RasterIO(GF_Read, 0, y, xsize, 1, ecozone_data, xsize, 1, GDT_Float32, 0, 0); INBAND9->RasterIO(GF_Read, 0, y, xsize, 1, climate_data, xsize, 1, GDT_Float32, 0, 0); for(x=0; x<xsize; x++) { // zero out anything that is no data so it can be added to other rasters without issues if (loss_data[x] > 0) { if (agc_data[x] == -9999) { agc_data[x] = 0; } if (bgc_data[x] == -9999) { bgc_data[x] = 0; } if (forestmodel_data[x] == 1) // forestry { if (peat_data[x] != 0) // if its on peat data { if (burn_data[x] != 0) // if its on peat and on burn data { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x]) * peat_data[x] + 917; } else // on peat but not on burn data { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x]) * peat_data[x]; } } else // not on peat { if (hist_data[x] != 0) // not on peat but is on histosoles { if (ecozone_data[x] = 1) { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + ((15 - loss_data[x]) * 55); } if (ecozone_data[x] = 2) { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + ((15 - loss_data[x]) * 2.16); } if (ecozone_data[x] = 3) { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + ((15 - loss_data[x]) * 6.27); } } else //not on peat and not on histosole { out_data1[x] = (agc_data[x] + bgc_data[x]) * 3.67; } } } if (forestmodel_data[x] == 2) { out_data2[x] = 2; } if (forestmodel_data[x] == 3) { out_data1[x] = -9999; } if (forestmodel_data[x] == 0) { out_data1[x] = -9999; } } else // not on loss { out_data1[x] = -9999; } // print out all the variables and results cout << "\n" << "agc: " << agc_data[x] << "\n"; cout << "bgc: " << bgc_data[x] << "\n"; cout << "loss: " << loss_data[x] << "\n"; cout << "peat: " << peat_data[x] << "\n"; cout << "burn: " << burn_data[x] << "\n"; cout << "hist: " << hist_data[x] << "\n"; cout << "ecozone: " << ecozone_data[x] << "\n"; cout << "forest model: " << forestmodel_data[x] << "\n"; cout << "out data: " << out_data1[x] << "\n"; } OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_data1, xsize, 1, GDT_Float32, 0, 0 ); OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_data2, xsize, 1, GDT_Float32, 0, 0 ); //closes for y loop } //close GDAL GDALClose(INGDAL); GDALClose((GDALDatasetH)OUTGDAL); GDALClose((GDALDatasetH)OUTGDAL2); return 0; } <commit_msg>tested full tile. working for forest conversion<commit_after>// #include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sys/stat.h> #include <math.h> #include <algorithm> #include <string.h> #include <stdint.h> #include <sstream> #include <iomanip> #include <gdal/gdal_priv.h> #include <gdal/cpl_conv.h> #include <gdal/ogr_spatialref.h> using namespace std; //to compile: c++ raster_math.cpp -o raster_math -lgdal // ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt int main(int argc, char* argv[]) { //passing arguments if (argc != 2){cout << "Use <program name> <tile id>" << endl; return 1;} string agb_name=argv[1]; string tile_id = argv[1]; string forestmodel_name = tile_id + "_res_forest_model.tif"; string bgc_name = tile_id + "_bgc.tif"; string agc_name = tile_id + "_carbon.tif"; string loss_name = tile_id + "_loss.tif"; string peat_name = tile_id + "_res_peatland_drainage_proj.tif"; string burn_name = tile_id + "_res_peatland_drainage_proj.tif"; string hist_name = tile_id + "_res_hwsd_histosoles.tif"; string ecozone_name = tile_id + "_res_fao_ecozones_bor_tem_tro.tif"; string climate_name = tile_id + "_res_climate_zone.tif"; //either parse this var from inputs or send it in string out_name1="test1.tif"; string out_name2 = "test2.tif"; //setting variables int x, y; int xsize, ysize; double GeoTransform[6]; double ulx, uly; double pixelsize; //initialize GDAL for reading GDALAllRegister(); GDALDataset *INGDAL; GDALRasterBand *INBAND; GDALDataset *INGDAL2; GDALRasterBand *INBAND2; GDALDataset *INGDAL3; GDALRasterBand *INBAND3; GDALDataset *INGDAL4; GDALRasterBand *INBAND4; GDALDataset *INGDAL5; GDALRasterBand *INBAND5; GDALDataset *INGDAL6; GDALRasterBand *INBAND6; GDALDataset *INGDAL7; GDALRasterBand *INBAND7; GDALDataset *INGDAL8; GDALRasterBand *INBAND8; GDALDataset *INGDAL9; GDALRasterBand *INBAND9; //open file and get extent and projection INGDAL = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly ); INBAND = INGDAL->GetRasterBand(1); INGDAL2 = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly ); INBAND2 = INGDAL2->GetRasterBand(1); INGDAL3 = (GDALDataset *) GDALOpen(forestmodel_name.c_str(), GA_ReadOnly ); INBAND3 = INGDAL3->GetRasterBand(1); INGDAL4 = (GDALDataset *) GDALOpen(loss_name.c_str(), GA_ReadOnly ); INBAND4 = INGDAL4->GetRasterBand(1); INGDAL5 = (GDALDataset *) GDALOpen(peat_name.c_str(), GA_ReadOnly ); INBAND5 = INGDAL5->GetRasterBand(1); INGDAL6 = (GDALDataset *) GDALOpen(burn_name.c_str(), GA_ReadOnly ); INBAND6 = INGDAL6->GetRasterBand(1); INGDAL7 = (GDALDataset *) GDALOpen(hist_name.c_str(), GA_ReadOnly ); INBAND7 = INGDAL7->GetRasterBand(1); INGDAL8 = (GDALDataset *) GDALOpen(ecozone_name.c_str(), GA_ReadOnly ); INBAND8 = INGDAL8->GetRasterBand(1); INGDAL9 = (GDALDataset *) GDALOpen(climate_name.c_str(), GA_ReadOnly ); INBAND9 = INGDAL9->GetRasterBand(1); xsize=INBAND3->GetXSize(); ysize=INBAND3->GetYSize(); INGDAL->GetGeoTransform(GeoTransform); ulx=GeoTransform[0]; uly=GeoTransform[3]; pixelsize=GeoTransform[1]; cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl; //initialize GDAL for writing GDALDriver *OUTDRIVER; GDALDataset *OUTGDAL; GDALDataset *OUTGDAL2; GDALRasterBand *OUTBAND1; GDALRasterBand *OUTBAND2; OGRSpatialReference oSRS; char *OUTPRJ = NULL; char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" ); OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF"); if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );}; oSRS.SetWellKnownGeogCS( "WGS84" ); oSRS.exportToWkt( &OUTPRJ ); double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize }; OUTGDAL = OUTDRIVER->Create( out_name1.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND1 = OUTGDAL->GetRasterBand(1); OUTBAND1->SetNoDataValue(-9999); OUTGDAL2 = OUTDRIVER->Create( out_name2.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL2->SetProjection(OUTPRJ); OUTBAND2 = OUTGDAL2->GetRasterBand(1); OUTBAND2->SetNoDataValue(-9999); //read/write data float agb_data[xsize]; float agc_data[xsize]; float bgc_data[xsize]; float loss_data[xsize]; float peat_data[xsize]; float forestmodel_data[xsize]; float burn_data[xsize]; float hist_data[xsize]; float ecozone_data[xsize]; float climate_data[xsize]; float out_data1[xsize]; float out_data2[xsize]; //for(y=33668; y<33672; y++) { for (y=0; y<ysize; y++) { //for (y=0; y<ysize; y++) { INBAND->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0); INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, forestmodel_data, xsize, 1, GDT_Float32, 0, 0); INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0); INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, peat_data, xsize, 1, GDT_Float32, 0, 0); INBAND6->RasterIO(GF_Read, 0, y, xsize, 1, burn_data, xsize, 1, GDT_Float32, 0, 0); INBAND7->RasterIO(GF_Read, 0, y, xsize, 1, hist_data, xsize, 1, GDT_Float32, 0, 0); INBAND8->RasterIO(GF_Read, 0, y, xsize, 1, ecozone_data, xsize, 1, GDT_Float32, 0, 0); INBAND9->RasterIO(GF_Read, 0, y, xsize, 1, climate_data, xsize, 1, GDT_Float32, 0, 0); for(x=0; x<xsize; x++) { // zero out anything that is no data so it can be added to other rasters without issues if (loss_data[x] > 0) { if (agc_data[x] == -9999) { agc_data[x] = 0; } if (bgc_data[x] == -9999) { bgc_data[x] = 0; } if (forestmodel_data[x] == 1) // forestry { if (peat_data[x] != 0) // if its on peat data { if (burn_data[x] != 0) // if its on peat and on burn data { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x]) * peat_data[x] + 917; } else // on peat but not on burn data { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x]) * peat_data[x]; } } else // not on peat { if (hist_data[x] != 0) // not on peat but is on histosoles { if (ecozone_data[x] = 1) { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + ((15 - loss_data[x]) * 55); } if (ecozone_data[x] = 2) { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + ((15 - loss_data[x]) * 2.16); } if (ecozone_data[x] = 3) { out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + ((15 - loss_data[x]) * 6.27); } } else //not on peat and not on histosole { out_data1[x] = (agc_data[x] + bgc_data[x]) * 3.67; } } } if (forestmodel_data[x] == 2) { out_data2[x] = 2; } if (forestmodel_data[x] == 3) { out_data1[x] = -9999; } if (forestmodel_data[x] == 0) { out_data1[x] = -9999; } } else // not on loss { out_data1[x] = -9999; } // print out all the variables and results // cout << "\n" << "agc: " << agc_data[x] << "\n"; // cout << "bgc: " << bgc_data[x] << "\n"; // cout << "loss: " << loss_data[x] << "\n"; // cout << "peat: " << peat_data[x] << "\n"; // cout << "burn: " << burn_data[x] << "\n"; // cout << "hist: " << hist_data[x] << "\n"; // cout << "ecozone: " << ecozone_data[x] << "\n"; // cout << "forest model: " << forestmodel_data[x] << "\n"; // cout << "out data: " << out_data1[x] << "\n"; } OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_data1, xsize, 1, GDT_Float32, 0, 0 ); OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_data2, xsize, 1, GDT_Float32, 0, 0 ); //closes for y loop } //close GDAL GDALClose(INGDAL); GDALClose((GDALDatasetH)OUTGDAL); GDALClose((GDALDatasetH)OUTGDAL2); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2010-present 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 VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3107 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3107 to 3108<commit_after>/* Copyright (c) 2010-present 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 VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3108 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 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 VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3489 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3489 to 3490<commit_after>/* Copyright (c) 2010 - 2021 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 VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3490 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// Time: O(m * n) // Space: O(m + n) class Solution { public: string multiply(string num1, string num2) { return BigInt(num1) * BigInt(num2); } class BigInt { public: BigInt(const string& s) { transform(s.rbegin(), s.rend(), back_inserter(n_), [](const char c) { return c - '0';}); } operator string() { string s; transform(find_if(n_.rbegin(), prev(n_.rend()), [](const int i) { return i != 0; }), n_.rend(), back_inserter(s), [](const int i) { return i + '0'; }); return s; } BigInt operator*(const BigInt &rhs) const { BigInt res(n_.size() + rhs.size() + 1, 0); for(auto i = 0; i < n_.size(); ++i) { for(auto j = 0; j < rhs.size(); ++j) { res[i + j] += n_[i] * rhs[j]; res[i + j + 1] += res[i + j] / 10; res[i + j] %= 10; } } return res; } private: vector<int> n_; BigInt(int num, int val): n_(num, val) { } // Getter. int operator[] (int i) const { return n_[i]; } // Setter. int & operator[] (int i) { return n_[i]; } size_t size() const { return n_.size(); } }; }; <commit_msg>Update multiply-strings.cpp<commit_after>// Time: O(m * n) // Space: O(m + n) class Solution { public: string multiply(string num1, string num2) { const auto char_to_int = [](const char c) { return c - '0'; }; const auto int_to_char = [](const int i) { return i + '0'; }; vector<int> n1; transform(num1.rbegin(), num1.rend(), back_inserter(n1), char_to_int); vector<int> n2; transform(num2.rbegin(), num2.rend(), back_inserter(n2), char_to_int); vector<int> tmp(n1.size() + n2.size() + 1); for(int i = 0; i < n1.size(); ++i) { for(int j = 0; j < n2.size(); ++j) { tmp[i + j] += n1[i] * n2[j]; tmp[i + j + 1] += tmp[i + j] / 10; tmp[i + j] %= 10; } } string res; transform(find_if(tmp.rbegin(), prev(tmp.rend()), [](const int i) { return i != 0; }), tmp.rend(), back_inserter(res), int_to_char); return res; } }; // Time: O(m * n) // Space: O(m + n) // Define a new BigInt class solutioin. class Solution2 { public: string multiply(string num1, string num2) { return BigInt(num1) * BigInt(num2); } class BigInt { public: BigInt(const string& s) { transform(s.rbegin(), s.rend(), back_inserter(n_), [](const char c) { return c - '0'; }); } operator string() { string s; transform(find_if(n_.rbegin(), prev(n_.rend()), [](const int i) { return i != 0; }), n_.rend(), back_inserter(s), [](const int i) { return i + '0'; }); return s; } BigInt operator*(const BigInt &rhs) const { BigInt res(n_.size() + rhs.size() + 1, 0); for(auto i = 0; i < n_.size(); ++i) { for(auto j = 0; j < rhs.size(); ++j) { res[i + j] += n_[i] * rhs[j]; res[i + j + 1] += res[i + j] / 10; res[i + j] %= 10; } } return res; } private: vector<int> n_; BigInt(int num, int val): n_(num, val) { } // Getter. int operator[] (int i) const { return n_[i]; } // Setter. int & operator[] (int i) { return n_[i]; } size_t size() const { return n_.size(); } }; }; <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONPainterInterfaceHelper.h" ///\class AliMUONPainterInterfaceHelper /// /// Helper class to work with TGButtonGroup /// /// This class only works if the buttons in the TGButtonGroup have contiguous /// ids, and if those ids start at ButtonStartingId(). /// Not bullet-proof, I admit, but this is the only way I've found with /// the current TGButtonGroup implementation which does not allow to loop /// easily on all buttons. /// // Author Laurent Aphecetche, Subatech #include "AliMUONPainterEnv.h" #include "AliMUONPainterHelper.h" #include "AliLog.h" #include <Riostream.h> #include <TClass.h> #include <TGButtonGroup.h> #include <TGButton.h> #include <TGClient.h> #include <TObjArray.h> #include <TObjString.h> #include <TString.h> #include <RVersion.h> #include <cassert> ///\cond CLASSIMP ClassImp(AliMUONPainterInterfaceHelper) ///\endcond //_____________________________________________________________________________ AliMUONPainterInterfaceHelper::AliMUONPainterInterfaceHelper() : TObject() { /// ctor } //_____________________________________________________________________________ AliMUONPainterInterfaceHelper::~AliMUONPainterInterfaceHelper() { /// dtor } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::AddRadioButton(TGButtonGroup& bg, const TString& name, void* userData, Bool_t select) { /// Add a radio button to a group Int_t n = bg.GetCount(); TGButton* button = new TGRadioButton(&bg, name.Data(), n+ButtonStartingId()); button->SetUserData(userData); button->SetOn(select,kFALSE); } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::AddCheckButton(TGButtonGroup& bg, const TString& name, void* userData, Bool_t select) { /// Add a check button to a group Int_t n = bg.GetCount(); TGButton* button = new TGCheckButton(&bg, name.Data(), n+ButtonStartingId()); button->SetUserData(userData); button->SetOn(select,kFALSE); } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::ClearButtons(TGButtonGroup& bg) { /// Remove all buttons from group. /// Bear in mind that you're thus disconnecting the group from /// any signals it might have. So you must re-connect them after /// a call to this method, if you want to. while ( bg.GetCount() > 0 ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(bg.GetCount())); if ( !button ) { AliFatalClass(Form("Got a null button for bg.Count()=%d",bg.GetCount())); } bg.Remove(button); #if ROOT_VERSION_CODE <= ROOT_VERSION(5,16,0) button->DestroyWindow(); #endif delete button; } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Copy(const TGButtonGroup& src, TGButtonGroup& dest) { /// Copy a button group into another one AliDebugClass(1,Form("src=%p (%s) count=%d dest=%p (%s) count=%d", &src,src.GetTitle(),src.GetCount(), &dest,dest.GetTitle(),dest.GetCount())); StdoutToAliDebugClass(1,cout << "---copying:" << endl; Dump(src); cout << "---to:" << endl; Dump(dest)); ClearButtons(dest); dest.SetTitle(src.GetTitle()); if ( &src != &dest ) { for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + src.GetCount(); ++i ) { TGTextButton* tb = static_cast<TGTextButton*>(src.GetButton(i)); TGButton* button = new TGRadioButton(&dest,tb->GetTitle(),tb->WidgetId()); assert(tb->WidgetId()==i); button->SetUserData(tb->GetUserData()); button->SetOn(tb->IsOn(),kFALSE); } } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Dump(const TGButtonGroup& bg) { /// Printout cout << Form("ButtonGroup %s %s",bg.GetName(),bg.GetTitle()) << endl; for ( Int_t i = ButtonStartingId(); i < bg.GetCount() + ButtonStartingId(); ++i ) { TGTextButton* button = static_cast<TGTextButton*>(bg.GetButton(i)); if ( button ) { cout << Form("i %2d button %s id %d wid %d ON %d", i,button->GetTitle(),button->GetId(), button->WidgetId(), button->IsOn()) << endl; } else { cout << Form("i %2d button = 0x0",i) << endl; } } } //_____________________________________________________________________________ TGButton* AliMUONPainterInterfaceHelper::FindButtonByName(const TGButtonGroup& bg, const TString& name) { /// Find a button by name for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = static_cast<TGTextButton*>(bg.GetButton(i)); if (!button) { AliErrorClass(Form("(%s) : Something wrong",name.Data())); Dump(bg); } else { if ( name == button->GetTitle() ) { return button; } } } return 0x0; } //_____________________________________________________________________________ TGButton* AliMUONPainterInterfaceHelper::FindButtonByUserData(const TGButtonGroup& bg, const void* userData) { /// Find a button by userData for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGButton* button = bg.GetButton(i); if ( button->GetUserData() == userData ) { return button; } } return 0x0; } //_____________________________________________________________________________ TGButton* AliMUONPainterInterfaceHelper::FindDownButton(const TGButtonGroup& bg) { /// Find which button is down (in a radio group) AliDebugClass(1,Form("bg %s",bg.GetTitle())); for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGButton* button = bg.GetButton(i); if ( button->IsOn() ) { AliDebugClass(1,Form("button %s",button->GetTitle())); return button; } } return 0x0; } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::SetBackgroundColor(const char* resourceBaseName, TGWindow& window) { /// Set the background color of the window TString rs(Form("%s.BackgroundColor",resourceBaseName)); TString colorName = AliMUONPainterHelper::Instance()->Env()->String(rs.Data(),"#c0c0c0"); Pixel_t color; Bool_t ok = gClient->GetColorByName(colorName, color); if ( ok ) { window.SetBackgroundColor(color); AliDebugClass(1,Form("Setting %s color to %s",rs.Data(),colorName.Data())); } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::SetState(TGButtonGroup& bg, Bool_t state) { /// should not be needed with root > 5.16/00 as there's a TGButtonGroup::SetState /// method now... #if ROOT_VERSION_CODE > ROOT_VERSION(5,16,0) bg.SetState(state); #else for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(i)); if ( state ) { button->SetState(kButtonUp); } else { button->SetState(kButtonDisabled); } } #endif } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Select(TGButtonGroup& bg, const TString& buttonName, Bool_t emit) { /// Select which button should be on AliDebugClass(1,Form("bg %s buttonName %s",bg.GetTitle(),buttonName.Data())); for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(i)); if ( buttonName == button->GetTitle() || buttonName == "*" ) { if ( emit ) { button->Clicked(); } else { button->SetOn(kTRUE); } } } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Unselect(TGButtonGroup& bg, const TString& buttonName, Bool_t emit) { /// Unselect a given button for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(i)); if ( buttonName == button->GetTitle() || buttonName == "*" ) { if ( emit ) { button->Released(); } else { button->SetOn(kFALSE); } } } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::RemoveButton(TGButtonGroup& bg, const TGButton* button) { /// Remove a button // need to redo it from scratch in order not the leave holes in the // id numbering TGButtonGroup bgtmp(bg.GetParent(),bg.GetTitle()); Int_t id(ButtonStartingId()); for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* b = static_cast<TGTextButton*>(bg.GetButton(i)); if ( b != button ) { TGButton* bc = new TGRadioButton(&bgtmp,b->GetTitle(),id); ++id; bc->SetUserData(b->GetUserData()); bc->SetOn(b->IsOn()); } } ClearButtons(bg); Copy(bgtmp,bg); bg.Show(); } <commit_msg>Fixing compiler warnings from Form() in one more file, now properly checked with Root trunk<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONPainterInterfaceHelper.h" ///\class AliMUONPainterInterfaceHelper /// /// Helper class to work with TGButtonGroup /// /// This class only works if the buttons in the TGButtonGroup have contiguous /// ids, and if those ids start at ButtonStartingId(). /// Not bullet-proof, I admit, but this is the only way I've found with /// the current TGButtonGroup implementation which does not allow to loop /// easily on all buttons. /// // Author Laurent Aphecetche, Subatech #include "AliMUONPainterEnv.h" #include "AliMUONPainterHelper.h" #include "AliLog.h" #include <Riostream.h> #include <TClass.h> #include <TGButtonGroup.h> #include <TGButton.h> #include <TGClient.h> #include <TObjArray.h> #include <TObjString.h> #include <TString.h> #include <RVersion.h> #include <cassert> ///\cond CLASSIMP ClassImp(AliMUONPainterInterfaceHelper) ///\endcond //_____________________________________________________________________________ AliMUONPainterInterfaceHelper::AliMUONPainterInterfaceHelper() : TObject() { /// ctor } //_____________________________________________________________________________ AliMUONPainterInterfaceHelper::~AliMUONPainterInterfaceHelper() { /// dtor } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::AddRadioButton(TGButtonGroup& bg, const TString& name, void* userData, Bool_t select) { /// Add a radio button to a group Int_t n = bg.GetCount(); TGButton* button = new TGRadioButton(&bg, name.Data(), n+ButtonStartingId()); button->SetUserData(userData); button->SetOn(select,kFALSE); } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::AddCheckButton(TGButtonGroup& bg, const TString& name, void* userData, Bool_t select) { /// Add a check button to a group Int_t n = bg.GetCount(); TGButton* button = new TGCheckButton(&bg, name.Data(), n+ButtonStartingId()); button->SetUserData(userData); button->SetOn(select,kFALSE); } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::ClearButtons(TGButtonGroup& bg) { /// Remove all buttons from group. /// Bear in mind that you're thus disconnecting the group from /// any signals it might have. So you must re-connect them after /// a call to this method, if you want to. while ( bg.GetCount() > 0 ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(bg.GetCount())); if ( !button ) { AliFatalClass(Form("Got a null button for bg.Count()=%d",bg.GetCount())); } bg.Remove(button); #if ROOT_VERSION_CODE <= ROOT_VERSION(5,16,0) button->DestroyWindow(); #endif delete button; } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Copy(const TGButtonGroup& src, TGButtonGroup& dest) { /// Copy a button group into another one AliDebugClass(1,Form("src=%p (%s) count=%d dest=%p (%s) count=%d", &src,src.GetTitle(),src.GetCount(), &dest,dest.GetTitle(),dest.GetCount())); StdoutToAliDebugClass(1,cout << "---copying:" << endl; Dump(src); cout << "---to:" << endl; Dump(dest)); ClearButtons(dest); dest.SetTitle(src.GetTitle()); if ( &src != &dest ) { for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + src.GetCount(); ++i ) { TGTextButton* tb = static_cast<TGTextButton*>(src.GetButton(i)); TGButton* button = new TGRadioButton(&dest,tb->GetTitle(),tb->WidgetId()); assert(tb->WidgetId()==i); button->SetUserData(tb->GetUserData()); button->SetOn(tb->IsOn(),kFALSE); } } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Dump(const TGButtonGroup& bg) { /// Printout cout << Form("ButtonGroup %s %s",bg.GetName(),bg.GetTitle()) << endl; for ( Int_t i = ButtonStartingId(); i < bg.GetCount() + ButtonStartingId(); ++i ) { TGTextButton* button = static_cast<TGTextButton*>(bg.GetButton(i)); if ( button ) { cout << Form("i %2d button %s id %lu wid %d ON %d", i,button->GetTitle(),button->GetId(), button->WidgetId(), button->IsOn()) << endl; } else { cout << Form("i %2d button = 0x0",i) << endl; } } } //_____________________________________________________________________________ TGButton* AliMUONPainterInterfaceHelper::FindButtonByName(const TGButtonGroup& bg, const TString& name) { /// Find a button by name for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = static_cast<TGTextButton*>(bg.GetButton(i)); if (!button) { AliErrorClass(Form("(%s) : Something wrong",name.Data())); Dump(bg); } else { if ( name == button->GetTitle() ) { return button; } } } return 0x0; } //_____________________________________________________________________________ TGButton* AliMUONPainterInterfaceHelper::FindButtonByUserData(const TGButtonGroup& bg, const void* userData) { /// Find a button by userData for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGButton* button = bg.GetButton(i); if ( button->GetUserData() == userData ) { return button; } } return 0x0; } //_____________________________________________________________________________ TGButton* AliMUONPainterInterfaceHelper::FindDownButton(const TGButtonGroup& bg) { /// Find which button is down (in a radio group) AliDebugClass(1,Form("bg %s",bg.GetTitle())); for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGButton* button = bg.GetButton(i); if ( button->IsOn() ) { AliDebugClass(1,Form("button %s",button->GetTitle())); return button; } } return 0x0; } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::SetBackgroundColor(const char* resourceBaseName, TGWindow& window) { /// Set the background color of the window TString rs(Form("%s.BackgroundColor",resourceBaseName)); TString colorName = AliMUONPainterHelper::Instance()->Env()->String(rs.Data(),"#c0c0c0"); Pixel_t color; Bool_t ok = gClient->GetColorByName(colorName, color); if ( ok ) { window.SetBackgroundColor(color); AliDebugClass(1,Form("Setting %s color to %s",rs.Data(),colorName.Data())); } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::SetState(TGButtonGroup& bg, Bool_t state) { /// should not be needed with root > 5.16/00 as there's a TGButtonGroup::SetState /// method now... #if ROOT_VERSION_CODE > ROOT_VERSION(5,16,0) bg.SetState(state); #else for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(i)); if ( state ) { button->SetState(kButtonUp); } else { button->SetState(kButtonDisabled); } } #endif } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Select(TGButtonGroup& bg, const TString& buttonName, Bool_t emit) { /// Select which button should be on AliDebugClass(1,Form("bg %s buttonName %s",bg.GetTitle(),buttonName.Data())); for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(i)); if ( buttonName == button->GetTitle() || buttonName == "*" ) { if ( emit ) { button->Clicked(); } else { button->SetOn(kTRUE); } } } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::Unselect(TGButtonGroup& bg, const TString& buttonName, Bool_t emit) { /// Unselect a given button for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* button = (TGTextButton*)(bg.GetButton(i)); if ( buttonName == button->GetTitle() || buttonName == "*" ) { if ( emit ) { button->Released(); } else { button->SetOn(kFALSE); } } } } //_____________________________________________________________________________ void AliMUONPainterInterfaceHelper::RemoveButton(TGButtonGroup& bg, const TGButton* button) { /// Remove a button // need to redo it from scratch in order not the leave holes in the // id numbering TGButtonGroup bgtmp(bg.GetParent(),bg.GetTitle()); Int_t id(ButtonStartingId()); for ( Int_t i = ButtonStartingId(); i < ButtonStartingId() + bg.GetCount(); ++i ) { TGTextButton* b = static_cast<TGTextButton*>(bg.GetButton(i)); if ( b != button ) { TGButton* bc = new TGRadioButton(&bgtmp,b->GetTitle(),id); ++id; bc->SetUserData(b->GetUserData()); bc->SetOn(b->IsOn()); } } ClearButtons(bg); Copy(bgtmp,bg); bg.Show(); } <|endoftext|>
<commit_before>// // RubiksCube.cpp // hog2 glut // // Created by Nathan Sturtevant on 4/6/13. // Copyright (c) 2013 University of Denver. All rights reserved. // #include "RubiksCube.h" #include <cassert> #include <cstdio> #include <algorithm> void RubiksCube::GetSuccessors(const RubiksState &nodeID, std::vector<RubiksState> &neighbors) const { neighbors.resize(18); for (int x = 0; x < 18; x++) { GetNextState(nodeID, x, neighbors[x]); } } void RubiksCube::GetActions(const RubiksState &nodeID, std::vector<RubiksAction> &actions) const { actions.resize(0); if (!pruneSuccessors || history.size() == 0) { for (int x = 0; x < 18; x++) actions.push_back(x); } else { // 0, 5, 2, 4, 1, 3 for (int x = 0; x < 18; x++) { // 1. after any face you can't turn the same face again if (x/3 == history.back()/3) continue; // 2. after faces 5, 4, 3 you can't turn 0, 2, 1 respectively if ((1 == (history.back()/3)%2) && (x/3+1 == history.back()/3)) continue; actions.push_back(x); } } // std::random_shuffle(actions.begin(), actions.end()); } RubiksAction RubiksCube::GetAction(const RubiksState &s1, const RubiksState &s2) const { //std::vector<RubiksAction> succ; //GetActions(s1, succ); RubiksState tmp; for (int x = 0; x < 18; x++) { GetNextState(s1, x, tmp); if (tmp == s2) return x; } assert(false); return 0; } void RubiksCube::ApplyAction(RubiksState &s, RubiksAction a) const { c.ApplyAction(s.corner, a); e.ApplyAction(s.edge, a); e7.ApplyAction(s.edge7, a); if (pruneSuccessors) history.push_back(a); } void RubiksCube::UndoAction(RubiksState &s, RubiksAction a) const { if (pruneSuccessors && history.size() > 0) { assert(history.back() == a); history.pop_back(); } InvertAction(a); c.ApplyAction(s.corner, a); e.ApplyAction(s.edge, a); e7.ApplyAction(s.edge7, a); } void RubiksCube::GetNextState(const RubiksState &s1, RubiksAction a, RubiksState &s2) const { s2 = s1; ApplyAction(s2, a); } bool RubiksCube::InvertAction(RubiksAction &a) const { if (2 == a%3) return true; if (1 == a%3) { a -= 1; return true; } a += 1; return true; } /** Heuristic value between two arbitrary nodes. **/ double RubiksCube::HCost(const RubiksState &node1, const RubiksState &node2) { double val = 0; // corner PDB uint64_t hash = c.GetStateHash(node1.corner); val = cornerPDB.Get(hash); // edge PDB hash = e7.GetStateHash(node1.edge7); // // edge PDB if (0 == hash%compressionFactor) { double val2 = edge7PDBint.Get(hash/compressionFactor); if (val2 > 8) val2 = 8; val = max(val, val2); } node1.edge7.GetDual(e7dual); hash = e7.GetStateHash(e7dual); if (0 == hash%compressionFactor) { double val2 = edge7PDBint.Get(hash/compressionFactor); if (val2 > 8) val2 = 8; val = max(val, val2); } return val; // load PDB values directly from disk! // make sure that "data" is initialized with the right constructor calls for the data // int64_t r1, r2; // e.rankPlayer(node1.edge, 0, r1, r2); // double edge = f.ReadFileDepth(data[r1].bucketID, data[r1].bucketOffset+r2); // if (edge > 10) // edge = 10; // val = max(val, edge); return val; } /** Heuristic value between node and the stored goal. Asserts that the goal is stored **/ double RubiksCube::HCost(const RubiksState &node) { return 0; } bool RubiksCube::GoalTest(const RubiksState &node, const RubiksState &goal) { return (node.corner.state == goal.corner.state && node.edge.state == goal.edge.state); } /** Goal Test if the goal is stored **/ bool RubiksCube::GoalTest(const RubiksState &node) { assert(false); return false; } uint64_t RubiksCube::GetStateHash(const RubiksState &node) const { uint64_t hash = c.GetStateHash(node.corner); hash *= e.getMaxSinglePlayerRank(); hash += e.GetStateHash(node.edge); return hash; } void RubiksCube::GetStateFromHash(uint64_t hash, RubiksState &node) const { e.GetStateFromHash(hash%e.getMaxSinglePlayerRank(), node.edge); c.GetStateFromHash(hash/e.getMaxSinglePlayerRank(), node.corner); } void RubiksCube::OpenGLDraw() const { } void RubiksCube::OpenGLDraw(const RubiksState&s) const { e.OpenGLDraw(s.edge); c.OpenGLDraw(s.corner); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawCorners(const RubiksState&s) const { c.OpenGLDraw(s.corner); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawEdges(const RubiksState&s) const { Rubik7EdgeState e7tmp; s.edge7.GetDual(e7tmp); e7.OpenGLDraw(e7tmp); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawEdgeDual(const RubiksState&s) const { s.edge.GetDual(dual); e.OpenGLDraw(dual); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawCenters() const { float scale = 0.3; float offset = 0.95*scale/3.0; glBegin(GL_QUADS); SetFaceColor(0); glVertex3f(-offset, -scale, -offset); glVertex3f(offset, -scale, -offset); glVertex3f(offset, -scale, offset); glVertex3f(-offset, -scale, offset); SetFaceColor(5); glVertex3f(-offset, scale, -offset); glVertex3f(offset, scale, -offset); glVertex3f(offset, scale, offset); glVertex3f(-offset, scale, offset); SetFaceColor(1); glVertex3f(-scale, -offset, -offset); glVertex3f(-scale, offset, -offset); glVertex3f(-scale, offset, offset); glVertex3f(-scale, -offset, offset); SetFaceColor(3); glVertex3f(scale, -offset, -offset); glVertex3f(scale, offset, -offset); glVertex3f(scale, offset, offset); glVertex3f(scale, -offset, offset); SetFaceColor(2); glVertex3f(-offset, -offset, -scale); glVertex3f(offset, -offset, -scale); glVertex3f(offset, offset, -scale); glVertex3f(-offset, offset, -scale); SetFaceColor(4); glVertex3f(-offset, -offset, scale); glVertex3f(offset, -offset, scale); glVertex3f(offset, offset, scale); glVertex3f(-offset, offset, scale); glColor3f(0,0,0); offset = scale/3.0; scale*=0.99; glVertex3f(-3.0*offset, -scale, -3.0*offset); glVertex3f(3.0*offset, -scale, -3.0*offset); glVertex3f(3.0*offset, -scale, 3.0*offset); glVertex3f(-3.0*offset, -scale, 3.0*offset); glVertex3f(-3.0*offset, scale, -3.0*offset); glVertex3f(3.0*offset, scale, -3.0*offset); glVertex3f(3.0*offset, scale, 3.0*offset); glVertex3f(-3.0*offset, scale, 3.0*offset); glVertex3f(-scale, -3.0*offset, -3.0*offset); glVertex3f(-scale, 3.0*offset, -3.0*offset); glVertex3f(-scale, 3.0*offset, 3.0*offset); glVertex3f(-scale, -3.0*offset, 3.0*offset); // SetFaceColor(3); glVertex3f(scale, -3.0*offset, -3.0*offset); glVertex3f(scale, 3.0*offset, -3.0*offset); glVertex3f(scale, 3.0*offset, 3.0*offset); glVertex3f(scale, -3.0*offset, 3.0*offset); // SetFaceColor(2); glVertex3f(-3.0*offset, -3.0*offset, -scale); glVertex3f(3.0*offset, -3.0*offset, -scale); glVertex3f(3.0*offset, 3.0*offset, -scale); glVertex3f(-3.0*offset, 3.0*offset, -scale); // SetFaceColor(4); glVertex3f(-3.0*offset, -3.0*offset, scale); glVertex3f(3.0*offset, -3.0*offset, scale); glVertex3f(3.0*offset, 3.0*offset, scale); glVertex3f(-3.0*offset, 3.0*offset, scale); glEnd(); } void RubiksCube::SetFaceColor(int theColor) const { switch (theColor) { case 0: glColor3f(1.0, 0.0, 0.0); break; case 1: glColor3f(0.0, 1.0, 0.0); break; case 2: glColor3f(0.0, 0.0, 1.0); break; case 3: glColor3f(1.0, 1.0, 0.0); break; case 4: glColor3f(1.0, 0.5, 0.0); break; case 5: glColor3f(1.0, 1.0, 1.0); break; default: assert(false); } } /** Draw the transition at some percentage 0...1 between two states */ void RubiksCube::OpenGLDraw(const RubiksState&, const RubiksState&, float) const { } void RubiksCube::OpenGLDraw(const RubiksState&, const RubiksAction&) const { } <commit_msg>modified heuristic code<commit_after>// // RubiksCube.cpp // hog2 glut // // Created by Nathan Sturtevant on 4/6/13. // Copyright (c) 2013 University of Denver. All rights reserved. // #include "RubiksCube.h" #include <cassert> #include <cstdio> #include <algorithm> void RubiksCube::GetSuccessors(const RubiksState &nodeID, std::vector<RubiksState> &neighbors) const { neighbors.resize(18); for (int x = 0; x < 18; x++) { GetNextState(nodeID, x, neighbors[x]); } } void RubiksCube::GetActions(const RubiksState &nodeID, std::vector<RubiksAction> &actions) const { actions.resize(0); if (!pruneSuccessors || history.size() == 0) { for (int x = 0; x < 18; x++) actions.push_back(x); } else { // 0, 5, 2, 4, 1, 3 for (int x = 0; x < 18; x++) { // 1. after any face you can't turn the same face again if (x/3 == history.back()/3) continue; // 2. after faces 5, 4, 3 you can't turn 0, 2, 1 respectively if ((1 == (history.back()/3)%2) && (x/3+1 == history.back()/3)) continue; actions.push_back(x); } } // std::random_shuffle(actions.begin(), actions.end()); } RubiksAction RubiksCube::GetAction(const RubiksState &s1, const RubiksState &s2) const { //std::vector<RubiksAction> succ; //GetActions(s1, succ); RubiksState tmp; for (int x = 0; x < 18; x++) { GetNextState(s1, x, tmp); if (tmp == s2) return x; } assert(false); return 0; } void RubiksCube::ApplyAction(RubiksState &s, RubiksAction a) const { c.ApplyAction(s.corner, a); e.ApplyAction(s.edge, a); e7.ApplyAction(s.edge7, a); if (pruneSuccessors) history.push_back(a); } void RubiksCube::UndoAction(RubiksState &s, RubiksAction a) const { if (pruneSuccessors && history.size() > 0) { assert(history.back() == a); history.pop_back(); } InvertAction(a); c.ApplyAction(s.corner, a); e.ApplyAction(s.edge, a); e7.ApplyAction(s.edge7, a); } void RubiksCube::GetNextState(const RubiksState &s1, RubiksAction a, RubiksState &s2) const { s2 = s1; ApplyAction(s2, a); } bool RubiksCube::InvertAction(RubiksAction &a) const { if (2 == a%3) return true; if (1 == a%3) { a -= 1; return true; } a += 1; return true; } /** Heuristic value between two arbitrary nodes. **/ double RubiksCube::HCost(const RubiksState &node1, const RubiksState &node2) { double val = 0; // corner PDB uint64_t hash = c.GetStateHash(node1.corner); val = cornerPDB.Get(hash); if (minCompression) { // edge PDB hash = e7.GetStateHash(node1.edge7); // // edge PDB double val2 = edge7PDBmin.Get(hash/compressionFactor); val = max(val, val2); node1.edge7.GetDual(e7dual); hash = e7.GetStateHash(e7dual); val2 = edge7PDBmin.Get(hash/compressionFactor); val = max(val, val2); } else if (!minCompression) // interleave { // edge PDB hash = e7.GetStateHash(node1.edge7); // // edge PDB if (0 == hash%compressionFactor) { double val2 = edge7PDBint.Get(hash/compressionFactor); val = max(val, val2); } node1.edge7.GetDual(e7dual); hash = e7.GetStateHash(e7dual); if (0 == hash%compressionFactor) { double val2 = edge7PDBint.Get(hash/compressionFactor); val = max(val, val2); } } return val; // load PDB values directly from disk! // make sure that "data" is initialized with the right constructor calls for the data // int64_t r1, r2; // e.rankPlayer(node1.edge, 0, r1, r2); // double edge = f.ReadFileDepth(data[r1].bucketID, data[r1].bucketOffset+r2); // if (edge > 10) // edge = 10; // val = max(val, edge); return val; } /** Heuristic value between node and the stored goal. Asserts that the goal is stored **/ double RubiksCube::HCost(const RubiksState &node) { return 0; } bool RubiksCube::GoalTest(const RubiksState &node, const RubiksState &goal) { return (node.corner.state == goal.corner.state && node.edge.state == goal.edge.state); } /** Goal Test if the goal is stored **/ bool RubiksCube::GoalTest(const RubiksState &node) { assert(false); return false; } uint64_t RubiksCube::GetStateHash(const RubiksState &node) const { uint64_t hash = c.GetStateHash(node.corner); hash *= e.getMaxSinglePlayerRank(); hash += e.GetStateHash(node.edge); return hash; } void RubiksCube::GetStateFromHash(uint64_t hash, RubiksState &node) const { e.GetStateFromHash(hash%e.getMaxSinglePlayerRank(), node.edge); c.GetStateFromHash(hash/e.getMaxSinglePlayerRank(), node.corner); } void RubiksCube::OpenGLDraw() const { } void RubiksCube::OpenGLDraw(const RubiksState&s) const { e.OpenGLDraw(s.edge); c.OpenGLDraw(s.corner); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawCorners(const RubiksState&s) const { c.OpenGLDraw(s.corner); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawEdges(const RubiksState&s) const { Rubik7EdgeState e7tmp; s.edge7.GetDual(e7tmp); e7.OpenGLDraw(e7tmp); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawEdgeDual(const RubiksState&s) const { s.edge.GetDual(dual); e.OpenGLDraw(dual); OpenGLDrawCenters(); } void RubiksCube::OpenGLDrawCenters() const { float scale = 0.3; float offset = 0.95*scale/3.0; glBegin(GL_QUADS); SetFaceColor(0); glVertex3f(-offset, -scale, -offset); glVertex3f(offset, -scale, -offset); glVertex3f(offset, -scale, offset); glVertex3f(-offset, -scale, offset); SetFaceColor(5); glVertex3f(-offset, scale, -offset); glVertex3f(offset, scale, -offset); glVertex3f(offset, scale, offset); glVertex3f(-offset, scale, offset); SetFaceColor(1); glVertex3f(-scale, -offset, -offset); glVertex3f(-scale, offset, -offset); glVertex3f(-scale, offset, offset); glVertex3f(-scale, -offset, offset); SetFaceColor(3); glVertex3f(scale, -offset, -offset); glVertex3f(scale, offset, -offset); glVertex3f(scale, offset, offset); glVertex3f(scale, -offset, offset); SetFaceColor(2); glVertex3f(-offset, -offset, -scale); glVertex3f(offset, -offset, -scale); glVertex3f(offset, offset, -scale); glVertex3f(-offset, offset, -scale); SetFaceColor(4); glVertex3f(-offset, -offset, scale); glVertex3f(offset, -offset, scale); glVertex3f(offset, offset, scale); glVertex3f(-offset, offset, scale); glColor3f(0,0,0); offset = scale/3.0; scale*=0.99; glVertex3f(-3.0*offset, -scale, -3.0*offset); glVertex3f(3.0*offset, -scale, -3.0*offset); glVertex3f(3.0*offset, -scale, 3.0*offset); glVertex3f(-3.0*offset, -scale, 3.0*offset); glVertex3f(-3.0*offset, scale, -3.0*offset); glVertex3f(3.0*offset, scale, -3.0*offset); glVertex3f(3.0*offset, scale, 3.0*offset); glVertex3f(-3.0*offset, scale, 3.0*offset); glVertex3f(-scale, -3.0*offset, -3.0*offset); glVertex3f(-scale, 3.0*offset, -3.0*offset); glVertex3f(-scale, 3.0*offset, 3.0*offset); glVertex3f(-scale, -3.0*offset, 3.0*offset); // SetFaceColor(3); glVertex3f(scale, -3.0*offset, -3.0*offset); glVertex3f(scale, 3.0*offset, -3.0*offset); glVertex3f(scale, 3.0*offset, 3.0*offset); glVertex3f(scale, -3.0*offset, 3.0*offset); // SetFaceColor(2); glVertex3f(-3.0*offset, -3.0*offset, -scale); glVertex3f(3.0*offset, -3.0*offset, -scale); glVertex3f(3.0*offset, 3.0*offset, -scale); glVertex3f(-3.0*offset, 3.0*offset, -scale); // SetFaceColor(4); glVertex3f(-3.0*offset, -3.0*offset, scale); glVertex3f(3.0*offset, -3.0*offset, scale); glVertex3f(3.0*offset, 3.0*offset, scale); glVertex3f(-3.0*offset, 3.0*offset, scale); glEnd(); } void RubiksCube::SetFaceColor(int theColor) const { switch (theColor) { case 0: glColor3f(1.0, 0.0, 0.0); break; case 1: glColor3f(0.0, 1.0, 0.0); break; case 2: glColor3f(0.0, 0.0, 1.0); break; case 3: glColor3f(1.0, 1.0, 0.0); break; case 4: glColor3f(1.0, 0.5, 0.0); break; case 5: glColor3f(1.0, 1.0, 1.0); break; default: assert(false); } } /** Draw the transition at some percentage 0...1 between two states */ void RubiksCube::OpenGLDraw(const RubiksState&, const RubiksState&, float) const { } void RubiksCube::OpenGLDraw(const RubiksState&, const RubiksAction&) const { } <|endoftext|>
<commit_before>// // Macintosh.cpp // Clock Signal // // Created by Thomas Harte on 03/05/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #include "Macintosh.hpp" #include "Video.hpp" #include "../../CRTMachine.hpp" #include "../../../Processors/68000/68000.hpp" #include "../../../Components/6522/6522.hpp" #include "../../Utility/MemoryPacker.hpp" namespace Apple { namespace Macintosh { class ConcreteMachine: public Machine, public CRTMachine::Machine, public CPU::MC68000::BusHandler { public: ConcreteMachine(const ROMMachine::ROMFetcher &rom_fetcher) : mc68000_(*this), video_(ram_), via_(via_port_handler_) { // Grab a copy of the ROM and convert it into big-endian data. const auto roms = rom_fetcher("Macintosh", { "mac128k.rom" }); if(!roms[0]) { throw ROMMachine::Error::MissingROMs; } roms[0]->resize(64*1024); Memory::PackBigEndian16(*roms[0], rom_); // The Mac runs at 7.8336mHz. set_clock_rate(7833600.0); } void set_scan_target(Outputs::Display::ScanTarget *scan_target) override { video_.set_scan_target(scan_target); } Outputs::Speaker::Speaker *get_speaker() override { return nullptr; } void run_for(const Cycles cycles) override { mc68000_.run_for(cycles); } HalfCycles perform_bus_operation(const CPU::MC68000::Microcycle &cycle, int is_supervisor) { via_.run_for(cycle.length); // TODO: the entirety of dealing with this cycle. /* Normal memory map: 000000: RAM 400000: ROM 9FFFF8+: SCC read operations BFFFF8+: SCC write operations DFE1FF+: IWM EFE1FE+: VIA Overlay mode: ROM replaces RAM at 00000, while also being at 400000 */ return HalfCycles(0); } /* Notes to self: accesses to the VIA are via the 68000's synchronous bus. */ private: class VIAPortHandler: public MOS::MOS6522::PortHandler { void set_port_output(MOS::MOS6522::Port port, uint8_t value, uint8_t direction_mask) { /* Port A: b7: [input] SCC wait/request (/W/REQA and /W/REQB wired together for a logical OR) b6: 0 = alternate screen buffer, 1 = main screen buffer b5: floppy disk SEL state control (upper/lower head "among other things") b4: 1 = use ROM overlay memory map, 0 = use ordinary memory map b3: 0 = use alternate sound buffer, 1 = use ordinary sound buffer b2–b0: audio output volume Port B: b7: 0 = sound enabled, 1 = sound disabled b6: [input] 0 = video beam in visible portion of line, 1 = outside b5: [input] mouse y2 b4: [input] mouse x2 b3: [input] 0 = mouse button down, 1 = up b2: 0 = real-time clock enabled, 1 = disabled b1: clock's data-clock line b0: clock's serial data line Peripheral lines: keyboard data, interrupt configuration. (See p176 [/215]) */ } }; CPU::MC68000::Processor<ConcreteMachine, true> mc68000_; Video video_; MOS::MOS6522::MOS6522<VIAPortHandler> via_; VIAPortHandler via_port_handler_; uint16_t rom_[32*1024]; uint16_t ram_[64*1024]; }; } } using namespace Apple::Macintosh; Machine *Machine::Macintosh(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) { return new ConcreteMachine(rom_fetcher); } Machine::~Machine() {} <commit_msg>Starts negotiating the Macintosh memory map.<commit_after>// // Macintosh.cpp // Clock Signal // // Created by Thomas Harte on 03/05/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #include "Macintosh.hpp" #include <array> #include "Video.hpp" #include "../../CRTMachine.hpp" #include "../../../Processors/68000/68000.hpp" #include "../../../Components/6522/6522.hpp" #include "../../Utility/MemoryPacker.hpp" namespace Apple { namespace Macintosh { class ConcreteMachine: public Machine, public CRTMachine::Machine, public CPU::MC68000::BusHandler { public: ConcreteMachine(const ROMMachine::ROMFetcher &rom_fetcher) : mc68000_(*this), video_(ram_.data()), via_(via_port_handler_) { // Grab a copy of the ROM and convert it into big-endian data. const auto roms = rom_fetcher("Macintosh", { "mac128k.rom" }); if(!roms[0]) { throw ROMMachine::Error::MissingROMs; } roms[0]->resize(64*1024); Memory::PackBigEndian16(*roms[0], rom_.data()); // The Mac runs at 7.8336mHz. set_clock_rate(7833600.0); } void set_scan_target(Outputs::Display::ScanTarget *scan_target) override { video_.set_scan_target(scan_target); } Outputs::Speaker::Speaker *get_speaker() override { return nullptr; } void run_for(const Cycles cycles) override { mc68000_.run_for(cycles); } using Microcycle = CPU::MC68000::Microcycle; HalfCycles perform_bus_operation(const Microcycle &cycle, int is_supervisor) { // Assumption here: it's a divide by ten to derive the 6522 clock, i.e. // it runs off the 68000's E clock. via_clock_ += cycle.length; via_.run_for(via_clock_.divide(HalfCycles(10))); // SCC is a divide-by-two. // A null cycle leaves nothing else to do. if(cycle.operation) { auto word_address = cycle.word_address(); // Hardware devices begin at 0x800000. mc68000_.set_is_peripheral_address(word_address >= 0x400000); if(word_address >= 0x400000) { printf("IO access to %06x\n", word_address << 1); } else { if(cycle.data_select_active()) { uint16_t *memory_base = nullptr; bool is_read_only = false; if(word_address & 0x200000 || ROM_is_overlay_) { memory_base = rom_.data(); word_address %= rom_.size(); is_read_only = true; } else { memory_base = ram_.data(); word_address %= ram_.size(); is_read_only = false; } if(!is_read_only || (cycle.operation & Microcycle::Read)) { switch(cycle.operation & (Microcycle::SelectWord | Microcycle::SelectByte | Microcycle::Read | Microcycle::InterruptAcknowledge)) { default: break; case Microcycle::SelectWord | Microcycle::Read: cycle.value->full = memory_base[word_address]; break; case Microcycle::SelectByte | Microcycle::Read: cycle.value->halves.low = uint8_t(memory_base[word_address] >> cycle.byte_shift()); break; case Microcycle::SelectWord: memory_base[word_address] = cycle.value->full; break; case Microcycle::SelectByte: memory_base[word_address] = uint16_t( (cycle.value->halves.low << cycle.byte_shift()) | (memory_base[word_address] & (0xffff ^ cycle.byte_mask())) ); break; } } } else { // Add delay if this is a RAM access and video blocks it momentarily. } } } // Any access to the // TODO: the entirety of dealing with this cycle. /* Normal memory map: 000000: RAM 400000: ROM 9FFFF8+: SCC read operations BFFFF8+: SCC write operations DFE1FF+: IWM EFE1FE+: VIA Overlay mode: ROM replaces RAM at 00000, while also being at 400000 */ return HalfCycles(0); } /* Notes to self: accesses to the VIA are via the 68000's synchronous bus. */ private: class VIAPortHandler: public MOS::MOS6522::PortHandler { void set_port_output(MOS::MOS6522::Port port, uint8_t value, uint8_t direction_mask) { /* Port A: b7: [input] SCC wait/request (/W/REQA and /W/REQB wired together for a logical OR) b6: 0 = alternate screen buffer, 1 = main screen buffer b5: floppy disk SEL state control (upper/lower head "among other things") b4: 1 = use ROM overlay memory map, 0 = use ordinary memory map b3: 0 = use alternate sound buffer, 1 = use ordinary sound buffer b2–b0: audio output volume Port B: b7: 0 = sound enabled, 1 = sound disabled b6: [input] 0 = video beam in visible portion of line, 1 = outside b5: [input] mouse y2 b4: [input] mouse x2 b3: [input] 0 = mouse button down, 1 = up b2: 0 = real-time clock enabled, 1 = disabled b1: clock's data-clock line b0: clock's serial data line Peripheral lines: keyboard data, interrupt configuration. (See p176 [/215]) */ } }; std::array<uint16_t, 32*1024> rom_; std::array<uint16_t, 64*1024> ram_; CPU::MC68000::Processor<ConcreteMachine, true> mc68000_; Video video_; MOS::MOS6522::MOS6522<VIAPortHandler> via_; VIAPortHandler via_port_handler_; HalfCycles via_clock_; bool ROM_is_overlay_ = true; }; } } using namespace Apple::Macintosh; Machine *Machine::Macintosh(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) { return new ConcreteMachine(rom_fetcher); } Machine::~Machine() {} <|endoftext|>
<commit_before>#include "AudioManager.h" #include <SDL.h> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include <views/SystemView.h> #include "Log.h" #include "RecalboxConf.h" #include "Settings.h" #include "ThemeData.h" std::vector<std::shared_ptr<Sound>> AudioManager::sSoundVector; std::vector<std::shared_ptr<Music>> AudioManager::sMusicVector; std::shared_ptr<AudioManager> AudioManager::sInstance; AudioManager::AudioManager() : currentMusic(NULL), running(0) { init(); } AudioManager::~AudioManager() { deinit(); } std::shared_ptr<AudioManager> &AudioManager::getInstance() { //check if an AudioManager instance is already created, if not create one if (sInstance == nullptr) { sInstance = std::shared_ptr<AudioManager>(new AudioManager); } return sInstance; } void AudioManager::init() { runningFromPlaylist = false; if (running == 0) { if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) { LOG(LogError) << "Error initializing SDL audio!\n" << SDL_GetError(); return; } //Open the audio device and pause if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) < 0) { LOG(LogError) << "MUSIC Error - Unable to open SDLMixer audio: " << SDL_GetError() << std::endl; } else { LOG(LogInfo) << "SDL AUDIO Initialized"; running = 1; } } } void AudioManager::deinit() { //stop all playback //stop(); //completely tear down SDL audio. else SDL hogs audio resources and emulators might fail to start... LOG(LogInfo) << "Shutting down SDL AUDIO"; Mix_HaltMusic(); Mix_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); running = 0; } void AudioManager::stopMusic() { Mix_FadeOutMusic(1000); Mix_HaltMusic(); currentMusic = NULL; } void musicEndInternal() { AudioManager::getInstance()->musicEnd(); } void AudioManager::themeChanged(const std::shared_ptr<ThemeData> &theme) { if (RecalboxConf::getInstance()->get("audio.bgmusic") == "1") { const ThemeData::ThemeElement *elem = theme->getElement("system", "directory", "sound"); if (!elem || !elem->has("path")) { currentThemeMusicDirectory = ""; } else { currentThemeMusicDirectory = elem->get<std::string>("path"); } std::shared_ptr<Music> bgsound = Music::getFromTheme(theme, "system", "bgsound"); // Found a music for the system if (bgsound) { runningFromPlaylist = false; stopMusic(); bgsound->play(true, NULL); currentMusic = bgsound; return; } if (!runningFromPlaylist) { playRandomMusic(); } } } void AudioManager::playRandomMusic() {// Find a random song in user directory or theme music directory std::shared_ptr<Music> bgsound = getRandomMusic(currentThemeMusicDirectory); if (bgsound) { runningFromPlaylist = true; stopMusic(); bgsound->play(false, musicEndInternal); currentMusic = bgsound; return; } else { // Not running from playlist, and no theme song found stopMusic(); } } void AudioManager::resumeMusic() { this->init(); if (currentMusic != NULL && RecalboxConf::getInstance()->get("audio.bgmusic") == "1") { currentMusic->play(runningFromPlaylist ? false : true, runningFromPlaylist ? musicEndInternal : NULL); } } void AudioManager::registerSound(std::shared_ptr<Sound> &sound) { getInstance(); sSoundVector.push_back(sound); } void AudioManager::registerMusic(std::shared_ptr<Music> &music) { getInstance(); sMusicVector.push_back(music); } void AudioManager::unregisterSound(std::shared_ptr<Sound> &sound) { getInstance(); for (unsigned int i = 0; i < sSoundVector.size(); i++) { if (sSoundVector.at(i) == sound) { sSoundVector[i]->stop(); sSoundVector.erase(sSoundVector.begin() + i); return; } } LOG(LogError) << "AudioManager Error - tried to unregister a sound that wasn't registered!"; } void AudioManager::unregisterMusic(std::shared_ptr<Music> &music) { getInstance(); for (unsigned int i = 0; i < sMusicVector.size(); i++) { if (sMusicVector.at(i) == music) { //sMusicVector[i]->stop(); sMusicVector.erase(sMusicVector.begin() + i); return; } } LOG(LogError) << "AudioManager Error - tried to unregister a music that wasn't registered!"; } void AudioManager::play() { getInstance(); //unpause audio, the mixer will figure out if samples need to be played... //SDL_PauseAudio(0); } void AudioManager::stop() { //stop playing all Sounds for (unsigned int i = 0; i < sSoundVector.size(); i++) { if (sSoundVector.at(i)->isPlaying()) { sSoundVector[i]->stop(); } } //stop playing all Musics //pause audio //SDL_PauseAudio(1); } std::vector<std::string> getMusicIn(const std::string &path) { std::vector<std::string> all_matching_files; if (!boost::filesystem::is_directory(path)) { return all_matching_files; } const std::string target_path(path); const boost::regex my_filter(".*\\.(mp3|ogg)$"); boost::filesystem::directory_iterator end_itr; // Default ctor yields past-the-end for (boost::filesystem::directory_iterator i(target_path); i != end_itr; ++i) { // Skip if not a file if (!boost::filesystem::is_regular_file(i->status())) continue; boost::smatch what; // Skip if no match if (!boost::regex_match(i->path().string(), what, my_filter)) continue; // File matches, store it all_matching_files.push_back(i->path().string()); } } std::shared_ptr<Music> AudioManager::getRandomMusic(std::string themeSoundDirectory) { // 1 check in User music directory std::vector<std::string> musics = getMusicIn(Settings::getInstance()->getString("MusicDirectory")); if (musics.empty()) { // Check in theme sound directory if (themeSoundDirectory != "") { musics = getMusicIn(themeSoundDirectory); if(musics.empty()) return NULL; } } int randomIndex = rand() % musics.size(); std::shared_ptr<Music> bgsound = Music::get(musics.at(randomIndex)); return bgsound; } void AudioManager::musicEnd() { LOG(LogInfo) << "MusicEnded"; if (runningFromPlaylist && RecalboxConf::getInstance()->get("audio.bgmusic") == "1") { playRandomMusic(); } } <commit_msg>fixed no music anywhere bug<commit_after>#include "AudioManager.h" #include <SDL.h> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include <views/SystemView.h> #include "Log.h" #include "RecalboxConf.h" #include "Settings.h" #include "ThemeData.h" std::vector<std::shared_ptr<Sound>> AudioManager::sSoundVector; std::vector<std::shared_ptr<Music>> AudioManager::sMusicVector; std::shared_ptr<AudioManager> AudioManager::sInstance; AudioManager::AudioManager() : currentMusic(NULL), running(0) { init(); } AudioManager::~AudioManager() { deinit(); } std::shared_ptr<AudioManager> &AudioManager::getInstance() { //check if an AudioManager instance is already created, if not create one if (sInstance == nullptr) { sInstance = std::shared_ptr<AudioManager>(new AudioManager); } return sInstance; } void AudioManager::init() { runningFromPlaylist = false; if (running == 0) { if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) { LOG(LogError) << "Error initializing SDL audio!\n" << SDL_GetError(); return; } //Open the audio device and pause if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) < 0) { LOG(LogError) << "MUSIC Error - Unable to open SDLMixer audio: " << SDL_GetError() << std::endl; } else { LOG(LogInfo) << "SDL AUDIO Initialized"; running = 1; } } } void AudioManager::deinit() { //stop all playback //stop(); //completely tear down SDL audio. else SDL hogs audio resources and emulators might fail to start... LOG(LogInfo) << "Shutting down SDL AUDIO"; Mix_HaltMusic(); Mix_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); running = 0; } void AudioManager::stopMusic() { Mix_FadeOutMusic(1000); Mix_HaltMusic(); currentMusic = NULL; } void musicEndInternal() { AudioManager::getInstance()->musicEnd(); } void AudioManager::themeChanged(const std::shared_ptr<ThemeData> &theme) { if (RecalboxConf::getInstance()->get("audio.bgmusic") == "1") { const ThemeData::ThemeElement *elem = theme->getElement("system", "directory", "sound"); if (!elem || !elem->has("path")) { currentThemeMusicDirectory = ""; } else { currentThemeMusicDirectory = elem->get<std::string>("path"); } std::shared_ptr<Music> bgsound = Music::getFromTheme(theme, "system", "bgsound"); // Found a music for the system if (bgsound) { runningFromPlaylist = false; stopMusic(); bgsound->play(true, NULL); currentMusic = bgsound; return; } if (!runningFromPlaylist) { playRandomMusic(); } } } void AudioManager::playRandomMusic() {// Find a random song in user directory or theme music directory std::shared_ptr<Music> bgsound = getRandomMusic(currentThemeMusicDirectory); if (bgsound) { runningFromPlaylist = true; stopMusic(); bgsound->play(false, musicEndInternal); currentMusic = bgsound; return; } else { // Not running from playlist, and no theme song found stopMusic(); } } void AudioManager::resumeMusic() { this->init(); if (currentMusic != NULL && RecalboxConf::getInstance()->get("audio.bgmusic") == "1") { currentMusic->play(runningFromPlaylist ? false : true, runningFromPlaylist ? musicEndInternal : NULL); } } void AudioManager::registerSound(std::shared_ptr<Sound> &sound) { getInstance(); sSoundVector.push_back(sound); } void AudioManager::registerMusic(std::shared_ptr<Music> &music) { getInstance(); sMusicVector.push_back(music); } void AudioManager::unregisterSound(std::shared_ptr<Sound> &sound) { getInstance(); for (unsigned int i = 0; i < sSoundVector.size(); i++) { if (sSoundVector.at(i) == sound) { sSoundVector[i]->stop(); sSoundVector.erase(sSoundVector.begin() + i); return; } } LOG(LogError) << "AudioManager Error - tried to unregister a sound that wasn't registered!"; } void AudioManager::unregisterMusic(std::shared_ptr<Music> &music) { getInstance(); for (unsigned int i = 0; i < sMusicVector.size(); i++) { if (sMusicVector.at(i) == music) { //sMusicVector[i]->stop(); sMusicVector.erase(sMusicVector.begin() + i); return; } } LOG(LogError) << "AudioManager Error - tried to unregister a music that wasn't registered!"; } void AudioManager::play() { getInstance(); //unpause audio, the mixer will figure out if samples need to be played... //SDL_PauseAudio(0); } void AudioManager::stop() { //stop playing all Sounds for (unsigned int i = 0; i < sSoundVector.size(); i++) { if (sSoundVector.at(i)->isPlaying()) { sSoundVector[i]->stop(); } } //stop playing all Musics //pause audio //SDL_PauseAudio(1); } std::vector<std::string> getMusicIn(const std::string &path) { std::vector<std::string> all_matching_files; if (!boost::filesystem::is_directory(path)) { return all_matching_files; } const std::string target_path(path); const boost::regex my_filter(".*\\.(mp3|ogg)$"); boost::filesystem::directory_iterator end_itr; // Default ctor yields past-the-end for (boost::filesystem::directory_iterator i(target_path); i != end_itr; ++i) { // Skip if not a file if (!boost::filesystem::is_regular_file(i->status())) continue; boost::smatch what; // Skip if no match if (!boost::regex_match(i->path().string(), what, my_filter)) continue; // File matches, store it all_matching_files.push_back(i->path().string()); } } std::shared_ptr<Music> AudioManager::getRandomMusic(std::string themeSoundDirectory) { // 1 check in User music directory std::vector<std::string> musics = getMusicIn(Settings::getInstance()->getString("MusicDirectory")); if (musics.empty()) { // Check in theme sound directory if (themeSoundDirectory != "") { musics = getMusicIn(themeSoundDirectory); if(musics.empty()) return NULL; } else return NULL; } int randomIndex = rand() % musics.size(); std::shared_ptr<Music> bgsound = Music::get(musics.at(randomIndex)); return bgsound; } void AudioManager::musicEnd() { LOG(LogInfo) << "MusicEnded"; if (runningFromPlaylist && RecalboxConf::getInstance()->get("audio.bgmusic") == "1") { playRandomMusic(); } } <|endoftext|>
<commit_before>#ifndef GNR_FORWARDER_HPP # define GNR_FORWARDER_HPP # pragma once #include <cassert> // std::size_t #include <cstddef> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail::forwarder { enum : std::size_t { default_size = 4 * sizeof(void*) }; template <typename, std::size_t, bool> class forwarder_impl2; template <typename R, typename ...A, std::size_t N, bool E> class forwarder_impl2<R (A...), N, E> { protected: R (*stub_)(void*, A&&...) noexcept(E) {}; std::aligned_storage_t<N> store_; public: using result_type = R; public: R operator()(A... args) const noexcept(E) { //assert(stub_); return stub_(const_cast<decltype(store_)*>(std::addressof(store_)), std::forward<A>(args)...); } template <typename F, typename = std::enable_if_t<std::is_invocable_r_v<R, F, A...>> > void assign(F&& f) #if !defined(__GNUC__) || defined(__clang__) noexcept(noexcept(std::decay_t<F>(std::forward<F>(f)))) #endif { using functor_type = std::decay_t<F>; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(std::is_trivially_copyable<functor_type>{}, "functor not trivially copyable"); ::new (std::addressof(store_)) functor_type(std::forward<F>(f)); stub_ = [](void* const ptr, A&&... args) noexcept(E) -> R { return std::invoke(*static_cast<functor_type*>(ptr), std::forward<A>(args)...); }; } }; template <typename, std::size_t> class forwarder_impl; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...), N> : public forwarder_impl2<R (A...), N, false> { }; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...) noexcept, N> : public forwarder_impl2<R (A...), N, true> { }; } template <typename A, std::size_t N = detail::forwarder::default_size> class forwarder : public detail::forwarder::forwarder_impl<A, N> { using inherited_t = detail::forwarder::forwarder_impl<A, N>; public: enum : std::size_t { size = N }; forwarder() = default; forwarder(forwarder const&) = default; forwarder(forwarder&&) = default; template <typename F> static constexpr auto have_assign(int) -> decltype(std::declval<inherited_t>().assign(std::declval<F>()), bool()) { return true; } template <typename F> static constexpr auto have_assign(...) { return false; } template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, forwarder> && have_assign<F>(int()) > > forwarder(F&& f) noexcept(noexcept(inherited_t::assign(std::forward<F>(f)))) { inherited_t::assign(std::forward<F>(f)); } forwarder& operator=(forwarder const&) = default; forwarder& operator=(forwarder&&) = default; template <typename F> forwarder& operator=(F&& f) noexcept( noexcept(inherited_t::assign(std::forward<F>(f)))) { static_assert(std::is_invocable_v< decltype(&inherited_t::template assign<F>), inherited_t&, F > ); inherited_t::assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return inherited_t::stub_; } bool operator==(std::nullptr_t) noexcept { return *this; } bool operator!=(std::nullptr_t) noexcept { return !operator==(nullptr); } void assign(std::nullptr_t) noexcept { reset(); } void reset() noexcept { inherited_t::stub_ = {}; } void swap(forwarder& other) noexcept { std::swap(*this, other); } void swap(forwarder&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() noexcept { return reinterpret_cast<T*>(std::addressof(inherited_t::store_)); } template <typename T> auto target() const noexcept { return reinterpret_cast<T const*>(std::addressof(inherited_t::store_)); } }; } #endif // GNR_FORWARDER_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_FORWARDER_HPP # define GNR_FORWARDER_HPP # pragma once #include <cassert> // std::size_t #include <cstddef> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail::forwarder { enum : std::size_t { default_size = 4 * sizeof(void*) }; template <typename, std::size_t, bool> class forwarder_impl2; template <typename R, typename ...A, std::size_t N, bool E> class forwarder_impl2<R (A...), N, E> { protected: R (*stub_)(void*, A&&...) noexcept(E) {}; std::aligned_storage_t<N> store_; template <typename F> static constexpr auto is_invocable() { return std::is_invocable_r_v<R, F, A...>; } public: using result_type = R; public: R operator()(A... args) const noexcept(E) { //assert(stub_); return stub_(const_cast<decltype(store_)*>(std::addressof(store_)), std::forward<A>(args)...); } template <typename F, typename = std::enable_if_t<std::is_invocable_r_v<R, F, A...>> > void assign(F&& f) noexcept(noexcept(std::decay_t<F>(std::forward<F>(f)))) { using functor_type = std::decay_t<F>; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(std::is_trivially_copyable<functor_type>{}, "functor not trivially copyable"); ::new (std::addressof(store_)) functor_type(std::forward<F>(f)); stub_ = [](void* const ptr, A&&... args) noexcept(E) -> R { return std::invoke(*static_cast<functor_type*>(ptr), std::forward<A>(args)...); }; } }; template <typename, std::size_t> class forwarder_impl; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...), N> : public forwarder_impl2<R (A...), N, false> { }; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...) noexcept, N> : public forwarder_impl2<R (A...), N, true> { }; } template <typename A, std::size_t N = detail::forwarder::default_size> class forwarder : public detail::forwarder::forwarder_impl<A, N> { using inherited_t = detail::forwarder::forwarder_impl<A, N>; public: enum : std::size_t { size = N }; forwarder() = default; forwarder(forwarder const&) = default; forwarder(forwarder&&) = default; template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, forwarder> && inherited_t::template is_invocable<F>() > > forwarder(F&& f) noexcept(noexcept(inherited_t::assign(std::forward<F>(f)))) { inherited_t::assign(std::forward<F>(f)); } forwarder& operator=(forwarder const&) = default; forwarder& operator=(forwarder&&) = default; template <typename F> forwarder& operator=(F&& f) noexcept( noexcept(inherited_t::assign(std::forward<F>(f)))) { static_assert(std::is_invocable_v< decltype(&inherited_t::template assign<F>), inherited_t&, F > ); inherited_t::assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return inherited_t::stub_; } bool operator==(std::nullptr_t) noexcept { return *this; } bool operator!=(std::nullptr_t) noexcept { return !operator==(nullptr); } void assign(std::nullptr_t) noexcept { reset(); } void reset() noexcept { inherited_t::stub_ = {}; } void swap(forwarder& other) noexcept { std::swap(*this, other); } void swap(forwarder&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() noexcept { return reinterpret_cast<T*>(std::addressof(inherited_t::store_)); } template <typename T> auto target() const noexcept { return reinterpret_cast<T const*>(std::addressof(inherited_t::store_)); } }; } #endif // GNR_FORWARDER_HPP <|endoftext|>
<commit_before>#ifndef GNR_FORWARDER_HPP # define GNR_FORWARDER_HPP # pragma once #include <cassert> // std::size_t #include <cstddef> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail::forwarder { enum : std::size_t { default_size = 4 * sizeof(void*) }; template <typename, std::size_t, bool> class forwarder_impl2; template <typename R, typename ...A, std::size_t N, bool E> class forwarder_impl2<R (A...), N, E> { protected: R (*stub_)(void*, A&&...) noexcept(E) {}; std::aligned_storage_t<N> store_; public: using result_type = R; public: R operator()(A... args) const noexcept(E) { //assert(stub_); return stub_(const_cast<decltype(store_)*>(std::addressof(store_)), std::forward<A>(args)...); } template <typename F, typename = std::enable_if_t<std::is_invocable_r_v<R, F, A...>> > void assign(F&& f) noexcept(noexcept(std::decay_t<F>(std::forward<F>(f)))) { using functor_type = std::decay_t<F>; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(std::is_trivially_copyable<functor_type>{}, "functor not trivially copyable"); ::new (std::addressof(store_)) functor_type(std::forward<F>(f)); stub_ = [](void* const ptr, A&&... args) noexcept(E) -> R { return std::invoke(*static_cast<functor_type*>(ptr), std::forward<A>(args)...); }; } }; template <typename, std::size_t> class forwarder_impl; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...), N> : public forwarder_impl2<R (A...), N, false> { }; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...) noexcept, N> : public forwarder_impl2<R (A...), N, true> { }; } template <typename A, std::size_t N = detail::forwarder::default_size> class forwarder : public detail::forwarder::forwarder_impl<A, N> { using inherited_t = detail::forwarder::forwarder_impl<A, N>; public: enum : std::size_t { size = N }; forwarder() = default; forwarder(forwarder const&) = default; forwarder(forwarder&&) = default; template <typename F> static constexpr auto have_assign(int) -> decltype(inherited_t::template assign<F>(std::declval<F>()), bool()) { return true; } template <typename F> static constexpr auto have_assign(...) { return false; } template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, forwarder> && have_assign<F>(int()) > > forwarder(F&& f) noexcept(noexcept(inherited_t::assign(std::forward<F>(f)))) { inherited_t::assign(std::forward<F>(f)); } forwarder& operator=(forwarder const&) = default; forwarder& operator=(forwarder&&) = default; template <typename F> forwarder& operator=(F&& f) noexcept( noexcept(inherited_t::assign(std::forward<F>(f)))) { static_assert(std::is_invocable_v< decltype(&inherited_t::template assign<F>), inherited_t&, F > ); inherited_t::assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return inherited_t::stub_; } bool operator==(std::nullptr_t) noexcept { return *this; } bool operator!=(std::nullptr_t) noexcept { return !operator==(nullptr); } void assign(std::nullptr_t) noexcept { reset(); } void reset() noexcept { inherited_t::stub_ = {}; } void swap(forwarder& other) noexcept { std::swap(*this, other); } void swap(forwarder&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() noexcept { return reinterpret_cast<T*>(std::addressof(inherited_t::store_)); } template <typename T> auto target() const noexcept { return reinterpret_cast<T const*>(std::addressof(inherited_t::store_)); } }; } #endif // GNR_FORWARDER_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_FORWARDER_HPP # define GNR_FORWARDER_HPP # pragma once #include <cassert> // std::size_t #include <cstddef> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail::forwarder { enum : std::size_t { default_size = 4 * sizeof(void*) }; template <typename, std::size_t, bool> class forwarder_impl2; template <typename R, typename ...A, std::size_t N, bool E> class forwarder_impl2<R (A...), N, E> { protected: R (*stub_)(void*, A&&...) noexcept(E) {}; std::aligned_storage_t<N> store_; public: using result_type = R; public: R operator()(A... args) const noexcept(E) { //assert(stub_); return stub_(const_cast<decltype(store_)*>(std::addressof(store_)), std::forward<A>(args)...); } template <typename F> void assign(F&& f) noexcept(noexcept(std::decay_t<F>(std::forward<F>(f)))) { using functor_type = std::decay_t<F>; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(std::is_trivially_copyable<functor_type>{}, "functor not trivially copyable"); ::new (std::addressof(store_)) functor_type(std::forward<F>(f)); stub_ = [](void* const ptr, A&&... args) noexcept(E) -> R { return std::invoke(*static_cast<functor_type*>(ptr), std::forward<A>(args)...); }; } }; template <typename, std::size_t> class forwarder_impl; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...), N> : public forwarder_impl2<R (A...), N, false> { }; template <typename R, typename ...A, std::size_t N> class forwarder_impl<R (A...) noexcept, N> : public forwarder_impl2<R (A...), N, true> { }; } template <typename A, std::size_t N = detail::forwarder::default_size> class forwarder : public detail::forwarder::forwarder_impl<A, N> { using inherited_t = detail::forwarder::forwarder_impl<A, N>; public: enum : std::size_t { size = N }; forwarder() = default; forwarder(forwarder const&) = default; forwarder(forwarder&&) = default; template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, forwarder> > > forwarder(F&& f) noexcept(noexcept(inherited_t::assign(std::forward<F>(f)))) { inherited_t::assign(std::forward<F>(f)); } forwarder& operator=(forwarder const&) = default; forwarder& operator=(forwarder&&) = default; template <typename F> forwarder& operator=(F&& f) noexcept( noexcept(inherited_t::assign(std::forward<F>(f)))) { static_assert(std::is_invocable_v< decltype(&inherited_t::template assign<F>), inherited_t&, F > ); inherited_t::assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return inherited_t::stub_; } bool operator==(std::nullptr_t) noexcept { return *this; } bool operator!=(std::nullptr_t) noexcept { return !operator==(nullptr); } void assign(std::nullptr_t) noexcept { reset(); } void reset() noexcept { inherited_t::stub_ = {}; } void swap(forwarder& other) noexcept { std::swap(*this, other); } void swap(forwarder&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() noexcept { return reinterpret_cast<T*>(std::addressof(inherited_t::store_)); } template <typename T> auto target() const noexcept { return reinterpret_cast<T const*>(std::addressof(inherited_t::store_)); } }; } #endif // GNR_FORWARDER_HPP <|endoftext|>
<commit_before>AliXiStar *AddTaskXiStar(bool MCcase=kFALSE, bool AODcase=kFALSE, int CutList=0) { //=========================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskXiStar", "No analysis manager to connect to."); return NULL; } //____________________________________________// // Create tasks AliXiStar *XiStarTask = new AliXiStar("XiStarTask", AODcase, MCcase, CutList); if(!XiStarTask) exit(-1); mgr->AddTask(XiStarTask); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWGLF.outputXiStarAnalysis.root"; AliAnalysisDataContainer *coutXiStar = mgr->CreateContainer("XiStarOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); mgr->ConnectInput(XiStarTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(XiStarTask, 1, coutXiStar); // Return the task pointer return XiStarTask; } <commit_msg>Add comments for AOD and ESD selection<commit_after>AliXiStar *AddTaskXiStar(bool MCcase=kFALSE, bool AODcase=kFALSE, int CutList=0) { //=========================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskXiStar", "No analysis manager to connect to."); return NULL; } if (AODcase == kTRUE) { Printf("INFO! You are using AODs!");} //____________________________________________// // Create tasks AliXiStar *XiStarTask = new AliXiStar("XiStarTask", AODcase, MCcase, CutList); if(!XiStarTask) exit(-1); mgr->AddTask(XiStarTask); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWGLF.outputXiStarAnalysis.root"; AliAnalysisDataContainer *coutXiStar = mgr->CreateContainer("XiStarOutput", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); mgr->ConnectInput(XiStarTask, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(XiStarTask, 1, coutXiStar); // Return the task pointer return XiStarTask; } <|endoftext|>
<commit_before>#include "plant_generator.h" #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <numeric> #include <random> #include <type_traits> #include <asdf_multiplat/main/asdf_defs.h> #include "from_json.h" using namespace std; namespace plantgen { //std::vector<std::string> roll_multi_value(multi_value_t const& m); std::mt19937 mt_rand( std::chrono::high_resolution_clock::now().time_since_epoch().count() ); int random_int(uint32_t min, uint32_t max) { std::uniform_int_distribution<int> dis(min,max); return dis(mt_rand); } int random_int(uint32_t max) { return random_int(0, max); } template <typename L> uint32_t total_weight(L const& list) { uint32_t total = 0; for(auto const& v : list) total += v.weight; return total; } std::vector<std::string> roll_multi_value(multi_value_t const& m) { if(m.num_to_pick >= m.values.size()) return m.values; std::vector<size_t> inds(m.values.size()); std::iota(inds.begin(), inds.end(), size_t(0)); //0, 1, 2, 3, ..., size-1 std::shuffle(inds.begin(), inds.end(), std::mt19937{std::random_device{}()}); std::vector<std::string> output; output.reserve(m.num_to_pick); for(size_t i = 0; i < m.num_to_pick; ++i) output.push_back(m.values[inds[i]]); return output; } std::vector<std::string> roll_range_value(range_value_t const& r) { std::vector<std::string> output; output.reserve(r.size()); uint32_t counter = 0; for(size_t i = 0; i < r.size() - 1; ++i) { int roll = 0; if(counter < 100) roll = random_int(100 - counter); counter += roll; output.push_back(std::to_string(roll) + "% " + r[i]); } //push remaining output.push_back(std::to_string(100 - counter) + "% " + r.back()); return output; } /// Runtime version (compile-time visitor pattern doesn't compile in msvc) std::vector<std::string> roll_value(weighted_value_t const& variant_val) { std::vector<std::string> output; if(auto* s = std::get_if<std::string>(&variant_val)) { output.push_back(*s); } else if(auto* r = std::get_if<range_value_t>(&variant_val)) { auto rolled_range = roll_range_value(*r); output.insert(output.end(), rolled_range.begin(), rolled_range.end()); } else if(auto* m = std::get_if<multi_value_t>(&variant_val)) { auto rolled_multi = roll_multi_value(*m); output.insert(output.end(), rolled_multi.begin(), rolled_multi.end()); } else { EXPLODE("unexpected variant sub-type"); } return output; } generated_node_t roll_values(value_list_t const& values, std::vector<pregen_node_t> const& value_nodes) { if(values.empty() && value_nodes.empty()) return generated_node_t(); uint32_t total = total_weight(values) + total_weight(value_nodes); int roll = random_int(total); for(size_t i = 0; i < values.size(); ++i) { if(roll <= values[i].weight) { generated_node_t node; node.generated_values = std::move(roll_value(values[i])); return node; } roll -= values[i].weight; } //if no value from the value list has been hit yet, continue onward into value_nodes for(size_t i = 0; i < value_nodes.size(); ++i) { if(roll <= value_nodes[i].weight) { generated_node_t node(value_nodes[i].name); //node.add_child(generate_node(value_nodes[i])); auto gend_node = generate_node(value_nodes[i]); node.add_value_node(std::move(gend_node)); return node; } roll -= value_nodes[i].weight; } EXPLODE("Random roll was too large, ran out of values and value_nodes"); return generated_node_t("ERROR"); } generated_node_t roll_values(pregen_node_t const& node) { return roll_values(node.values, node.value_nodes); } pregen_node_t node_from_file(stdfs::path const& filepath) { using namespace std; auto ext = filepath.extension(); if(ext == ".json") { return node_from_json(filepath); } else if(ext == ".yaml" || ext == ".yml") { cout << "TODO: yaml support"; return pregen_node_t(); } //TODO: exception? if(stdfs::is_directory(filepath)) cout << filepath.string() << " is a directory, not a file"; else cout << "Filetype " << ext << " not recognized"; return pregen_node_t(); } generated_node_t generate_node(pregen_node_t const& pre_node) { generated_node_t node; node.name = pre_node.name; for(auto const& child : pre_node.children) { node.add_child(generate_node(child)); } if(pre_node.values.size() > 0 || pre_node.value_nodes.size() > 0) { generated_node_t rolled = roll_values(pre_node); node.merge_with(rolled); } auto search = pre_node.user_data.find("PrintString"); if(search != pre_node.user_data.end()) { node.print_string = std::get<std::string>(search->second); } return node; } generated_node_t generate_node_from_file(stdfs::path const& filepath) { auto node = node_from_file(filepath); return generate_node(node); } constexpr size_t indent_amt = 4; // constexpr char indent_char = ' '; // constexpr char indent_tree_marker = ':'; constexpr char const* indent_cstr = ": "; std::string indenation_string(size_t indent_level) { if(indent_level == 0) return ""; // std::string indent_str(indent_level * indent_amt, indent_char); // indent_str[indent_str.size()-indent_amt] = indent_tree_marker; std::string indent_str; for(size_t i = 0; i < indent_level; ++i) indent_str.insert(indent_str.end(), indent_cstr, indent_cstr + 4); return indent_str; } /// TODO: factor out similarities with below? string to_string(pregen_node_t const& node, size_t const depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << "\n"; if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.values) s << indent << value << "\n"; for(auto const& vnode : node.value_nodes) s << to_string(vnode, depth, level + 1); for(auto const& user_vals : node.user_data) s << indent << user_vals.first << ": " << user_vals.second << "\n"; return s.str(); } string to_string(generated_node_t const& node, size_t depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << "\n"; if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.generated_values) s << indent << value << "\n"; for(auto const& vn : node.value_nodes) s << to_string(vn, depth, level + 1); return s.str(); } void print_node(pregen_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } void print_node(generated_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } }<commit_msg>to_string() for pregen nodes will now include the weight as part of the name (only if the weight is not equal to 1)<commit_after>#include "plant_generator.h" #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <numeric> #include <random> #include <type_traits> #include <asdf_multiplat/main/asdf_defs.h> #include "from_json.h" using namespace std; namespace plantgen { //std::vector<std::string> roll_multi_value(multi_value_t const& m); std::mt19937 mt_rand( std::chrono::high_resolution_clock::now().time_since_epoch().count() ); int random_int(uint32_t min, uint32_t max) { std::uniform_int_distribution<int> dis(min,max); return dis(mt_rand); } int random_int(uint32_t max) { return random_int(0, max); } template <typename L> uint32_t total_weight(L const& list) { uint32_t total = 0; for(auto const& v : list) total += v.weight; return total; } std::vector<std::string> roll_multi_value(multi_value_t const& m) { if(m.num_to_pick >= m.values.size()) return m.values; std::vector<size_t> inds(m.values.size()); std::iota(inds.begin(), inds.end(), size_t(0)); //0, 1, 2, 3, ..., size-1 std::shuffle(inds.begin(), inds.end(), std::mt19937{std::random_device{}()}); std::vector<std::string> output; output.reserve(m.num_to_pick); for(size_t i = 0; i < m.num_to_pick; ++i) output.push_back(m.values[inds[i]]); return output; } std::vector<std::string> roll_range_value(range_value_t const& r) { std::vector<std::string> output; output.reserve(r.size()); uint32_t counter = 0; for(size_t i = 0; i < r.size() - 1; ++i) { int roll = 0; if(counter < 100) roll = random_int(100 - counter); counter += roll; output.push_back(std::to_string(roll) + "% " + r[i]); } //push remaining output.push_back(std::to_string(100 - counter) + "% " + r.back()); return output; } /// Runtime version (compile-time visitor pattern doesn't compile in msvc) std::vector<std::string> roll_value(weighted_value_t const& variant_val) { std::vector<std::string> output; if(auto* s = std::get_if<std::string>(&variant_val)) { output.push_back(*s); } else if(auto* r = std::get_if<range_value_t>(&variant_val)) { auto rolled_range = roll_range_value(*r); output.insert(output.end(), rolled_range.begin(), rolled_range.end()); } else if(auto* m = std::get_if<multi_value_t>(&variant_val)) { auto rolled_multi = roll_multi_value(*m); output.insert(output.end(), rolled_multi.begin(), rolled_multi.end()); } else { EXPLODE("unexpected variant sub-type"); } return output; } generated_node_t roll_values(value_list_t const& values, std::vector<pregen_node_t> const& value_nodes) { if(values.empty() && value_nodes.empty()) return generated_node_t(); uint32_t total = total_weight(values) + total_weight(value_nodes); int roll = random_int(total); for(size_t i = 0; i < values.size(); ++i) { if(roll <= values[i].weight) { generated_node_t node; node.generated_values = std::move(roll_value(values[i])); return node; } roll -= values[i].weight; } //if no value from the value list has been hit yet, continue onward into value_nodes for(size_t i = 0; i < value_nodes.size(); ++i) { if(roll <= value_nodes[i].weight) { generated_node_t node(value_nodes[i].name); //node.add_child(generate_node(value_nodes[i])); auto gend_node = generate_node(value_nodes[i]); node.add_value_node(std::move(gend_node)); return node; } roll -= value_nodes[i].weight; } EXPLODE("Random roll was too large, ran out of values and value_nodes"); return generated_node_t("ERROR"); } generated_node_t roll_values(pregen_node_t const& node) { return roll_values(node.values, node.value_nodes); } pregen_node_t node_from_file(stdfs::path const& filepath) { using namespace std; auto ext = filepath.extension(); if(ext == ".json") { return node_from_json(filepath); } else if(ext == ".yaml" || ext == ".yml") { cout << "TODO: yaml support"; return pregen_node_t(); } //TODO: exception? if(stdfs::is_directory(filepath)) cout << filepath.string() << " is a directory, not a file"; else cout << "Filetype " << ext << " not recognized"; return pregen_node_t(); } generated_node_t generate_node(pregen_node_t const& pre_node) { generated_node_t node; node.name = pre_node.name; for(auto const& child : pre_node.children) { node.add_child(generate_node(child)); } if(pre_node.values.size() > 0 || pre_node.value_nodes.size() > 0) { generated_node_t rolled = roll_values(pre_node); node.merge_with(rolled); } auto search = pre_node.user_data.find("PrintString"); if(search != pre_node.user_data.end()) { node.print_string = std::get<std::string>(search->second); } return node; } generated_node_t generate_node_from_file(stdfs::path const& filepath) { auto node = node_from_file(filepath); return generate_node(node); } constexpr size_t indent_amt = 4; // constexpr char indent_char = ' '; // constexpr char indent_tree_marker = ':'; constexpr char const* indent_cstr = ": "; std::string indenation_string(size_t indent_level) { if(indent_level == 0) return ""; // std::string indent_str(indent_level * indent_amt, indent_char); // indent_str[indent_str.size()-indent_amt] = indent_tree_marker; std::string indent_str; for(size_t i = 0; i < indent_level; ++i) indent_str.insert(indent_str.end(), indent_cstr, indent_cstr + 4); return indent_str; } /// TODO: factor out similarities with below? string to_string(pregen_node_t const& node, size_t const depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); string weight_str = node.weight == 1 ? "" : " (Weight " + std::to_string(node.weight) + ")"; s << indent << node.name_string() << weight_str << "\n"; if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.values) s << indent << value << "\n"; for(auto const& vnode : node.value_nodes) s << to_string(vnode, depth, level + 1); for(auto const& user_vals : node.user_data) s << indent << user_vals.first << ": " << user_vals.second << "\n"; return s.str(); } string to_string(generated_node_t const& node, size_t depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << "\n"; if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.generated_values) s << indent << value << "\n"; for(auto const& vn : node.value_nodes) s << to_string(vn, depth, level + 1); return s.str(); } void print_node(pregen_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } void print_node(generated_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } }<|endoftext|>
<commit_before>#include "plant_generator.h" #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <numeric> #include <random> #include <type_traits> #include <asdf_multiplat/main/asdf_defs.h> #include "from_json.h" using namespace std; namespace plantgen { //std::vector<std::string> roll_multi_value(multi_value_t const& m); std::mt19937 mt_rand( std::chrono::high_resolution_clock::now().time_since_epoch().count() ); int32_t random_int(uint32_t min, uint32_t max) { std::uniform_int_distribution<int> dis(min,max); return dis(mt_rand); } int32_t random_int(uint32_t max) { return random_int(0, max); } template <typename L> uint32_t total_weight(L const& list) { uint32_t total = 0; for(auto const& v : list) total += v.weight; return total; } std::vector<std::string> roll_multi_value(multi_value_t const& m) { if(m.num_to_pick >= m.values.size()) return m.values; std::vector<size_t> inds(m.values.size()); std::iota(inds.begin(), inds.end(), size_t(0)); //0, 1, 2, 3, ..., size-1 std::shuffle(inds.begin(), inds.end(), std::mt19937{std::random_device{}()}); std::vector<std::string> output; output.reserve(m.num_to_pick); for(size_t i = 0; i < m.num_to_pick; ++i) output.push_back(m.values[inds[i]]); return output; } std::vector<std::string> roll_range_value(range_value_t const& r) { std::vector<std::string> output; output.reserve(r.size()); uint32_t counter = 0; for(size_t i = 0; i < r.size() - 1; ++i) { int roll = 0; if(counter < 100) roll = random_int(100 - counter); counter += roll; output.push_back(std::to_string(roll) + "% " + r[i]); } //push remaining output.push_back(std::to_string(100 - counter) + "% " + r.back()); return output; } /// Runtime version (compile-time visitor pattern doesn't compile in msvc) std::vector<std::string> roll_value(variant_value_t const& variant_val) { std::vector<std::string> output; if(auto* s = std::get_if<std::string>(&variant_val)) { output.push_back(*s); } else if(auto* r = std::get_if<range_value_t>(&variant_val)) { auto rolled_range = roll_range_value(*r); output.insert(output.end(), rolled_range.begin(), rolled_range.end()); } else if(auto* m = std::get_if<multi_value_t>(&variant_val)) { auto rolled_multi = roll_multi_value(*m); output.insert(output.end(), rolled_multi.begin(), rolled_multi.end()); } else { EXPLODE("unexpected variant sub-type"); } return output; } generated_node_t roll_values(pregen_node_t const& node) { generated_node_t output_node; auto const& value_nodes = node.value_nodes; output_node.num_rollable_values = value_nodes.size(); WARN_IF(value_nodes.empty(), "Rolling values for an empty list"); if(value_nodes.empty()) return generated_node_t(); int roll = random_int(total_weight(value_nodes)); //if no value from the value list has been hit yet, continue onward into value_nodes for(size_t i = 0; i < value_nodes.size(); ++i) { if(roll <= value_nodes[i].weight) { output_node.name = value_nodes[i].name; output_node.value_index = i; if(value_nodes[i].value.index() > 0) { output_node.generated_values = roll_value(value_nodes[i].value); } else { auto gend_node = generate_node(value_nodes[i]); output_node.add_value_node(std::move(gend_node)); } return output_node; } roll -= value_nodes[i].weight; } EXPLODE("Random roll was too large, ran out of values and value_nodes"); return generated_node_t("ERROR"); } pregen_node_t node_from_file(stdfs::path const& filepath) { using namespace std; auto ext = filepath.extension(); if(ext == ".json") { return node_from_json(filepath); } else if(ext == ".yaml" || ext == ".yml") { cout << "TODO: yaml support"; return pregen_node_t(); } //TODO: exception? if(stdfs::is_directory(filepath)) cout << filepath.string() << " is a directory, not a file"; else cout << "Filetype " << ext << " not recognized"; return pregen_node_t(); } generated_node_t generate_node(pregen_node_t const& pre_node) { generated_node_t node; node.name = pre_node.name; node.weight = pre_node.weight; for(auto const& child : pre_node.children) { node.add_child(generate_node(child)); } if(pre_node.value_nodes.size() > 0) { generated_node_t rolled = roll_values(pre_node); node.merge_with(rolled); ASSERT(node.weight == pre_node.weight, "Node merge affected weight unexpectedly"); } // auto search = pre_node.user_data.find("PrintString"); if(auto const* nd = find(pre_node.user_data, "PrintString"); nd) { node.print_string = std::get<std::string>(nd->value); } return node; } generated_node_t generate_node_from_file(stdfs::path const& filepath) { auto node = node_from_file(filepath); return generate_node(node); } constexpr size_t indent_amt = 4; // constexpr char indent_char = ' '; // constexpr char indent_tree_marker = ':'; constexpr char const* indent_cstr = ": "; std::string indenation_string(size_t indent_level) { if(indent_level == 0) return ""; // std::string indent_str(indent_level * indent_amt, indent_char); // indent_str[indent_str.size()-indent_amt] = indent_tree_marker; std::string indent_str; for(size_t i = 0; i < indent_level; ++i) indent_str.insert(indent_str.end(), indent_cstr, indent_cstr + 4); return indent_str; } /// TODO: factor out similarities with below? /// TODO: use regular string concat rather than stringstream /// I'm not using any of the features of SS that make it worth using string to_string(user_data_node_t const& node, size_t const depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << ": "; if(is_leaf(node)) { s << node.value; return s.str(); } if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << "\n" << to_string(child, depth, level + 1); return s.str(); } string to_string(pregen_node_t const& node, size_t const depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); string weight_str = node.weight == 1 ? "" : " (Weight " + std::to_string(node.weight) + ")"; if(is_leaf(node)) { s << indent << node.value << weight_str << "\n"; } else { s << indent << node.name_string() << weight_str << "\n"; } if(level + 1 > depth) return s.str(); if(node.has_user_data()) s << to_string(node.user_data, depth, level + 1) << "\n"; for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& vnode : node.value_nodes) s << to_string(vnode, depth, level + 1); return s.str(); } string to_string(generated_node_t const& node, size_t depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << "\n"; if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.generated_values) s << indent << value << "\n"; for(auto const& vn : node.value_nodes) s << to_string(vn, depth, level + 1); return s.str(); } void print_node(pregen_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } void print_node(generated_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } }<commit_msg>fixed to_string(pregen_node_t const& node)<commit_after>#include "plant_generator.h" #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <numeric> #include <random> #include <type_traits> #include <asdf_multiplat/main/asdf_defs.h> #include "from_json.h" using namespace std; namespace plantgen { //std::vector<std::string> roll_multi_value(multi_value_t const& m); std::mt19937 mt_rand( std::chrono::high_resolution_clock::now().time_since_epoch().count() ); int32_t random_int(uint32_t min, uint32_t max) { std::uniform_int_distribution<int> dis(min,max); return dis(mt_rand); } int32_t random_int(uint32_t max) { return random_int(0, max); } template <typename L> uint32_t total_weight(L const& list) { uint32_t total = 0; for(auto const& v : list) total += v.weight; return total; } std::vector<std::string> roll_multi_value(multi_value_t const& m) { if(m.num_to_pick >= m.values.size()) return m.values; std::vector<size_t> inds(m.values.size()); std::iota(inds.begin(), inds.end(), size_t(0)); //0, 1, 2, 3, ..., size-1 std::shuffle(inds.begin(), inds.end(), std::mt19937{std::random_device{}()}); std::vector<std::string> output; output.reserve(m.num_to_pick); for(size_t i = 0; i < m.num_to_pick; ++i) output.push_back(m.values[inds[i]]); return output; } std::vector<std::string> roll_range_value(range_value_t const& r) { std::vector<std::string> output; output.reserve(r.size()); uint32_t counter = 0; for(size_t i = 0; i < r.size() - 1; ++i) { int roll = 0; if(counter < 100) roll = random_int(100 - counter); counter += roll; output.push_back(std::to_string(roll) + "% " + r[i]); } //push remaining output.push_back(std::to_string(100 - counter) + "% " + r.back()); return output; } /// Runtime version (compile-time visitor pattern doesn't compile in msvc) std::vector<std::string> roll_value(variant_value_t const& variant_val) { std::vector<std::string> output; if(auto* s = std::get_if<std::string>(&variant_val)) { output.push_back(*s); } else if(auto* r = std::get_if<range_value_t>(&variant_val)) { auto rolled_range = roll_range_value(*r); output.insert(output.end(), rolled_range.begin(), rolled_range.end()); } else if(auto* m = std::get_if<multi_value_t>(&variant_val)) { auto rolled_multi = roll_multi_value(*m); output.insert(output.end(), rolled_multi.begin(), rolled_multi.end()); } else { EXPLODE("unexpected variant sub-type"); } return output; } generated_node_t roll_values(pregen_node_t const& node) { generated_node_t output_node; auto const& value_nodes = node.value_nodes; output_node.num_rollable_values = value_nodes.size(); WARN_IF(value_nodes.empty(), "Rolling values for an empty list"); if(value_nodes.empty()) return generated_node_t(); int roll = random_int(total_weight(value_nodes)); //if no value from the value list has been hit yet, continue onward into value_nodes for(size_t i = 0; i < value_nodes.size(); ++i) { if(roll <= value_nodes[i].weight) { output_node.name = value_nodes[i].name; output_node.value_index = i; if(value_nodes[i].value.index() > 0) { output_node.generated_values = roll_value(value_nodes[i].value); } else { auto gend_node = generate_node(value_nodes[i]); output_node.add_value_node(std::move(gend_node)); } return output_node; } roll -= value_nodes[i].weight; } EXPLODE("Random roll was too large, ran out of values and value_nodes"); return generated_node_t("ERROR"); } pregen_node_t node_from_file(stdfs::path const& filepath) { using namespace std; auto ext = filepath.extension(); if(ext == ".json") { return node_from_json(filepath); } else if(ext == ".yaml" || ext == ".yml") { cout << "TODO: yaml support"; return pregen_node_t(); } //TODO: exception? if(stdfs::is_directory(filepath)) cout << filepath.string() << " is a directory, not a file"; else cout << "Filetype " << ext << " not recognized"; return pregen_node_t(); } generated_node_t generate_node(pregen_node_t const& pre_node) { generated_node_t node; node.name = pre_node.name; node.weight = pre_node.weight; for(auto const& child : pre_node.children) { node.add_child(generate_node(child)); } if(pre_node.value_nodes.size() > 0) { generated_node_t rolled = roll_values(pre_node); node.merge_with(rolled); ASSERT(node.weight == pre_node.weight, "Node merge affected weight unexpectedly"); } // auto search = pre_node.user_data.find("PrintString"); if(auto const* nd = find(pre_node.user_data, "PrintString"); nd) { node.print_string = std::get<std::string>(nd->value); } return node; } generated_node_t generate_node_from_file(stdfs::path const& filepath) { auto node = node_from_file(filepath); return generate_node(node); } constexpr size_t indent_amt = 4; // constexpr char indent_char = ' '; // constexpr char indent_tree_marker = ':'; constexpr char const* indent_cstr = ": "; std::string indenation_string(size_t indent_level) { if(indent_level == 0) return ""; // std::string indent_str(indent_level * indent_amt, indent_char); // indent_str[indent_str.size()-indent_amt] = indent_tree_marker; std::string indent_str; for(size_t i = 0; i < indent_level; ++i) indent_str.insert(indent_str.end(), indent_cstr, indent_cstr + 4); return indent_str; } /// TODO: factor out similarities with below? /// TODO: use regular string concat rather than stringstream /// I'm not using any of the features of SS that make it worth using string to_string(user_data_node_t const& node, size_t const depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << ": "; if(is_leaf(node)) { s << node.value; return s.str(); } if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << "\n" << to_string(child, depth, level + 1); return s.str(); } string to_string(pregen_node_t const& node, size_t const depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent; if(node.name.size() > 0) s << node.name_string(); if(node.value.index() > 0) s << node.value; if(node.weight != 1) s << " (Weight " + std::to_string(node.weight) + ")"; s << "\n"; if(level + 1 > depth) return s.str(); if(node.has_user_data()) s << to_string(node.user_data, depth, level + 1) << "\n"; for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& vnode : node.value_nodes) s << to_string(vnode, depth, level + 1); return s.str(); } string to_string(generated_node_t const& node, size_t depth, size_t level) { if(level > depth) return ""; stringstream s; auto indent = indenation_string(level); s << indent << node.name_string() << "\n"; if(level + 1 > depth) return s.str(); for(auto const& child : node.children) s << to_string(child, depth, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.generated_values) s << indent << value << "\n"; for(auto const& vn : node.value_nodes) s << to_string(vn, depth, level + 1); return s.str(); } void print_node(pregen_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } void print_node(generated_node_t const& node, size_t depth, size_t level) { cout << to_string(node, depth, level); } }<|endoftext|>
<commit_before>#include "model.h" #include "modelwidget.h" #include "figurepainter.h" #include "recognition.h" #include "layouting.h" #include <QPainter> #include <QMouseEvent> #include <QInputDialog> #include <QDebug> #include <QTimer> #include <iostream> Ui::ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent), mouseAction(MouseAction::None), _gridStep(0) { setFocusPolicy(Qt::FocusPolicy::StrongFocus); } void drawTrack(QPainter &painter, Scaler &scaler, const Track &track) { for (size_t i = 0; i + 1 < track.size(); i++) { painter.drawLine(scaler(track[i]), scaler(track[i + 1])); } } int Ui::ModelWidget::gridStep() { return _gridStep; } void Ui::ModelWidget::setGridStep(int newGridStep) { if (newGridStep < 0) { throw std::runtime_error("Grid step should be >= 0"); } _gridStep = newGridStep; repaint(); } double Ui::ModelWidget::scaleFactor() { return scaler.scaleFactor; } void Ui::ModelWidget::setScaleFactor(double newScaleFactor) { if (!(newScaleFactor >= 0.01)) { // >= instead of < for NaNs throw std::runtime_error("Scale factor should be >= 0.01"); } scaler.scaleFactor = newScaleFactor; emit scaleFactorChanged(); repaint(); } void Ui::ModelWidget::setModel(Model model) { commitedModel = std::move(model); previousModels.clear(); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); } Model &Ui::ModelWidget::getModel() { return commitedModel; } bool Ui::ModelWidget::canUndo() { return !previousModels.empty(); } void Ui::ModelWidget::undo() { if (!canUndo()) { throw std::runtime_error("Cannot undo"); } redoModels.push_front(std::move(commitedModel)); commitedModel = std::move(previousModels.back()); previousModels.pop_back(); if (!canUndo()) { emit canUndoChanged(); } emit canRedoChanged(); repaint(); } bool Ui::ModelWidget::canRedo() { return !redoModels.empty(); } void Ui::ModelWidget::redo() { if (!canRedo()) { throw std::runtime_error("Cannot redo"); } previousModels.push_back(std::move(commitedModel)); commitedModel = std::move(redoModels.front()); redoModels.pop_front(); if (!canRedo()) { canRedoChanged(); } canUndoChanged(); repaint(); } double roundDownToMultiple(double x, double multiple) { return floor(x / multiple) * multiple; } void Ui::ModelWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(QRect(QPoint(), size()), Qt::white); QFont font; font.setPointSizeF(10 * scaler.scaleFactor); painter.setFont(font); QPen pen(Qt::black); pen.setWidthF(scaler.scaleFactor); painter.setPen(pen); FigurePainter fpainter(painter, scaler); if (gridStep() > 0) { int step = gridStep(); // Calculating visible area Point p1 = scaler(QPointF(0, 0)); Point p2 = scaler(QPointF(width(), height())); if (p1.x > p2.x) { std::swap(p1.x, p2.x); } if (p1.y > p2.y) { std::swap(p1.y, p2.y); } // Finding starting point for the grid p1.x = roundDownToMultiple(p1.x, step); p1.y = roundDownToMultiple(p1.y, step); // Drawing QPen pen(QColor(192, 192, 192, 255)); pen.setStyle(Qt::DashLine); painter.setPen(pen); for (int x = p1.x; x <= p2.x; x += step) { painter.drawLine(scaler(Point(x, p1.y)), scaler(Point(x, p2.y))); } for (int y = p1.y; y <= p2.y; y += step) { painter.drawLine(scaler(Point(p1.x, y)), scaler(Point(p2.x, y))); } } Model copiedModel; Model &modelToDraw = lastTrack.empty() ? commitedModel : (copiedModel = commitedModel); PFigure modified = recognize(lastTrack, modelToDraw); for (PFigure fig : modelToDraw) { if (fig == modified) { pen.setColor(Qt::magenta); } else if (fig == modelToDraw.selectedFigure) { pen.setColor(Qt::blue); } else { pen.setColor(Qt::black); } painter.setPen(pen); fig->visit(fpainter); } pen.setColor(QColor(255, 0, 0, 16)); pen.setWidth(3 * scaler.scaleFactor); painter.setPen(pen); drawTrack(painter, scaler, lastTrack); for (const Track &track : visibleTracks) { drawTrack(painter, scaler, track); } } void Ui::ModelWidget::mousePressEvent(QMouseEvent *event) { lastTrack = Track(); if (event->modifiers().testFlag(Qt::ShiftModifier)) { mouseAction = MouseAction::ViewpointMove; viewpointMoveStart = event->pos(); viewpointMoveOldScaler = scaler; setCursor(Qt::ClosedHandCursor); } else { mouseAction = MouseAction::TrackActive; lastTrack.points.push_back(scaler(event->pos())); } repaint(); } void Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) { if (mouseAction == MouseAction::ViewpointMove) { scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); repaint(); } if (mouseAction == MouseAction::TrackActive) { lastTrack.points.push_back(scaler(event->pos())); repaint(); } } void Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) { if (mouseAction == MouseAction::None) { return; } if (mouseAction == MouseAction::ViewpointMove) { mouseAction = MouseAction::None; setCursor(Qt::ArrowCursor); scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); repaint(); return; } assert(mouseAction == MouseAction::TrackActive); mouseAction = MouseAction::None; lastTrack.points.push_back(scaler(event->pos())); Model previousModel = commitedModel; PFigure modifiedFigure = recognize(lastTrack, commitedModel); if (_gridStep > 0 && modifiedFigure) { GridAlignLayouter layouter(_gridStep); layouter.updateLayout(commitedModel, modifiedFigure); commitedModel.recalculate(); } visibleTracks.push_back(lastTrack); auto iterator = --visibleTracks.end(); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, [this, iterator, timer]() { visibleTracks.erase(iterator); delete timer; repaint(); }); timer->setInterval(1500); timer->setSingleShot(true); timer->start(); lastTrack = Track(); if (modifiedFigure) { previousModels.push_back(previousModel); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); } repaint(); } void Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape && mouseAction == MouseAction::TrackActive) { lastTrack = Track(); mouseAction = MouseAction::None; repaint(); } if (event->key() == Qt::Key_Delete) { if (commitedModel.selectedFigure) { previousModels.push_back(commitedModel); redoModels.clear(); for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) { if (*it == commitedModel.selectedFigure) { commitedModel.removeFigure(it); break; } } emit canUndoChanged(); emit canRedoChanged(); repaint(); } } } void Ui::ModelWidget::mouseDoubleClickEvent(QMouseEvent *event) { figures::PBoundedFigure figure = std::dynamic_pointer_cast<figures::BoundedFigure>(commitedModel.selectedFigure); if (figure && figure->getApproximateDistanceToBorder(scaler(event->pos())) < 10) { bool ok; QString newLabel = QInputDialog::getMultiLineText(this, "Figure label", "Specify new figure label", QString::fromStdString(figure->label()), &ok); if (ok) { previousModels.push_back(commitedModel); redoModels.clear(); figure->setLabel(newLabel.toStdString()); emit canUndoChanged(); emit canRedoChanged(); repaint(); } } } <commit_msg>modelwidget: accepting/ignoring of mouse/keyboard events was added (fixes #52)<commit_after>#include "model.h" #include "modelwidget.h" #include "figurepainter.h" #include "recognition.h" #include "layouting.h" #include <QPainter> #include <QMouseEvent> #include <QInputDialog> #include <QDebug> #include <QTimer> #include <iostream> Ui::ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent), mouseAction(MouseAction::None), _gridStep(0) { setFocusPolicy(Qt::FocusPolicy::StrongFocus); } void drawTrack(QPainter &painter, Scaler &scaler, const Track &track) { for (size_t i = 0; i + 1 < track.size(); i++) { painter.drawLine(scaler(track[i]), scaler(track[i + 1])); } } int Ui::ModelWidget::gridStep() { return _gridStep; } void Ui::ModelWidget::setGridStep(int newGridStep) { if (newGridStep < 0) { throw std::runtime_error("Grid step should be >= 0"); } _gridStep = newGridStep; repaint(); } double Ui::ModelWidget::scaleFactor() { return scaler.scaleFactor; } void Ui::ModelWidget::setScaleFactor(double newScaleFactor) { if (!(newScaleFactor >= 0.01)) { // >= instead of < for NaNs throw std::runtime_error("Scale factor should be >= 0.01"); } scaler.scaleFactor = newScaleFactor; emit scaleFactorChanged(); repaint(); } void Ui::ModelWidget::setModel(Model model) { commitedModel = std::move(model); previousModels.clear(); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); } Model &Ui::ModelWidget::getModel() { return commitedModel; } bool Ui::ModelWidget::canUndo() { return !previousModels.empty(); } void Ui::ModelWidget::undo() { if (!canUndo()) { throw std::runtime_error("Cannot undo"); } redoModels.push_front(std::move(commitedModel)); commitedModel = std::move(previousModels.back()); previousModels.pop_back(); if (!canUndo()) { emit canUndoChanged(); } emit canRedoChanged(); repaint(); } bool Ui::ModelWidget::canRedo() { return !redoModels.empty(); } void Ui::ModelWidget::redo() { if (!canRedo()) { throw std::runtime_error("Cannot redo"); } previousModels.push_back(std::move(commitedModel)); commitedModel = std::move(redoModels.front()); redoModels.pop_front(); if (!canRedo()) { canRedoChanged(); } canUndoChanged(); repaint(); } double roundDownToMultiple(double x, double multiple) { return floor(x / multiple) * multiple; } void Ui::ModelWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(QRect(QPoint(), size()), Qt::white); QFont font; font.setPointSizeF(10 * scaler.scaleFactor); painter.setFont(font); QPen pen(Qt::black); pen.setWidthF(scaler.scaleFactor); painter.setPen(pen); FigurePainter fpainter(painter, scaler); if (gridStep() > 0) { int step = gridStep(); // Calculating visible area Point p1 = scaler(QPointF(0, 0)); Point p2 = scaler(QPointF(width(), height())); if (p1.x > p2.x) { std::swap(p1.x, p2.x); } if (p1.y > p2.y) { std::swap(p1.y, p2.y); } // Finding starting point for the grid p1.x = roundDownToMultiple(p1.x, step); p1.y = roundDownToMultiple(p1.y, step); // Drawing QPen pen(QColor(192, 192, 192, 255)); pen.setStyle(Qt::DashLine); painter.setPen(pen); for (int x = p1.x; x <= p2.x; x += step) { painter.drawLine(scaler(Point(x, p1.y)), scaler(Point(x, p2.y))); } for (int y = p1.y; y <= p2.y; y += step) { painter.drawLine(scaler(Point(p1.x, y)), scaler(Point(p2.x, y))); } } Model copiedModel; Model &modelToDraw = lastTrack.empty() ? commitedModel : (copiedModel = commitedModel); PFigure modified = recognize(lastTrack, modelToDraw); for (PFigure fig : modelToDraw) { if (fig == modified) { pen.setColor(Qt::magenta); } else if (fig == modelToDraw.selectedFigure) { pen.setColor(Qt::blue); } else { pen.setColor(Qt::black); } painter.setPen(pen); fig->visit(fpainter); } pen.setColor(QColor(255, 0, 0, 16)); pen.setWidth(3 * scaler.scaleFactor); painter.setPen(pen); drawTrack(painter, scaler, lastTrack); for (const Track &track : visibleTracks) { drawTrack(painter, scaler, track); } } void Ui::ModelWidget::mousePressEvent(QMouseEvent *event) { lastTrack = Track(); if (event->modifiers().testFlag(Qt::ShiftModifier)) { mouseAction = MouseAction::ViewpointMove; viewpointMoveStart = event->pos(); viewpointMoveOldScaler = scaler; setCursor(Qt::ClosedHandCursor); } else { mouseAction = MouseAction::TrackActive; lastTrack.points.push_back(scaler(event->pos())); } repaint(); } void Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) { if (mouseAction == MouseAction::ViewpointMove) { scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); repaint(); } else if (mouseAction == MouseAction::TrackActive) { lastTrack.points.push_back(scaler(event->pos())); repaint(); } else { event->ignore(); } } void Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) { if (mouseAction == MouseAction::None) { event->ignore(); return; } if (mouseAction == MouseAction::ViewpointMove) { mouseAction = MouseAction::None; setCursor(Qt::ArrowCursor); scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); repaint(); return; } assert(mouseAction == MouseAction::TrackActive); mouseAction = MouseAction::None; lastTrack.points.push_back(scaler(event->pos())); Model previousModel = commitedModel; PFigure modifiedFigure = recognize(lastTrack, commitedModel); if (_gridStep > 0 && modifiedFigure) { GridAlignLayouter layouter(_gridStep); layouter.updateLayout(commitedModel, modifiedFigure); commitedModel.recalculate(); } visibleTracks.push_back(lastTrack); auto iterator = --visibleTracks.end(); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, [this, iterator, timer]() { visibleTracks.erase(iterator); delete timer; repaint(); }); timer->setInterval(1500); timer->setSingleShot(true); timer->start(); lastTrack = Track(); if (modifiedFigure) { previousModels.push_back(previousModel); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); } repaint(); } void Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) { event->ignore(); if (event->key() == Qt::Key_Escape && mouseAction == MouseAction::TrackActive) { event->accept(); lastTrack = Track(); mouseAction = MouseAction::None; repaint(); } if (event->key() == Qt::Key_Delete) { if (commitedModel.selectedFigure) { event->accept(); previousModels.push_back(commitedModel); redoModels.clear(); for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) { if (*it == commitedModel.selectedFigure) { commitedModel.removeFigure(it); break; } } emit canUndoChanged(); emit canRedoChanged(); repaint(); } } } void Ui::ModelWidget::mouseDoubleClickEvent(QMouseEvent *event) { event->ignore(); figures::PBoundedFigure figure = std::dynamic_pointer_cast<figures::BoundedFigure>(commitedModel.selectedFigure); if (figure && figure->getApproximateDistanceToBorder(scaler(event->pos())) < 10) { event->accept(); bool ok; QString newLabel = QInputDialog::getMultiLineText(this, "Figure label", "Specify new figure label", QString::fromStdString(figure->label()), &ok); if (ok) { previousModels.push_back(commitedModel); redoModels.clear(); figure->setLabel(newLabel.toStdString()); emit canUndoChanged(); emit canRedoChanged(); repaint(); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleSwitch.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkInteractorStyleSwitch.h" #include "vtkObjectFactory.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkInteractorStyleJoystickActor.h" #include "vtkInteractorStyleJoystickCamera.h" #include "vtkInteractorStyleTrackballActor.h" #include "vtkInteractorStyleTrackballCamera.h" vtkCxxRevisionMacro(vtkInteractorStyleSwitch, "1.11"); vtkStandardNewMacro(vtkInteractorStyleSwitch); //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::vtkInteractorStyleSwitch() { this->JoystickActor = vtkInteractorStyleJoystickActor::New(); this->JoystickCamera = vtkInteractorStyleJoystickCamera::New(); this->TrackballActor = vtkInteractorStyleTrackballActor::New(); this->TrackballCamera = vtkInteractorStyleTrackballCamera::New(); this->JoystickOrTrackball = VTKIS_JOYSTICK; this->CameraOrActor = VTKIS_CAMERA; this->CurrentStyle = 0; } //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::~vtkInteractorStyleSwitch() { this->JoystickActor->Delete(); this->JoystickActor = NULL; this->JoystickCamera->Delete(); this->JoystickCamera = NULL; this->TrackballActor->Delete(); this->TrackballActor = NULL; this->TrackballCamera->Delete(); this->TrackballCamera = NULL; } void vtkInteractorStyleSwitch::SetAutoAdjustCameraClippingRange( int value ) { if ( value == this->AutoAdjustCameraClippingRange ) { return; } if ( value < 0 || value > 1 ) { vtkErrorMacro("Value must be between 0 and 1 for" << " SetAutoAdjustCameraClippingRange"); return; } this->AutoAdjustCameraClippingRange = value; this->JoystickActor->SetAutoAdjustCameraClippingRange( value ); this->JoystickCamera->SetAutoAdjustCameraClippingRange( value ); this->TrackballActor->SetAutoAdjustCameraClippingRange( value ); this->TrackballCamera->SetAutoAdjustCameraClippingRange( value ); this->Modified(); } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnChar(int ctrl, int shift, char keycode, int repeatcount) { switch (keycode) { case 'j': case 'J': this->JoystickOrTrackball = VTKIS_JOYSTICK; break; case 't': case 'T': this->JoystickOrTrackball = VTKIS_TRACKBALL; break; case 'c': case 'C': this->CameraOrActor = VTKIS_CAMERA; break; case 'a': case 'A': this->CameraOrActor = VTKIS_ACTOR; break; default: vtkInteractorStyle::OnChar(ctrl, shift, keycode, repeatcount); break; } // Set the CurrentStyle pointer to the picked style this->SetCurrentStyle(); } // this will do nothing if the CurrentStyle matchs // JoystickOrTrackball and CameraOrActor void vtkInteractorStyleSwitch::SetCurrentStyle() { // if the currentstyle does not match JoystickOrTrackball // and CameraOrActor ivars, then call SetInteractor(0) // on the Currentstyle to remove all of the observers. // Then set the Currentstyle and call SetInteractor with // this->Interactor so the callbacks are set for the // currentstyle. if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { if(this->CurrentStyle != this->JoystickCamera) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->JoystickCamera; this->CurrentStyle->SetInteractor(this->Interactor); } } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { if(this->CurrentStyle != this->JoystickActor) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->JoystickActor; this->CurrentStyle->SetInteractor(this->Interactor); } } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { if(this->CurrentStyle != this->TrackballCamera) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->TrackballCamera; this->CurrentStyle->SetInteractor(this->Interactor); } } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { if(this->CurrentStyle != this->TrackballActor) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->TrackballActor; this->CurrentStyle->SetInteractor(this->Interactor); } } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::SetInteractor(vtkRenderWindowInteractor *iren) { if(iren == this->Interactor) { return; } // if we already have an Interactor then stop observing it if(this->Interactor) { this->Interactor->RemoveObserver(this->EventCallbackCommand); } this->Interactor = iren; // add observers for each of the events handled in ProcessEvents if(iren) { iren->AddObserver(vtkCommand::CharEvent, this->EventCallbackCommand); iren->AddObserver(vtkCommand::DeleteEvent, this->EventCallbackCommand); } this->SetCurrentStyle(); } void vtkInteractorStyleSwitch::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "CurrentStyle " << this->CurrentStyle << "\n"; } <commit_msg>FIX: fix duplicate OnChar handler (OnCharEvent was processed twice)<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleSwitch.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkInteractorStyleSwitch.h" #include "vtkObjectFactory.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkInteractorStyleJoystickActor.h" #include "vtkInteractorStyleJoystickCamera.h" #include "vtkInteractorStyleTrackballActor.h" #include "vtkInteractorStyleTrackballCamera.h" vtkCxxRevisionMacro(vtkInteractorStyleSwitch, "1.12"); vtkStandardNewMacro(vtkInteractorStyleSwitch); //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::vtkInteractorStyleSwitch() { this->JoystickActor = vtkInteractorStyleJoystickActor::New(); this->JoystickCamera = vtkInteractorStyleJoystickCamera::New(); this->TrackballActor = vtkInteractorStyleTrackballActor::New(); this->TrackballCamera = vtkInteractorStyleTrackballCamera::New(); this->JoystickOrTrackball = VTKIS_JOYSTICK; this->CameraOrActor = VTKIS_CAMERA; this->CurrentStyle = 0; } //---------------------------------------------------------------------------- vtkInteractorStyleSwitch::~vtkInteractorStyleSwitch() { this->JoystickActor->Delete(); this->JoystickActor = NULL; this->JoystickCamera->Delete(); this->JoystickCamera = NULL; this->TrackballActor->Delete(); this->TrackballActor = NULL; this->TrackballCamera->Delete(); this->TrackballCamera = NULL; } void vtkInteractorStyleSwitch::SetAutoAdjustCameraClippingRange( int value ) { if ( value == this->AutoAdjustCameraClippingRange ) { return; } if ( value < 0 || value > 1 ) { vtkErrorMacro("Value must be between 0 and 1 for" << " SetAutoAdjustCameraClippingRange"); return; } this->AutoAdjustCameraClippingRange = value; this->JoystickActor->SetAutoAdjustCameraClippingRange( value ); this->JoystickCamera->SetAutoAdjustCameraClippingRange( value ); this->TrackballActor->SetAutoAdjustCameraClippingRange( value ); this->TrackballCamera->SetAutoAdjustCameraClippingRange( value ); this->Modified(); } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::OnChar(int ctrl, int shift, char keycode, int repeatcount) { switch (keycode) { case 'j': case 'J': this->JoystickOrTrackball = VTKIS_JOYSTICK; break; case 't': case 'T': this->JoystickOrTrackball = VTKIS_TRACKBALL; break; case 'c': case 'C': this->CameraOrActor = VTKIS_CAMERA; break; case 'a': case 'A': this->CameraOrActor = VTKIS_ACTOR; break; } // Set the CurrentStyle pointer to the picked style this->SetCurrentStyle(); } // this will do nothing if the CurrentStyle matchs // JoystickOrTrackball and CameraOrActor void vtkInteractorStyleSwitch::SetCurrentStyle() { // if the currentstyle does not match JoystickOrTrackball // and CameraOrActor ivars, then call SetInteractor(0) // on the Currentstyle to remove all of the observers. // Then set the Currentstyle and call SetInteractor with // this->Interactor so the callbacks are set for the // currentstyle. if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_CAMERA) { if(this->CurrentStyle != this->JoystickCamera) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->JoystickCamera; this->CurrentStyle->SetInteractor(this->Interactor); } } else if (this->JoystickOrTrackball == VTKIS_JOYSTICK && this->CameraOrActor == VTKIS_ACTOR) { if(this->CurrentStyle != this->JoystickActor) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->JoystickActor; this->CurrentStyle->SetInteractor(this->Interactor); } } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_CAMERA) { if(this->CurrentStyle != this->TrackballCamera) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->TrackballCamera; this->CurrentStyle->SetInteractor(this->Interactor); } } else if (this->JoystickOrTrackball == VTKIS_TRACKBALL && this->CameraOrActor == VTKIS_ACTOR) { if(this->CurrentStyle != this->TrackballActor) { if(this->CurrentStyle) { this->CurrentStyle->SetInteractor(0); } this->CurrentStyle = this->TrackballActor; this->CurrentStyle->SetInteractor(this->Interactor); } } } //---------------------------------------------------------------------------- void vtkInteractorStyleSwitch::SetInteractor(vtkRenderWindowInteractor *iren) { if(iren == this->Interactor) { return; } // if we already have an Interactor then stop observing it if(this->Interactor) { this->Interactor->RemoveObserver(this->EventCallbackCommand); } this->Interactor = iren; // add observers for each of the events handled in ProcessEvents if(iren) { iren->AddObserver(vtkCommand::CharEvent, this->EventCallbackCommand); iren->AddObserver(vtkCommand::DeleteEvent, this->EventCallbackCommand); } this->SetCurrentStyle(); } void vtkInteractorStyleSwitch::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "CurrentStyle " << this->CurrentStyle << "\n"; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPainterPolyDataMapper.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPainterPolyDataMapper.h" #include "vtkChooserPainter.h" #include "vtkClipPlanesPainter.h" #include "vtkCoincidentTopologyResolutionPainter.h" #include "vtkCommand.h" #include "vtkDefaultPainter.h" #include "vtkDisplayListPainter.h" #include "vtkGarbageCollector.h" #include "vtkGenericVertexAttributeMapping.h" #include "vtkInformation.h" #include "vtkInformationObjectBaseKey.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPlaneCollection.h" #include "vtkPolyData.h" #include "vtkPrimitivePainter.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkScalarsToColorsPainter.h" vtkStandardNewMacro(vtkPainterPolyDataMapper); vtkCxxRevisionMacro(vtkPainterPolyDataMapper, "1.10") //----------------------------------------------------------------------------- class vtkPainterPolyDataMapperObserver : public vtkCommand { public: static vtkPainterPolyDataMapperObserver* New() { return new vtkPainterPolyDataMapperObserver; } virtual void Execute(vtkObject* caller, unsigned long event, void*) { vtkPainter* p = vtkPainter::SafeDownCast(caller); if (this->Target && p && event == vtkCommand::ProgressEvent) { this->Target->UpdateProgress(p->GetProgress()); } } vtkPainterPolyDataMapperObserver() { this->Target = 0; } vtkPainterPolyDataMapper* Target; }; //----------------------------------------------------------------------------- vtkPainterPolyDataMapper::vtkPainterPolyDataMapper() { this->Painter = 0; this->PainterInformation = vtkInformation::New(); this->Observer = vtkPainterPolyDataMapperObserver::New(); this->Observer->Target = this; vtkDefaultPainter* dp = vtkDefaultPainter::New(); this->SetPainter(dp); dp->Delete(); vtkChooserPainter* cp = vtkChooserPainter::New(); this->Painter->SetDelegatePainter(cp); cp->Delete(); } //----------------------------------------------------------------------------- vtkPainterPolyDataMapper::~vtkPainterPolyDataMapper() { this->SetPainter(NULL); this->Observer->Target = NULL; this->Observer->Delete(); this->PainterInformation->Delete(); } //--------------------------------------------------------------------------- void vtkPainterPolyDataMapper::MapDataArrayToVertexAttribute( const char* vertexAttributeName, const char* dataArrayName, int field, int componentno) { vtkGenericVertexAttributeMapping* mappings = 0; if( this->PainterInformation->Has( vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) ) { mappings = vtkGenericVertexAttributeMapping::SafeDownCast( this->PainterInformation->Get( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); } if (mappings==NULL) { mappings = vtkGenericVertexAttributeMapping::New(); this->PainterInformation->Set( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE(), mappings); mappings->Delete(); } mappings->AddMapping( vertexAttributeName, dataArrayName, field, componentno); } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::RemoveAllVertexAttributeMappings() { vtkGenericVertexAttributeMapping* mappings = 0; if( this->PainterInformation->Has( vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) ) { mappings = vtkGenericVertexAttributeMapping::SafeDownCast( this->PainterInformation->Get( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); mappings->RemoveAllMappings(); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::RemoveVertexAttributeMapping( const char* vertexAttributeName) { vtkGenericVertexAttributeMapping* mappings = 0; if( this->PainterInformation->Has( vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) ) { mappings = vtkGenericVertexAttributeMapping::SafeDownCast( this->PainterInformation->Get( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); mappings->RemoveMapping(vertexAttributeName); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::SetPainter(vtkPolyDataPainter* p) { if (this->Painter) { this->Painter->RemoveObservers(vtkCommand::ProgressEvent, this->Observer); } vtkSetObjectBodyMacro(Painter, vtkPolyDataPainter, p); if (this->Painter) { this->Painter->AddObserver(vtkCommand::ProgressEvent, this->Observer); this->Painter->SetInformation(this->PainterInformation); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Painter, "Painter"); } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::ReleaseGraphicsResources(vtkWindow *w) { if (this->Painter) { this->Painter->ReleaseGraphicsResources(w); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::UpdatePainterInformation() { vtkInformation* info = this->PainterInformation; info->Set(vtkPainter::STATIC_DATA(), this->Static); info->Set(vtkScalarsToColorsPainter::USE_LOOKUP_TABLE_SCALAR_RANGE(), this->GetUseLookupTableScalarRange()); info->Set(vtkScalarsToColorsPainter::SCALAR_RANGE(), this->GetScalarRange(), 2); info->Set(vtkScalarsToColorsPainter::SCALAR_MODE(), this->GetScalarMode()); info->Set(vtkScalarsToColorsPainter::COLOR_MODE(), this->GetColorMode()); info->Set(vtkScalarsToColorsPainter::INTERPOLATE_SCALARS_BEFORE_MAPPING(), this->GetInterpolateScalarsBeforeMapping()); info->Set(vtkScalarsToColorsPainter::LOOKUP_TABLE(), this->LookupTable); info->Set(vtkScalarsToColorsPainter::SCALAR_VISIBILITY(), this->GetScalarVisibility()); info->Set(vtkScalarsToColorsPainter::ARRAY_ACCESS_MODE(), this->ArrayAccessMode); info->Set(vtkScalarsToColorsPainter::ARRAY_ID(), this->ArrayId); info->Set(vtkScalarsToColorsPainter::ARRAY_NAME(), this->ArrayName); info->Set(vtkScalarsToColorsPainter::ARRAY_COMPONENT(), this->ArrayComponent); info->Set(vtkScalarsToColorsPainter::SCALAR_MATERIAL_MODE(), this->GetScalarMaterialMode()); info->Set(vtkClipPlanesPainter::CLIPPING_PLANES(), this->ClippingPlanes); info->Set(vtkCoincidentTopologyResolutionPainter::RESOLVE_COINCIDENT_TOPOLOGY(), this->GetResolveCoincidentTopology()); info->Set(vtkCoincidentTopologyResolutionPainter::Z_SHIFT(), this->GetResolveCoincidentTopologyZShift()); double p[2]; this->GetResolveCoincidentTopologyPolygonOffsetParameters(p[0], p[1]); info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_PARAMETERS(), p, 2); info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_FACES(), this->GetResolveCoincidentTopologyPolygonOffsetFaces()); int immr = (this->ImmediateModeRendering || vtkMapper::GetGlobalImmediateModeRendering()); info->Set(vtkDisplayListPainter::IMMEDIATE_MODE_RENDERING(), immr); } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::RenderPiece(vtkRenderer* ren, vtkActor* act) { vtkPolyData *input= this->GetInput(); // // make sure that we've been properly initialized // if (ren->GetRenderWindow()->CheckAbortStatus()) { return; } if ( input == NULL ) { vtkErrorMacro(<< "No input!"); return; } else { this->InvokeEvent(vtkCommand::StartEvent,NULL); if (!this->Static) { input->Update(); } this->InvokeEvent(vtkCommand::EndEvent,NULL); vtkIdType numPts = input->GetNumberOfPoints(); if (numPts == 0) { vtkDebugMacro(<< "No points!"); return; } } // make sure our window is current ren->GetRenderWindow()->MakeCurrent(); this->TimeToDraw = 0.0; if (this->Painter) { // Update Painter information if obsolete. if (this->PainterUpdateTime < this->MTime) { this->UpdatePainterInformation(); this->PainterUpdateTime.Modified(); } // Pass polydata if changed. if (this->Painter->GetPolyData() != input) { this->Painter->SetPolyData(input); } this->Painter->Render(ren, act, 0xff); this->TimeToDraw = this->Painter->GetTimeToDraw(); } // If the timer is not accurate enough, set it to a small // time so that it is not zero if ( this->TimeToDraw == 0.0 ) { this->TimeToDraw = 0.0001; } this->UpdateProgress(1.0); } //------------------------------------------------------------------------- void vtkPainterPolyDataMapper::GetBounds(double bounds[6]) { this->GetBounds(); memcpy(bounds,this->Bounds,6*sizeof(double)); } //------------------------------------------------------------------------- double* vtkPainterPolyDataMapper::GetBounds() { static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0}; // do we have an input if ( ! this->GetNumberOfInputConnections(0) ) { return bounds; } else { if (!this->Static) { // For proper clipping, this would be this->Piece, // this->NumberOfPieces. // But that removes all benefites of streaming. // Update everything as a hack for paraview streaming. // This should not affect anything else, because no one uses this. // It should also render just the same. // Just remove this lie if we no longer need streaming in paraview :) //this->GetInput()->SetUpdateExtent(0, 1, 0); //this->GetInput()->Update(); // first get the bounds from the input this->Update(); this->GetInput()->GetBounds(this->Bounds); // if the mapper has a painter, update the bounds in the painter vtkPainter *painter = this->GetPainter(); if( painter ) { painter->UpdateBounds(this->Bounds); } } // if the bounds indicate NAN and subpieces are being used then // return NULL if (!vtkMath::AreBoundsInitialized(this->Bounds) && this->NumberOfSubPieces > 1) { return NULL; } return this->Bounds; } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Painter: " ; if (this->Painter) { os << endl; this->Painter->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "(none)" << endl; } } <commit_msg>BUG: The clipping planes' MTime was not getting included in the decision to update painter information.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPainterPolyDataMapper.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPainterPolyDataMapper.h" #include "vtkChooserPainter.h" #include "vtkClipPlanesPainter.h" #include "vtkCoincidentTopologyResolutionPainter.h" #include "vtkCommand.h" #include "vtkDefaultPainter.h" #include "vtkDisplayListPainter.h" #include "vtkGarbageCollector.h" #include "vtkGenericVertexAttributeMapping.h" #include "vtkInformation.h" #include "vtkInformationObjectBaseKey.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPlaneCollection.h" #include "vtkPolyData.h" #include "vtkPrimitivePainter.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkScalarsToColorsPainter.h" vtkStandardNewMacro(vtkPainterPolyDataMapper); vtkCxxRevisionMacro(vtkPainterPolyDataMapper, "1.11") //----------------------------------------------------------------------------- class vtkPainterPolyDataMapperObserver : public vtkCommand { public: static vtkPainterPolyDataMapperObserver* New() { return new vtkPainterPolyDataMapperObserver; } virtual void Execute(vtkObject* caller, unsigned long event, void*) { vtkPainter* p = vtkPainter::SafeDownCast(caller); if (this->Target && p && event == vtkCommand::ProgressEvent) { this->Target->UpdateProgress(p->GetProgress()); } } vtkPainterPolyDataMapperObserver() { this->Target = 0; } vtkPainterPolyDataMapper* Target; }; //----------------------------------------------------------------------------- vtkPainterPolyDataMapper::vtkPainterPolyDataMapper() { this->Painter = 0; this->PainterInformation = vtkInformation::New(); this->Observer = vtkPainterPolyDataMapperObserver::New(); this->Observer->Target = this; vtkDefaultPainter* dp = vtkDefaultPainter::New(); this->SetPainter(dp); dp->Delete(); vtkChooserPainter* cp = vtkChooserPainter::New(); this->Painter->SetDelegatePainter(cp); cp->Delete(); } //----------------------------------------------------------------------------- vtkPainterPolyDataMapper::~vtkPainterPolyDataMapper() { this->SetPainter(NULL); this->Observer->Target = NULL; this->Observer->Delete(); this->PainterInformation->Delete(); } //--------------------------------------------------------------------------- void vtkPainterPolyDataMapper::MapDataArrayToVertexAttribute( const char* vertexAttributeName, const char* dataArrayName, int field, int componentno) { vtkGenericVertexAttributeMapping* mappings = 0; if( this->PainterInformation->Has( vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) ) { mappings = vtkGenericVertexAttributeMapping::SafeDownCast( this->PainterInformation->Get( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); } if (mappings==NULL) { mappings = vtkGenericVertexAttributeMapping::New(); this->PainterInformation->Set( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE(), mappings); mappings->Delete(); } mappings->AddMapping( vertexAttributeName, dataArrayName, field, componentno); } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::RemoveAllVertexAttributeMappings() { vtkGenericVertexAttributeMapping* mappings = 0; if( this->PainterInformation->Has( vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) ) { mappings = vtkGenericVertexAttributeMapping::SafeDownCast( this->PainterInformation->Get( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); mappings->RemoveAllMappings(); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::RemoveVertexAttributeMapping( const char* vertexAttributeName) { vtkGenericVertexAttributeMapping* mappings = 0; if( this->PainterInformation->Has( vtkPrimitivePainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE()) ) { mappings = vtkGenericVertexAttributeMapping::SafeDownCast( this->PainterInformation->Get( vtkPolyDataPainter::DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); mappings->RemoveMapping(vertexAttributeName); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::SetPainter(vtkPolyDataPainter* p) { if (this->Painter) { this->Painter->RemoveObservers(vtkCommand::ProgressEvent, this->Observer); } vtkSetObjectBodyMacro(Painter, vtkPolyDataPainter, p); if (this->Painter) { this->Painter->AddObserver(vtkCommand::ProgressEvent, this->Observer); this->Painter->SetInformation(this->PainterInformation); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Painter, "Painter"); } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::ReleaseGraphicsResources(vtkWindow *w) { if (this->Painter) { this->Painter->ReleaseGraphicsResources(w); } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::UpdatePainterInformation() { vtkInformation* info = this->PainterInformation; info->Set(vtkPainter::STATIC_DATA(), this->Static); info->Set(vtkScalarsToColorsPainter::USE_LOOKUP_TABLE_SCALAR_RANGE(), this->GetUseLookupTableScalarRange()); info->Set(vtkScalarsToColorsPainter::SCALAR_RANGE(), this->GetScalarRange(), 2); info->Set(vtkScalarsToColorsPainter::SCALAR_MODE(), this->GetScalarMode()); info->Set(vtkScalarsToColorsPainter::COLOR_MODE(), this->GetColorMode()); info->Set(vtkScalarsToColorsPainter::INTERPOLATE_SCALARS_BEFORE_MAPPING(), this->GetInterpolateScalarsBeforeMapping()); info->Set(vtkScalarsToColorsPainter::LOOKUP_TABLE(), this->LookupTable); info->Set(vtkScalarsToColorsPainter::SCALAR_VISIBILITY(), this->GetScalarVisibility()); info->Set(vtkScalarsToColorsPainter::ARRAY_ACCESS_MODE(), this->ArrayAccessMode); info->Set(vtkScalarsToColorsPainter::ARRAY_ID(), this->ArrayId); info->Set(vtkScalarsToColorsPainter::ARRAY_NAME(), this->ArrayName); info->Set(vtkScalarsToColorsPainter::ARRAY_COMPONENT(), this->ArrayComponent); info->Set(vtkScalarsToColorsPainter::SCALAR_MATERIAL_MODE(), this->GetScalarMaterialMode()); info->Set(vtkClipPlanesPainter::CLIPPING_PLANES(), this->ClippingPlanes); info->Set(vtkCoincidentTopologyResolutionPainter::RESOLVE_COINCIDENT_TOPOLOGY(), this->GetResolveCoincidentTopology()); info->Set(vtkCoincidentTopologyResolutionPainter::Z_SHIFT(), this->GetResolveCoincidentTopologyZShift()); double p[2]; this->GetResolveCoincidentTopologyPolygonOffsetParameters(p[0], p[1]); info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_PARAMETERS(), p, 2); info->Set(vtkCoincidentTopologyResolutionPainter::POLYGON_OFFSET_FACES(), this->GetResolveCoincidentTopologyPolygonOffsetFaces()); int immr = (this->ImmediateModeRendering || vtkMapper::GetGlobalImmediateModeRendering()); info->Set(vtkDisplayListPainter::IMMEDIATE_MODE_RENDERING(), immr); } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::RenderPiece(vtkRenderer* ren, vtkActor* act) { vtkPolyData *input= this->GetInput(); // // make sure that we've been properly initialized // if (ren->GetRenderWindow()->CheckAbortStatus()) { return; } if ( input == NULL ) { vtkErrorMacro(<< "No input!"); return; } else { this->InvokeEvent(vtkCommand::StartEvent,NULL); if (!this->Static) { input->Update(); } this->InvokeEvent(vtkCommand::EndEvent,NULL); vtkIdType numPts = input->GetNumberOfPoints(); if (numPts == 0) { vtkDebugMacro(<< "No points!"); return; } } // make sure our window is current ren->GetRenderWindow()->MakeCurrent(); this->TimeToDraw = 0.0; if (this->Painter) { // Update Painter information if obsolete. if (this->PainterUpdateTime < this->GetMTime()) { this->UpdatePainterInformation(); this->PainterUpdateTime.Modified(); } // Pass polydata if changed. if (this->Painter->GetPolyData() != input) { this->Painter->SetPolyData(input); } this->Painter->Render(ren, act, 0xff); this->TimeToDraw = this->Painter->GetTimeToDraw(); } // If the timer is not accurate enough, set it to a small // time so that it is not zero if ( this->TimeToDraw == 0.0 ) { this->TimeToDraw = 0.0001; } this->UpdateProgress(1.0); } //------------------------------------------------------------------------- void vtkPainterPolyDataMapper::GetBounds(double bounds[6]) { this->GetBounds(); memcpy(bounds,this->Bounds,6*sizeof(double)); } //------------------------------------------------------------------------- double* vtkPainterPolyDataMapper::GetBounds() { static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0}; // do we have an input if ( ! this->GetNumberOfInputConnections(0) ) { return bounds; } else { if (!this->Static) { // For proper clipping, this would be this->Piece, // this->NumberOfPieces. // But that removes all benefites of streaming. // Update everything as a hack for paraview streaming. // This should not affect anything else, because no one uses this. // It should also render just the same. // Just remove this lie if we no longer need streaming in paraview :) //this->GetInput()->SetUpdateExtent(0, 1, 0); //this->GetInput()->Update(); // first get the bounds from the input this->Update(); this->GetInput()->GetBounds(this->Bounds); // if the mapper has a painter, update the bounds in the painter vtkPainter *painter = this->GetPainter(); if( painter ) { painter->UpdateBounds(this->Bounds); } } // if the bounds indicate NAN and subpieces are being used then // return NULL if (!vtkMath::AreBoundsInitialized(this->Bounds) && this->NumberOfSubPieces > 1) { return NULL; } return this->Bounds; } } //----------------------------------------------------------------------------- void vtkPainterPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Painter: " ; if (this->Painter) { os << endl; this->Painter->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "(none)" << endl; } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdint.h> #include <spice/controller_prot.h> #ifdef WIN32 #include <windows.h> #define PIPE_NAME TEXT("\\\\.\\pipe\\SpiceController-%lu") static HANDLE pipe = INVALID_HANDLE_VALUE; #else #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> typedef void *LPVOID; typedef const void *LPCVOID; typedef unsigned long DWORD; typedef char TCHAR; #define PIPE_NAME "/tmp/SpiceController-%lu.uds" static int sock = -1; #endif #define PIPE_NAME_MAX_LEN 256 void write_to_pipe(LPCVOID data, DWORD size) { #ifdef WIN32 DWORD written; if (!WriteFile(pipe, data, size, &written, NULL) || written != size) { printf("Write to pipe failed %u\n", GetLastError()); } #else if (send(sock, data, size, 0) != size) { printf("send failed, (%d) %s\n", errno, strerror(errno)); } #endif } void send_init() { ControllerInit msg = {{CONTROLLER_MAGIC, CONTROLLER_VERSION, sizeof(msg)}, 0, CONTROLLER_FLAG_EXCLUSIVE}; write_to_pipe((LPCVOID)&msg, sizeof(msg)); } void send_msg(uint32_t id) { ControllerMsg msg = {id, sizeof(msg)}; write_to_pipe((LPCVOID)&msg, sizeof(msg)); } void send_value(uint32_t id, uint32_t value) { ControllerValue msg = {{id, sizeof(msg)}, value}; write_to_pipe((LPCVOID)&msg, sizeof(msg)); } void send_data(uint32_t id, uint8_t* data, size_t data_size) { size_t size = sizeof(ControllerData) + data_size; ControllerData* msg = (ControllerData*)malloc(size); msg->base.id = id; msg->base.size = (uint32_t)size; memcpy(msg->data, data, data_size); write_to_pipe((LPCVOID)msg, (DWORD)size); free(msg); } DWORD read_from_pipe(LPVOID data, DWORD size) { DWORD read; #ifdef WIN32 if (!ReadFile(pipe, data, size, &read, NULL)) { printf("Read from pipe failed %u\n", GetLastError()); } #else if (read = recv(sock, data, size, 0) && (read == -1 || read == 0)) { printf("recv failed, (%d) %s\n", errno, strerror(errno)); } #endif return read; } #define HOST "localhost" #define PORT 5931 #define SPORT 0 #define PWD "" #define SECURE_CHANNELS "main,inputs,playback" #define DISABLED_CHANNELS "playback,record" #define TITLE "Hello from controller" #define HOTKEYS "toggle-fullscreen=shift+f1,release-cursor=shift+f2" #define MENU "0\r4864\rS&end Ctrl+Alt+Del\tCtrl+Alt+End\r0\r\n" \ "0\r5120\r&Toggle full screen\tShift+F11\r0\r\n" \ "0\r1\r&Special keys\r4\r\n" \ "1\r5376\r&Send Shift+F11\r0\r\n" \ "1\r5632\r&Send Shift+F12\r0\r\n" \ "1\r5888\r&Send Ctrl+Alt+End\r0\r\n" \ "0\r1\r-\r1\r\n" \ "0\r2\rChange CD\r4\r\n" \ "2\r3\rNo CDs\r0\r\n" \ "2\r4\r[Eject]\r0\r\n" \ "0\r5\r-\r1\r\n" \ "0\r6\rPlay\r0\r\n" \ "0\r7\rSuspend\r0\r\n" \ "0\r8\rStop\r0\r\n" #define TLS_CIPHERS "NONE" #define CA_FILE "NONE" #define HOST_SUBJECT "NONE" int main(int argc, char *argv[]) { int spicec_pid = (argc > 1 ? atoi(argv[1]) : 0); char* host = (argc > 2 ? argv[2] : (char*)HOST); int port = (argc > 3 ? atoi(argv[3]) : PORT); TCHAR pipe_name[PIPE_NAME_MAX_LEN]; ControllerValue msg; DWORD read; #ifdef WIN32 _snwprintf_s(pipe_name, PIPE_NAME_MAX_LEN, PIPE_NAME_MAX_LEN, PIPE_NAME, spicec_pid); printf("Creating Spice controller connection %S\n", pipe_name); pipe = CreateFile(pipe_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (pipe == INVALID_HANDLE_VALUE) { printf("Could not open pipe %u\n", GetLastError()); return -1; } #else snprintf(pipe_name, PIPE_NAME_MAX_LEN, PIPE_NAME, spicec_pid); printf("Creating a controller connection %s\n", pipe_name); struct sockaddr_un remote; if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { printf("Could not open socket, (%d) %s\n", errno, strerror(errno)); return -1; } remote.sun_family = AF_UNIX; strcpy(remote.sun_path, pipe_name); if (connect(sock, (struct sockaddr *)&remote, strlen(remote.sun_path) + sizeof(remote.sun_family)) == -1) { printf("Socket connect failed, (%d) %s\n", errno, strerror(errno)); close(sock); return -1; } #endif send_init(); printf("Setting Spice parameters\n"); send_data(CONTROLLER_HOST, (uint8_t*)host, strlen(host) + 1); send_value(CONTROLLER_PORT, port); send_value(CONTROLLER_SPORT, SPORT); send_data(CONTROLLER_PASSWORD, (uint8_t*)PWD, sizeof(PWD)); //send_data(CONTROLLER_SECURE_CHANNELS, (uint8_t*)SECURE_CHANNELS, sizeof(SECURE_CHANNELS)); send_data(CONTROLLER_DISABLE_CHANNELS, (uint8_t*)DISABLED_CHANNELS, sizeof(DISABLED_CHANNELS)); //send_data(CONTROLLER_TLS_CIPHERS, (uint8_t*)TLS_CIPHERS, sizeof(TLS_CIPHERS)); //send_data(CONTROLLER_CA_FILE, (uint8_t*)CA_FILE, sizeof(CA_FILE)); //send_data(CONTROLLER_HOST_SUBJECT, (uint8_t*)HOST_SUBJECT, sizeof(HOST_SUBJECT)); send_data(CONTROLLER_SET_TITLE, (uint8_t*)TITLE, sizeof(TITLE)); send_data(CONTROLLER_HOTKEYS, (uint8_t*)HOTKEYS, sizeof(HOTKEYS)); send_data(CONTROLLER_CREATE_MENU, (uint8_t*)MENU, sizeof(MENU)); printf("Smartcard...\n"); getchar(); send_value(CONTROLLER_ENABLE_SMARTCARD, 1); send_value(CONTROLLER_FULL_SCREEN, /*CONTROLLER_SET_FULL_SCREEN |*/ CONTROLLER_AUTO_DISPLAY_RES); printf("Show...\n"); getchar(); send_msg(CONTROLLER_SHOW); printf("Connect...\n"); getchar(); send_msg(CONTROLLER_CONNECT); printf("Hide...\n"); getchar(); send_msg(CONTROLLER_HIDE); printf("Show...\n"); getchar(); send_msg(CONTROLLER_SHOW); //send_msg(CONTROLLER_DELETE_MENU); //send_msg(CONTROLLER_HIDE); while ((read = read_from_pipe(&msg, sizeof(msg))) == sizeof(msg)) { printf("Received id %u, size %u, value %u\n", msg.base.id, msg.base.size, msg.value); } printf("Press <Enter> to close connection\n"); getchar(); #ifdef WIN32 CloseHandle(pipe); #else close(sock); #endif return 0; } <commit_msg>client controller_test: reorder parameters since pid isn't needed for linux client test<commit_after>#include <stdio.h> #include <stdint.h> #include <spice/controller_prot.h> #ifdef WIN32 #include <windows.h> #define PIPE_NAME TEXT("\\\\.\\pipe\\SpiceController-%lu") static HANDLE pipe = INVALID_HANDLE_VALUE; #else #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> typedef void *LPVOID; typedef const void *LPCVOID; typedef unsigned long DWORD; typedef char TCHAR; #define PIPE_NAME "/tmp/SpiceController-%lu.uds" static int sock = -1; #endif #define PIPE_NAME_MAX_LEN 256 void write_to_pipe(LPCVOID data, DWORD size) { #ifdef WIN32 DWORD written; if (!WriteFile(pipe, data, size, &written, NULL) || written != size) { printf("Write to pipe failed %u\n", GetLastError()); } #else if (send(sock, data, size, 0) != size) { printf("send failed, (%d) %s\n", errno, strerror(errno)); } #endif } void send_init() { ControllerInit msg = {{CONTROLLER_MAGIC, CONTROLLER_VERSION, sizeof(msg)}, 0, CONTROLLER_FLAG_EXCLUSIVE}; write_to_pipe((LPCVOID)&msg, sizeof(msg)); } void send_msg(uint32_t id) { ControllerMsg msg = {id, sizeof(msg)}; write_to_pipe((LPCVOID)&msg, sizeof(msg)); } void send_value(uint32_t id, uint32_t value) { ControllerValue msg = {{id, sizeof(msg)}, value}; write_to_pipe((LPCVOID)&msg, sizeof(msg)); } void send_data(uint32_t id, uint8_t* data, size_t data_size) { size_t size = sizeof(ControllerData) + data_size; ControllerData* msg = (ControllerData*)malloc(size); msg->base.id = id; msg->base.size = (uint32_t)size; memcpy(msg->data, data, data_size); write_to_pipe((LPCVOID)msg, (DWORD)size); free(msg); } DWORD read_from_pipe(LPVOID data, DWORD size) { DWORD read; #ifdef WIN32 if (!ReadFile(pipe, data, size, &read, NULL)) { printf("Read from pipe failed %u\n", GetLastError()); } #else if (read = recv(sock, data, size, 0) && (read == -1 || read == 0)) { printf("recv failed, (%d) %s\n", errno, strerror(errno)); } #endif return read; } #define HOST "localhost" #define PORT 5931 #define SPORT 0 #define PWD "" #define SECURE_CHANNELS "main,inputs,playback" #define DISABLED_CHANNELS "playback,record" #define TITLE "Hello from controller" #define HOTKEYS "toggle-fullscreen=shift+f1,release-cursor=shift+f2" #define MENU "0\r4864\rS&end Ctrl+Alt+Del\tCtrl+Alt+End\r0\r\n" \ "0\r5120\r&Toggle full screen\tShift+F11\r0\r\n" \ "0\r1\r&Special keys\r4\r\n" \ "1\r5376\r&Send Shift+F11\r0\r\n" \ "1\r5632\r&Send Shift+F12\r0\r\n" \ "1\r5888\r&Send Ctrl+Alt+End\r0\r\n" \ "0\r1\r-\r1\r\n" \ "0\r2\rChange CD\r4\r\n" \ "2\r3\rNo CDs\r0\r\n" \ "2\r4\r[Eject]\r0\r\n" \ "0\r5\r-\r1\r\n" \ "0\r6\rPlay\r0\r\n" \ "0\r7\rSuspend\r0\r\n" \ "0\r8\rStop\r0\r\n" #define TLS_CIPHERS "NONE" #define CA_FILE "NONE" #define HOST_SUBJECT "NONE" int main(int argc, char *argv[]) { int spicec_pid = (argc > 3 ? atoi(argv[3]) : 0); char* host = (argc > 1 ? argv[1] : (char*)HOST); int port = (argc > 2 ? atoi(argv[2]) : PORT); TCHAR pipe_name[PIPE_NAME_MAX_LEN]; ControllerValue msg; DWORD read; #ifdef WIN32 _snwprintf_s(pipe_name, PIPE_NAME_MAX_LEN, PIPE_NAME_MAX_LEN, PIPE_NAME, spicec_pid); printf("Creating Spice controller connection %S\n", pipe_name); pipe = CreateFile(pipe_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (pipe == INVALID_HANDLE_VALUE) { printf("Could not open pipe %u\n", GetLastError()); return -1; } #else snprintf(pipe_name, PIPE_NAME_MAX_LEN, PIPE_NAME, spicec_pid); printf("Creating a controller connection %s\n", pipe_name); struct sockaddr_un remote; if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { printf("Could not open socket, (%d) %s\n", errno, strerror(errno)); return -1; } remote.sun_family = AF_UNIX; strcpy(remote.sun_path, pipe_name); if (connect(sock, (struct sockaddr *)&remote, strlen(remote.sun_path) + sizeof(remote.sun_family)) == -1) { printf("Socket connect failed, (%d) %s\n", errno, strerror(errno)); close(sock); return -1; } #endif send_init(); printf("Setting Spice parameters\n"); send_data(CONTROLLER_HOST, (uint8_t*)host, strlen(host) + 1); send_value(CONTROLLER_PORT, port); send_value(CONTROLLER_SPORT, SPORT); send_data(CONTROLLER_PASSWORD, (uint8_t*)PWD, sizeof(PWD)); //send_data(CONTROLLER_SECURE_CHANNELS, (uint8_t*)SECURE_CHANNELS, sizeof(SECURE_CHANNELS)); send_data(CONTROLLER_DISABLE_CHANNELS, (uint8_t*)DISABLED_CHANNELS, sizeof(DISABLED_CHANNELS)); //send_data(CONTROLLER_TLS_CIPHERS, (uint8_t*)TLS_CIPHERS, sizeof(TLS_CIPHERS)); //send_data(CONTROLLER_CA_FILE, (uint8_t*)CA_FILE, sizeof(CA_FILE)); //send_data(CONTROLLER_HOST_SUBJECT, (uint8_t*)HOST_SUBJECT, sizeof(HOST_SUBJECT)); send_data(CONTROLLER_SET_TITLE, (uint8_t*)TITLE, sizeof(TITLE)); send_data(CONTROLLER_HOTKEYS, (uint8_t*)HOTKEYS, sizeof(HOTKEYS)); send_data(CONTROLLER_CREATE_MENU, (uint8_t*)MENU, sizeof(MENU)); printf("Smartcard...\n"); getchar(); send_value(CONTROLLER_ENABLE_SMARTCARD, 1); send_value(CONTROLLER_FULL_SCREEN, /*CONTROLLER_SET_FULL_SCREEN |*/ CONTROLLER_AUTO_DISPLAY_RES); printf("Show...\n"); getchar(); send_msg(CONTROLLER_SHOW); printf("Connect...\n"); getchar(); send_msg(CONTROLLER_CONNECT); printf("Hide...\n"); getchar(); send_msg(CONTROLLER_HIDE); printf("Show...\n"); getchar(); send_msg(CONTROLLER_SHOW); //send_msg(CONTROLLER_DELETE_MENU); //send_msg(CONTROLLER_HIDE); while ((read = read_from_pipe(&msg, sizeof(msg))) == sizeof(msg)) { printf("Received id %u, size %u, value %u\n", msg.base.id, msg.base.size, msg.value); } printf("Press <Enter> to close connection\n"); getchar(); #ifdef WIN32 CloseHandle(pipe); #else close(sock); #endif return 0; } <|endoftext|>
<commit_before>/* * Copyright 2018 Sergey Khabarov, sergeykhbr@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "api_core.h" #include "bp.h" namespace debugger { BranchPredictor::BranchPredictor(sc_module_name name_, bool async_reset) : sc_module(name_), i_clk("i_clk"), i_nrst("i_nrst"), i_resp_mem_valid("i_resp_mem_valid"), i_resp_mem_addr("i_resp_mem_addr"), i_resp_mem_data("i_resp_mem_data"), i_e_jmp("i_e_jmp"), i_e_pc("i_e_pc"), i_e_npc("i_e_npc"), i_ra("i_ra"), o_f_valid("o_f_valid"), o_f_pc("o_f_pc"), i_f_requested_pc("i_f_requested_pc"), i_f_fetched_pc("i_f_fetched_pc"), i_f_fetching_pc("i_f_fetching_pc"), i_d_pc("i_d_pc") { char tstr[256]; for (int i = 0; i < 2; i++) { RISCV_sprintf(tstr, sizeof(tstr), "predec%d", i); predec[i] = new BpPreDecoder(tstr); predec[i]->i_c_valid(wb_pd[i].c_valid); predec[i]->i_addr(wb_pd[i].addr); predec[i]->i_data(wb_pd[i].data); predec[i]->i_ra(i_ra); predec[i]->o_jmp(wb_pd[i].jmp); predec[i]->o_pc(wb_pd[i].pc); predec[i]->o_npc(wb_pd[i].npc); } btb = new BpBTB("btb", async_reset); btb->i_clk(i_clk); btb->i_nrst(i_nrst); btb->i_flush_pipeline(i_flush_pipeline); btb->i_e(w_btb_e); btb->i_we(w_btb_we); btb->i_we_pc(wb_btb_we_pc); btb->i_we_npc(wb_btb_we_npc); btb->i_bp_pc(wb_start_pc); btb->o_bp_npc(wb_npc); btb->o_bp_exec(wb_bp_exec); SC_METHOD(comb); sensitive << i_nrst; sensitive << i_resp_mem_valid; sensitive << i_resp_mem_addr; sensitive << i_resp_mem_data; sensitive << i_e_jmp; sensitive << i_e_pc; sensitive << i_e_npc; sensitive << i_ra; sensitive << i_f_requested_pc; sensitive << i_f_fetching_pc; sensitive << i_f_fetched_pc; sensitive << i_d_pc; sensitive << wb_npc; sensitive << wb_bp_exec; for (int i = 0; i < 2; i++) { sensitive << wb_pd[i].jmp; sensitive << wb_pd[i].pc; sensitive << wb_pd[i].npc; } }; BranchPredictor::~BranchPredictor() { for (int i = 0; i < 2; i++) { delete predec[i]; } delete btb; } void BranchPredictor::generateVCD(sc_trace_file *i_vcd, sc_trace_file *o_vcd) { btb->generateVCD(i_vcd, o_vcd); for (int i = 0; i < 2; i++) { predec[i]->generateVCD(i_vcd, o_vcd); } if (o_vcd) { sc_trace(o_vcd, i_flush_pipeline, i_flush_pipeline.name()); sc_trace(o_vcd, i_resp_mem_valid, i_resp_mem_valid.name()); sc_trace(o_vcd, i_resp_mem_addr, i_resp_mem_addr.name()); sc_trace(o_vcd, i_resp_mem_data, i_resp_mem_data.name()); sc_trace(o_vcd, i_e_jmp, i_e_jmp.name()); sc_trace(o_vcd, i_e_pc, i_e_pc.name()); sc_trace(o_vcd, i_e_npc, i_e_npc.name()); sc_trace(o_vcd, i_ra, i_ra.name()); sc_trace(o_vcd, o_f_valid, o_f_valid.name()); sc_trace(o_vcd, o_f_pc, o_f_pc.name()); sc_trace(o_vcd, i_f_requested_pc, i_f_requested_pc.name()); sc_trace(o_vcd, i_f_fetching_pc, i_f_fetching_pc.name()); sc_trace(o_vcd, i_f_fetched_pc, i_f_fetched_pc.name()); sc_trace(o_vcd, i_d_pc, i_d_pc.name()); std::string pn(name()); sc_trace(o_vcd, wb_start_pc, pn + ".wb_start_pc"); sc_trace(o_vcd, wb_npc, pn + ".wb_npc"); sc_trace(o_vcd, wb_bp_exec, pn + ".wb_bp_exec"); sc_trace(o_vcd, wb_pd[0].jmp, pn + ".wb_pd0_jmp"); sc_trace(o_vcd, wb_pd[0].pc, pn + ".wb_pd0_pc"); sc_trace(o_vcd, wb_pd[0].npc, pn + ".wb_pd0_npc"); sc_trace(o_vcd, wb_pd[1].jmp, pn + ".wb_pd1_jmp"); sc_trace(o_vcd, wb_pd[1].pc, pn + ".wb_pd1_pc"); sc_trace(o_vcd, wb_pd[1].npc, pn + ".wb_pd1_npc"); } } void BranchPredictor::comb() { sc_uint<CFG_CPU_ADDR_BITS> vb_addr[CFG_BP_DEPTH]; sc_uint<CFG_CPU_ADDR_BITS> vb_piped[4]; sc_uint<CFG_CPU_ADDR_BITS> vb_fetch_npc; bool v_btb_we; sc_uint<CFG_CPU_ADDR_BITS> vb_btb_we_pc; sc_uint<CFG_CPU_ADDR_BITS> vb_btb_we_npc; sc_uint<4> vb_hit; sc_uint<2> vb_ignore_pd; // Transform address into 2-dimesional array for convinience for (int i = 0; i < CFG_BP_DEPTH; i++) { vb_addr[i] = wb_npc.read()((i+1)*CFG_CPU_ADDR_BITS-1, i*CFG_CPU_ADDR_BITS); } vb_piped[0] = i_d_pc.read()(CFG_CPU_ADDR_BITS-1, 2); vb_piped[1] = i_f_fetched_pc.read()(CFG_CPU_ADDR_BITS-1, 2); vb_piped[2] = i_f_fetching_pc.read()(CFG_CPU_ADDR_BITS-1, 2); vb_piped[3] = i_f_requested_pc.read()(CFG_CPU_ADDR_BITS-1, 2); vb_hit = 0; for (int n = 0; n < 4; n++) { for (int i = n; i < 4; i++) { if (vb_addr[n](CFG_CPU_ADDR_BITS-1, 2) == vb_piped[i]) { vb_hit[n] = 1; } } } vb_fetch_npc = vb_addr[CFG_BP_DEPTH-1]; for (int i = 3; i >= 0; i--) { if (vb_hit[i] == 0) { vb_fetch_npc = vb_addr[i]; } } // Pre-decoder input signals (not used for now) for (int i = 0; i < 2; i++) { wb_pd[i].c_valid = !i_resp_mem_data.read()(16*i+1, 16*i).and_reduce(); wb_pd[i].addr = i_resp_mem_addr.read() + 2*i; wb_pd[i].data = i_resp_mem_data.read()(16*i + 31, 16*i); } vb_ignore_pd = 0; for (int i = 0; i < 4; i++) { if (wb_pd[0].npc.read()(CFG_CPU_ADDR_BITS-1, 2) == vb_piped[i]) { vb_ignore_pd[0] = 1; } if (wb_pd[1].npc.read()(CFG_CPU_ADDR_BITS-1, 2) == vb_piped[i]) { vb_ignore_pd[1] = 1; } } v_btb_we = i_e_jmp || wb_pd[0].jmp || wb_pd[1].jmp; if (i_e_jmp) { vb_btb_we_pc = i_e_pc; vb_btb_we_npc = i_e_npc; } else if (wb_pd[0].jmp) { vb_btb_we_pc = wb_pd[0].pc; vb_btb_we_npc = wb_pd[0].npc; if (vb_hit(2, 0) == 0x7 && wb_bp_exec.read()[2] == 0 && !vb_ignore_pd[0]) { vb_fetch_npc = wb_pd[0].npc; } } else if (wb_pd[1].jmp) { vb_btb_we_pc = wb_pd[1].pc; vb_btb_we_npc = wb_pd[1].npc; if (vb_hit(2, 0) == 0x7 && wb_bp_exec.read()[2] == 0 && !vb_ignore_pd[1]) { vb_fetch_npc = wb_pd[1].npc; } } else { vb_btb_we_pc = i_e_pc; vb_btb_we_npc = i_e_npc; } wb_start_pc = i_e_npc; w_btb_e = i_e_jmp; w_btb_we = v_btb_we; wb_btb_we_pc = vb_btb_we_pc; wb_btb_we_npc = vb_btb_we_npc; o_f_valid = 1; o_f_pc = (vb_fetch_npc >> 2) << 2; } } // namespace debugger <commit_msg>[*] adding rtlgen generated systemc module bp into project<commit_after>// // Copyright 2022 Sergey Khabarov, sergeykhbr@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "bp.h" #include "api_core.h" namespace debugger { BranchPredictor::BranchPredictor(sc_module_name name, bool async_reset) : sc_module(name), i_clk("i_clk"), i_nrst("i_nrst"), i_flush_pipeline("i_flush_pipeline"), i_resp_mem_valid("i_resp_mem_valid"), i_resp_mem_addr("i_resp_mem_addr"), i_resp_mem_data("i_resp_mem_data"), i_e_jmp("i_e_jmp"), i_e_pc("i_e_pc"), i_e_npc("i_e_npc"), i_ra("i_ra"), o_f_valid("o_f_valid"), o_f_pc("o_f_pc"), i_f_requested_pc("i_f_requested_pc"), i_f_fetching_pc("i_f_fetching_pc"), i_f_fetched_pc("i_f_fetched_pc"), i_d_pc("i_d_pc") { async_reset_ = async_reset; for (int i = 0; i < 2; i++) { char tstr[256]; RISCV_sprintf(tstr, sizeof(tstr), "predec%d", i); predec[i] = new BpPreDecoder(tstr); predec[i]->i_c_valid(wb_pd[i].c_valid); predec[i]->i_addr(wb_pd[i].addr); predec[i]->i_data(wb_pd[i].data); predec[i]->i_ra(i_ra); predec[i]->o_jmp(wb_pd[i].jmp); predec[i]->o_pc(wb_pd[i].pc); predec[i]->o_npc(wb_pd[i].npc); } btb = new BpBTB("btb", async_reset); btb->i_clk(i_clk); btb->i_nrst(i_nrst); btb->i_flush_pipeline(i_flush_pipeline); btb->i_e(w_btb_e); btb->i_we(w_btb_we); btb->i_we_pc(wb_btb_we_pc); btb->i_we_npc(wb_btb_we_npc); btb->i_bp_pc(wb_start_pc); btb->o_bp_npc(wb_npc); btb->o_bp_exec(wb_bp_exec); SC_METHOD(comb); sensitive << i_nrst; sensitive << i_flush_pipeline; sensitive << i_resp_mem_valid; sensitive << i_resp_mem_addr; sensitive << i_resp_mem_data; sensitive << i_e_jmp; sensitive << i_e_pc; sensitive << i_e_npc; sensitive << i_ra; sensitive << i_f_requested_pc; sensitive << i_f_fetching_pc; sensitive << i_f_fetched_pc; sensitive << i_d_pc; for (int i = 0; i < 2; i++) { sensitive << wb_pd[i].c_valid; sensitive << wb_pd[i].addr; sensitive << wb_pd[i].data; sensitive << wb_pd[i].jmp; sensitive << wb_pd[i].pc; sensitive << wb_pd[i].npc; } sensitive << w_btb_e; sensitive << w_btb_we; sensitive << wb_btb_we_pc; sensitive << wb_btb_we_npc; sensitive << wb_start_pc; sensitive << wb_npc; sensitive << wb_bp_exec; } BranchPredictor::~BranchPredictor() { delete btb; for (int i = 0; i < 2; i++) { delete predec[i]; } } void BranchPredictor::generateVCD(sc_trace_file *i_vcd, sc_trace_file *o_vcd) { if (o_vcd) { sc_trace(o_vcd, i_flush_pipeline, i_flush_pipeline.name()); sc_trace(o_vcd, i_resp_mem_valid, i_resp_mem_valid.name()); sc_trace(o_vcd, i_resp_mem_addr, i_resp_mem_addr.name()); sc_trace(o_vcd, i_resp_mem_data, i_resp_mem_data.name()); sc_trace(o_vcd, i_e_jmp, i_e_jmp.name()); sc_trace(o_vcd, i_e_pc, i_e_pc.name()); sc_trace(o_vcd, i_e_npc, i_e_npc.name()); sc_trace(o_vcd, i_ra, i_ra.name()); sc_trace(o_vcd, o_f_valid, o_f_valid.name()); sc_trace(o_vcd, o_f_pc, o_f_pc.name()); sc_trace(o_vcd, i_f_requested_pc, i_f_requested_pc.name()); sc_trace(o_vcd, i_f_fetching_pc, i_f_fetching_pc.name()); sc_trace(o_vcd, i_f_fetched_pc, i_f_fetched_pc.name()); sc_trace(o_vcd, i_d_pc, i_d_pc.name()); } btb->generateVCD(i_vcd, o_vcd); for (int i = 0; i < 2; i++) { predec[i]->generateVCD(i_vcd, o_vcd); } } void BranchPredictor::comb() { sc_uint<CFG_CPU_ADDR_BITS> vb_addr[CFG_BP_DEPTH]; sc_uint<CFG_CPU_ADDR_BITS> vb_piped[4]; sc_uint<CFG_CPU_ADDR_BITS> vb_fetch_npc; bool v_btb_we; sc_uint<CFG_CPU_ADDR_BITS> vb_btb_we_pc; sc_uint<CFG_CPU_ADDR_BITS> vb_btb_we_npc; sc_uint<4> vb_hit; sc_uint<2> vb_ignore_pd; // Transform address into 2-dimesional array for convinience for (int i = 0; i < CFG_BP_DEPTH; i++) { vb_addr[i] = wb_npc.read()((((i + 1) * CFG_CPU_ADDR_BITS) - 1), (i * CFG_CPU_ADDR_BITS)); } vb_piped[0] = i_d_pc.read()((CFG_CPU_ADDR_BITS - 1), 2); vb_piped[1] = i_f_fetched_pc.read()((CFG_CPU_ADDR_BITS - 1), 2); vb_piped[2] = i_f_fetching_pc.read()((CFG_CPU_ADDR_BITS - 1), 2); vb_piped[3] = i_f_requested_pc.read()((CFG_CPU_ADDR_BITS - 1), 2); vb_hit = 0; for (int n = 0; n < 4; n++) { for (int i = n; i < 4; i++) { if (vb_addr[n]((CFG_CPU_ADDR_BITS - 1), 2) == vb_piped[i]) { vb_hit[n] = 1; } } } vb_fetch_npc = vb_addr[(CFG_BP_DEPTH - 1)]; for (int i = 3; i >= 0; i--) { if (vb_hit[i] == 0) { vb_fetch_npc = vb_addr[i]; } } // Pre-decoder input signals (not used for now) for (int i = 0; i < 2; i++) { wb_pd[i].c_valid = (!i_resp_mem_data.read()(((16 * i) + 1), (16 * i)).and_reduce()); wb_pd[i].addr = (i_resp_mem_addr.read() + (2 * i)); wb_pd[i].data = i_resp_mem_data.read()(((16 * i) + 31), (16 * i)); } vb_ignore_pd = 0; for (int i = 0; i < 4; i++) { if (wb_pd[0].npc.read()((CFG_CPU_ADDR_BITS - 1), 2) == vb_piped[i]) { vb_ignore_pd[0] = 1; } if (wb_pd[1].npc.read()((CFG_CPU_ADDR_BITS - 1), 2) == vb_piped[i]) { vb_ignore_pd[1] = 1; } } v_btb_we = (i_e_jmp || wb_pd[0].jmp || wb_pd[1].jmp); if (i_e_jmp == 1) { vb_btb_we_pc = i_e_pc; vb_btb_we_npc = i_e_npc; } else if (wb_pd[0].jmp) { vb_btb_we_pc = wb_pd[0].pc; vb_btb_we_npc = wb_pd[0].npc; if ((vb_hit(2, 0) == 0x7) && (wb_bp_exec.read()[2] == 0) && (vb_ignore_pd[0] == 0)) { vb_fetch_npc = wb_pd[0].npc; } } else if (wb_pd[1].jmp) { vb_btb_we_pc = wb_pd[1].pc; vb_btb_we_npc = wb_pd[1].npc; if ((vb_hit(2, 0) == 0x7) && (wb_bp_exec.read()[2] == 0) && (vb_ignore_pd[1] == 0)) { vb_fetch_npc = wb_pd[1].npc; } } else { vb_btb_we_pc = i_e_pc; vb_btb_we_npc = i_e_npc; } wb_start_pc = i_e_npc; w_btb_e = i_e_jmp; w_btb_we = v_btb_we; wb_btb_we_pc = vb_btb_we_pc; wb_btb_we_npc = vb_btb_we_npc; o_f_valid = 1; o_f_pc = (vb_fetch_npc((CFG_CPU_ADDR_BITS - 1), 2) << 2); } } // namespace debugger <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <ndb_global.h> #include "NdbApiSignal.hpp" #include "NdbImpl.hpp" //#include "NdbSchemaOp.hpp" //#include "NdbSchemaCon.hpp" #include "NdbOperation.hpp" #include "NdbConnection.hpp" #include "NdbRecAttr.hpp" #include "IPCConfig.hpp" #include "TransporterFacade.hpp" #include "ConfigRetriever.hpp" #include <ndb_limits.h> #include <NdbOut.hpp> #include <NdbSleep.h> #include "ObjectMap.hpp" class NdbGlobalEventBufferHandle; NdbGlobalEventBufferHandle *NdbGlobalEventBuffer_init(int); void NdbGlobalEventBuffer_drop(NdbGlobalEventBufferHandle *); /** * Static object for NDB */ static int theNoOfNdbObjects = 0; static char *ndbConnectString = 0; static Ndb_cluster_connection *global_ndb_cluster_connection= 0; #if defined NDB_WIN32 || defined SCO static NdbMutex & createNdbMutex = * NdbMutex_Create(); #else static NdbMutex createNdbMutex = NDB_MUTEX_INITIALIZER; #endif /*************************************************************************** Ndb(const char* aDataBase); Parameters: aDataBase : Name of the database. Remark: Connect to the database. ***************************************************************************/ Ndb::Ndb( const char* aDataBase , const char* aSchema) { if (global_ndb_cluster_connection == 0) { if (theNoOfNdbObjects > 0) abort(); // old and new Ndb constructor used mixed global_ndb_cluster_connection= new Ndb_cluster_connection(ndbConnectString); global_ndb_cluster_connection->connect(); } setup(global_ndb_cluster_connection, aDataBase, aSchema); } Ndb::Ndb( Ndb_cluster_connection *ndb_cluster_connection, const char* aDataBase , const char* aSchema) { if (global_ndb_cluster_connection != 0 && global_ndb_cluster_connection != ndb_cluster_connection) abort(); // old and new Ndb constructor used mixed setup(ndb_cluster_connection, aDataBase, aSchema); } void Ndb::setup(Ndb_cluster_connection *ndb_cluster_connection, const char* aDataBase , const char* aSchema) { DBUG_ENTER("Ndb::setup"); theNdbObjectIdMap= 0; m_ndb_cluster_connection= ndb_cluster_connection; thePreparedTransactionsArray= NULL; theSentTransactionsArray= NULL; theCompletedTransactionsArray= NULL; theNoOfPreparedTransactions= 0; theNoOfSentTransactions= 0; theNoOfCompletedTransactions= 0; theNoOfAllocatedTransactions= 0; theMaxNoOfTransactions= 0; theMinNoOfEventsToWakeUp= 0; prefixEnd= NULL; theImpl= NULL; theDictionary= NULL; theConIdleList= NULL; theOpIdleList= NULL; theScanOpIdleList= NULL; theIndexOpIdleList= NULL; // theSchemaConIdleList= NULL; // theSchemaConToNdbList= NULL; theTransactionList= NULL; theConnectionArray= NULL; theRecAttrIdleList= NULL; theSignalIdleList= NULL; theLabelList= NULL; theBranchList= NULL; theSubroutineList= NULL; theCallList= NULL; theScanList= NULL; theNdbBlobIdleList= NULL; theNoOfDBnodes= 0; theDBnodes= NULL; the_release_ind= NULL; the_last_check_time= 0; theFirstTransId= 0; theRestartGCI= 0; theNdbBlockNumber= -1; theInitState= NotConstructed; theNode= 0; theFirstTransId= 0; theMyRef= 0; theNoOfDBnodes= 0; fullyQualifiedNames = true; cgetSignals =0; cfreeSignals = 0; cnewSignals = 0; creleaseSignals = 0; theError.code = 0; theNdbObjectIdMap = new NdbObjectIdMap(1024,1024); theConnectionArray = new NdbConnection * [MAX_NDB_NODES]; theDBnodes = new Uint32[MAX_NDB_NODES]; the_release_ind = new Uint8[MAX_NDB_NODES]; theCommitAckSignal = NULL; theCurrentConnectCounter = 1; theCurrentConnectIndex = 0; int i; for (i = 0; i < MAX_NDB_NODES ; i++) { theConnectionArray[i] = NULL; the_release_ind[i] = 0; theDBnodes[i] = 0; }//forg for (i = 0; i < 2048 ; i++) { theFirstTupleId[i] = 0; theLastTupleId[i] = 0; }//for snprintf(theDataBase, sizeof(theDataBase), "%s", aDataBase ? aDataBase : ""); snprintf(theDataBaseSchema, sizeof(theDataBaseSchema), "%s", aSchema ? aSchema : ""); int len = snprintf(prefixName, sizeof(prefixName), "%s%c%s%c", theDataBase, table_name_separator, theDataBaseSchema, table_name_separator); prefixEnd = prefixName + (len < sizeof(prefixName) ? len : sizeof(prefixName) - 1); NdbMutex_Lock(&createNdbMutex); theWaiter.m_mutex = TransporterFacade::instance()->theMutexPtr; // For keeping track of how many Ndb objects that exists. theNoOfNdbObjects += 1; // Signal that the constructor has finished OK if (theInitState == NotConstructed) theInitState = NotInitialised; theImpl = new NdbImpl(); { NdbGlobalEventBufferHandle *h= NdbGlobalEventBuffer_init(NDB_MAX_ACTIVE_EVENTS); if (h == NULL) { ndbout_c("Failed NdbGlobalEventBuffer_init(%d)",NDB_MAX_ACTIVE_EVENTS); exit(-1); } theGlobalEventBufferHandle = h; } NdbMutex_Unlock(&createNdbMutex); theDictionary = new NdbDictionaryImpl(*this); if (theDictionary == NULL) { ndbout_c("Ndb cailed to allocate dictionary"); exit(-1); } DBUG_VOID_RETURN; } void Ndb::setConnectString(const char * connectString) { if (ndbConnectString != 0) { free(ndbConnectString); ndbConnectString = 0; } if (connectString) ndbConnectString = strdup(connectString); } /***************************************************************************** * ~Ndb(); * * Remark: Disconnect with the database. *****************************************************************************/ Ndb::~Ndb() { DBUG_ENTER("Ndb::~Ndb()"); doDisconnect(); delete theDictionary; delete theImpl; NdbGlobalEventBuffer_drop(theGlobalEventBufferHandle); if (TransporterFacade::instance() != NULL && theNdbBlockNumber > 0){ TransporterFacade::instance()->close(theNdbBlockNumber, theFirstTransId); } NdbMutex_Lock(&createNdbMutex); theNoOfNdbObjects -= 1; if(theNoOfNdbObjects == 0){ TransporterFacade::stop_instance(); if (global_ndb_cluster_connection != 0) { delete global_ndb_cluster_connection; global_ndb_cluster_connection= 0; } }//if NdbMutex_Unlock(&createNdbMutex); // if (theSchemaConToNdbList != NULL) // closeSchemaTransaction(theSchemaConToNdbList); while ( theConIdleList != NULL ) freeNdbCon(); while ( theSignalIdleList != NULL ) freeSignal(); while (theRecAttrIdleList != NULL) freeRecAttr(); while (theOpIdleList != NULL) freeOperation(); while (theScanOpIdleList != NULL) freeScanOperation(); while (theIndexOpIdleList != NULL) freeIndexOperation(); while (theLabelList != NULL) freeNdbLabel(); while (theBranchList != NULL) freeNdbBranch(); while (theSubroutineList != NULL) freeNdbSubroutine(); while (theCallList != NULL) freeNdbCall(); while (theScanList != NULL) freeNdbScanRec(); while (theNdbBlobIdleList != NULL) freeNdbBlob(); releaseTransactionArrays(); startTransactionNodeSelectionData.release(); delete []theConnectionArray; delete []theDBnodes; delete []the_release_ind; if(theCommitAckSignal != NULL){ delete theCommitAckSignal; theCommitAckSignal = NULL; } if(theNdbObjectIdMap != 0) delete theNdbObjectIdMap; /** * This sleep is to make sure that the transporter * send thread will come in and send any * signal buffers that this thread may have allocated. * If that doesn't happen an error will occur in OSE * when trying to restore a signal buffer allocated by a thread * that have been killed. */ #ifdef NDB_OSE NdbSleep_MilliSleep(50); #endif #ifdef POORMANSPURIFY #ifdef POORMANSGUI ndbout << "cnewSignals=" << cnewSignals << endl; ndbout << "cfreeSignals=" << cfreeSignals << endl; ndbout << "cgetSignals=" << cgetSignals << endl; ndbout << "creleaseSignals=" << creleaseSignals << endl; #endif // Poor mans purifier assert(cnewSignals == cfreeSignals); assert(cgetSignals == creleaseSignals); #endif DBUG_VOID_RETURN; } NdbWaiter::NdbWaiter(){ m_node = 0; m_state = NO_WAIT; m_mutex = 0; m_condition = NdbCondition_Create(); } NdbWaiter::~NdbWaiter(){ NdbCondition_Destroy(m_condition); } <commit_msg>introduced my_init() in backwards compatible Ndb constructor<commit_after>/* Copyright (C) 2003 MySQL AB 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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <ndb_global.h> #include <my_sys.h> #include "NdbApiSignal.hpp" #include "NdbImpl.hpp" //#include "NdbSchemaOp.hpp" //#include "NdbSchemaCon.hpp" #include "NdbOperation.hpp" #include "NdbConnection.hpp" #include "NdbRecAttr.hpp" #include "IPCConfig.hpp" #include "TransporterFacade.hpp" #include "ConfigRetriever.hpp" #include <ndb_limits.h> #include <NdbOut.hpp> #include <NdbSleep.h> #include "ObjectMap.hpp" class NdbGlobalEventBufferHandle; NdbGlobalEventBufferHandle *NdbGlobalEventBuffer_init(int); void NdbGlobalEventBuffer_drop(NdbGlobalEventBufferHandle *); /** * Static object for NDB */ static int theNoOfNdbObjects = 0; static char *ndbConnectString = 0; static Ndb_cluster_connection *global_ndb_cluster_connection= 0; #if defined NDB_WIN32 || defined SCO static NdbMutex & createNdbMutex = * NdbMutex_Create(); #else static NdbMutex createNdbMutex = NDB_MUTEX_INITIALIZER; #endif /*************************************************************************** Ndb(const char* aDataBase); Parameters: aDataBase : Name of the database. Remark: Connect to the database. ***************************************************************************/ Ndb::Ndb( const char* aDataBase , const char* aSchema) { if (global_ndb_cluster_connection == 0) { if (theNoOfNdbObjects > 0) abort(); // old and new Ndb constructor used mixed my_init(); global_ndb_cluster_connection= new Ndb_cluster_connection(ndbConnectString); global_ndb_cluster_connection->connect(); } setup(global_ndb_cluster_connection, aDataBase, aSchema); } Ndb::Ndb( Ndb_cluster_connection *ndb_cluster_connection, const char* aDataBase , const char* aSchema) { if (global_ndb_cluster_connection != 0 && global_ndb_cluster_connection != ndb_cluster_connection) abort(); // old and new Ndb constructor used mixed setup(ndb_cluster_connection, aDataBase, aSchema); } void Ndb::setup(Ndb_cluster_connection *ndb_cluster_connection, const char* aDataBase , const char* aSchema) { DBUG_ENTER("Ndb::setup"); theNdbObjectIdMap= 0; m_ndb_cluster_connection= ndb_cluster_connection; thePreparedTransactionsArray= NULL; theSentTransactionsArray= NULL; theCompletedTransactionsArray= NULL; theNoOfPreparedTransactions= 0; theNoOfSentTransactions= 0; theNoOfCompletedTransactions= 0; theNoOfAllocatedTransactions= 0; theMaxNoOfTransactions= 0; theMinNoOfEventsToWakeUp= 0; prefixEnd= NULL; theImpl= NULL; theDictionary= NULL; theConIdleList= NULL; theOpIdleList= NULL; theScanOpIdleList= NULL; theIndexOpIdleList= NULL; // theSchemaConIdleList= NULL; // theSchemaConToNdbList= NULL; theTransactionList= NULL; theConnectionArray= NULL; theRecAttrIdleList= NULL; theSignalIdleList= NULL; theLabelList= NULL; theBranchList= NULL; theSubroutineList= NULL; theCallList= NULL; theScanList= NULL; theNdbBlobIdleList= NULL; theNoOfDBnodes= 0; theDBnodes= NULL; the_release_ind= NULL; the_last_check_time= 0; theFirstTransId= 0; theRestartGCI= 0; theNdbBlockNumber= -1; theInitState= NotConstructed; theNode= 0; theFirstTransId= 0; theMyRef= 0; theNoOfDBnodes= 0; fullyQualifiedNames = true; cgetSignals =0; cfreeSignals = 0; cnewSignals = 0; creleaseSignals = 0; theError.code = 0; theNdbObjectIdMap = new NdbObjectIdMap(1024,1024); theConnectionArray = new NdbConnection * [MAX_NDB_NODES]; theDBnodes = new Uint32[MAX_NDB_NODES]; the_release_ind = new Uint8[MAX_NDB_NODES]; theCommitAckSignal = NULL; theCurrentConnectCounter = 1; theCurrentConnectIndex = 0; int i; for (i = 0; i < MAX_NDB_NODES ; i++) { theConnectionArray[i] = NULL; the_release_ind[i] = 0; theDBnodes[i] = 0; }//forg for (i = 0; i < 2048 ; i++) { theFirstTupleId[i] = 0; theLastTupleId[i] = 0; }//for snprintf(theDataBase, sizeof(theDataBase), "%s", aDataBase ? aDataBase : ""); snprintf(theDataBaseSchema, sizeof(theDataBaseSchema), "%s", aSchema ? aSchema : ""); int len = snprintf(prefixName, sizeof(prefixName), "%s%c%s%c", theDataBase, table_name_separator, theDataBaseSchema, table_name_separator); prefixEnd = prefixName + (len < sizeof(prefixName) ? len : sizeof(prefixName) - 1); NdbMutex_Lock(&createNdbMutex); theWaiter.m_mutex = TransporterFacade::instance()->theMutexPtr; // For keeping track of how many Ndb objects that exists. theNoOfNdbObjects += 1; // Signal that the constructor has finished OK if (theInitState == NotConstructed) theInitState = NotInitialised; theImpl = new NdbImpl(); { NdbGlobalEventBufferHandle *h= NdbGlobalEventBuffer_init(NDB_MAX_ACTIVE_EVENTS); if (h == NULL) { ndbout_c("Failed NdbGlobalEventBuffer_init(%d)",NDB_MAX_ACTIVE_EVENTS); exit(-1); } theGlobalEventBufferHandle = h; } NdbMutex_Unlock(&createNdbMutex); theDictionary = new NdbDictionaryImpl(*this); if (theDictionary == NULL) { ndbout_c("Ndb cailed to allocate dictionary"); exit(-1); } DBUG_VOID_RETURN; } void Ndb::setConnectString(const char * connectString) { if (ndbConnectString != 0) { free(ndbConnectString); ndbConnectString = 0; } if (connectString) ndbConnectString = strdup(connectString); } /***************************************************************************** * ~Ndb(); * * Remark: Disconnect with the database. *****************************************************************************/ Ndb::~Ndb() { DBUG_ENTER("Ndb::~Ndb()"); doDisconnect(); delete theDictionary; delete theImpl; NdbGlobalEventBuffer_drop(theGlobalEventBufferHandle); if (TransporterFacade::instance() != NULL && theNdbBlockNumber > 0){ TransporterFacade::instance()->close(theNdbBlockNumber, theFirstTransId); } NdbMutex_Lock(&createNdbMutex); theNoOfNdbObjects -= 1; if(theNoOfNdbObjects == 0){ TransporterFacade::stop_instance(); if (global_ndb_cluster_connection != 0) { delete global_ndb_cluster_connection; global_ndb_cluster_connection= 0; } }//if NdbMutex_Unlock(&createNdbMutex); // if (theSchemaConToNdbList != NULL) // closeSchemaTransaction(theSchemaConToNdbList); while ( theConIdleList != NULL ) freeNdbCon(); while ( theSignalIdleList != NULL ) freeSignal(); while (theRecAttrIdleList != NULL) freeRecAttr(); while (theOpIdleList != NULL) freeOperation(); while (theScanOpIdleList != NULL) freeScanOperation(); while (theIndexOpIdleList != NULL) freeIndexOperation(); while (theLabelList != NULL) freeNdbLabel(); while (theBranchList != NULL) freeNdbBranch(); while (theSubroutineList != NULL) freeNdbSubroutine(); while (theCallList != NULL) freeNdbCall(); while (theScanList != NULL) freeNdbScanRec(); while (theNdbBlobIdleList != NULL) freeNdbBlob(); releaseTransactionArrays(); startTransactionNodeSelectionData.release(); delete []theConnectionArray; delete []theDBnodes; delete []the_release_ind; if(theCommitAckSignal != NULL){ delete theCommitAckSignal; theCommitAckSignal = NULL; } if(theNdbObjectIdMap != 0) delete theNdbObjectIdMap; /** * This sleep is to make sure that the transporter * send thread will come in and send any * signal buffers that this thread may have allocated. * If that doesn't happen an error will occur in OSE * when trying to restore a signal buffer allocated by a thread * that have been killed. */ #ifdef NDB_OSE NdbSleep_MilliSleep(50); #endif #ifdef POORMANSPURIFY #ifdef POORMANSGUI ndbout << "cnewSignals=" << cnewSignals << endl; ndbout << "cfreeSignals=" << cfreeSignals << endl; ndbout << "cgetSignals=" << cgetSignals << endl; ndbout << "creleaseSignals=" << creleaseSignals << endl; #endif // Poor mans purifier assert(cnewSignals == cfreeSignals); assert(cgetSignals == creleaseSignals); #endif DBUG_VOID_RETURN; } NdbWaiter::NdbWaiter(){ m_node = 0; m_state = NO_WAIT; m_mutex = 0; m_condition = NdbCondition_Create(); } NdbWaiter::~NdbWaiter(){ NdbCondition_Destroy(m_condition); } <|endoftext|>
<commit_before>#include "kwm.h" extern window_info *FocusedWindow; int KwmSockFD; bool KwmDaemonIsRunning; int KwmDaemonPort = 3020; std::string KwmReadFromSocket(int ClientSockFD) { char Cur; std::string Message; while(recv(ClientSockFD, &Cur, 1, 0)) { if(Cur == '\n') break; Message += Cur; } return Message; } void KwmWriteToSocket(int ClientSockFD, std::string Msg) { send(ClientSockFD, Msg.c_str(), Msg.size(), 0); } void * KwmDaemonHandleConnectionBG(void *) { while(KwmDaemonIsRunning) KwmDaemonHandleConnection(); } void KwmDaemonHandleConnection() { int ClientSockFD; struct sockaddr_in ClientAddr; socklen_t SinSize = sizeof(struct sockaddr); ClientSockFD = accept(KwmSockFD, (struct sockaddr*)&ClientAddr, &SinSize); if(ClientSockFD != -1) { std::string Message; std::stringstream Stream(KwmReadFromSocket(ClientSockFD)); std::getline(Stream, Message, ' '); if(Message == "focused") { std::cout << "write to socket" << std::endl; KwmWriteToSocket(ClientSockFD, FocusedWindow->Name); } close(ClientSockFD); } } void KwmTerminateDaemon() { KwmDaemonIsRunning = false; close(KwmSockFD); } void KwmStartDaemon() { struct sockaddr_in SrvAddr; int _True = 1; if((KwmSockFD = socket(PF_INET, SOCK_STREAM, 0)) == -1) Fatal("Could not create socket!"); if(setsockopt(KwmSockFD, SOL_SOCKET, SO_REUSEADDR, &_True, sizeof(int)) == -1) std::cout << "Could not set socket option: SO_REUSEADDR!" << std::endl; SrvAddr.sin_family = AF_INET; SrvAddr.sin_port = htons(KwmDaemonPort); SrvAddr.sin_addr.s_addr = 0; std::memset(&SrvAddr.sin_zero, '\0', 8); if(bind(KwmSockFD, (struct sockaddr*)&SrvAddr, sizeof(struct sockaddr)) == -1) Fatal("Could not bind to port!"); if(listen(KwmSockFD, 10) == -1) Fatal("Could not start listening!"); KwmDaemonIsRunning = true; std::cout << "Local Daemon is now running.." << std::endl; } <commit_msg>removed print<commit_after>#include "kwm.h" extern window_info *FocusedWindow; int KwmSockFD; bool KwmDaemonIsRunning; int KwmDaemonPort = 3020; std::string KwmReadFromSocket(int ClientSockFD) { char Cur; std::string Message; while(recv(ClientSockFD, &Cur, 1, 0)) { if(Cur == '\n') break; Message += Cur; } return Message; } void KwmWriteToSocket(int ClientSockFD, std::string Msg) { send(ClientSockFD, Msg.c_str(), Msg.size(), 0); } void * KwmDaemonHandleConnectionBG(void *) { while(KwmDaemonIsRunning) KwmDaemonHandleConnection(); } void KwmDaemonHandleConnection() { int ClientSockFD; struct sockaddr_in ClientAddr; socklen_t SinSize = sizeof(struct sockaddr); ClientSockFD = accept(KwmSockFD, (struct sockaddr*)&ClientAddr, &SinSize); if(ClientSockFD != -1) { std::string Message; std::stringstream Stream(KwmReadFromSocket(ClientSockFD)); std::getline(Stream, Message, ' '); if(Message == "focused") { KwmWriteToSocket(ClientSockFD, FocusedWindow->Name); } close(ClientSockFD); } } void KwmTerminateDaemon() { KwmDaemonIsRunning = false; close(KwmSockFD); } void KwmStartDaemon() { struct sockaddr_in SrvAddr; int _True = 1; if((KwmSockFD = socket(PF_INET, SOCK_STREAM, 0)) == -1) Fatal("Could not create socket!"); if(setsockopt(KwmSockFD, SOL_SOCKET, SO_REUSEADDR, &_True, sizeof(int)) == -1) std::cout << "Could not set socket option: SO_REUSEADDR!" << std::endl; SrvAddr.sin_family = AF_INET; SrvAddr.sin_port = htons(KwmDaemonPort); SrvAddr.sin_addr.s_addr = 0; std::memset(&SrvAddr.sin_zero, '\0', 8); if(bind(KwmSockFD, (struct sockaddr*)&SrvAddr, sizeof(struct sockaddr)) == -1) Fatal("Could not bind to port!"); if(listen(KwmSockFD, 10) == -1) Fatal("Could not start listening!"); KwmDaemonIsRunning = true; std::cout << "Local Daemon is now running.." << std::endl; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/modules/desktop_capture/win/window_capture_utils.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); // Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if // error occurs. std::string Utf16ToUtf8(const WCHAR* str) { int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (len_utf8 <= 0) return std::string(); std::string result(len_utf8, '\0'); int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1, &*(result.begin()), len_utf8, NULL, NULL); if (rv != len_utf8) assert(false); return result; } BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = Utf16ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; virtual bool BringSelectedWindowToFront() OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } bool WindowCapturerWin::BringSelectedWindowToFront() { if (!window_) return false; if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_)) return false; return SetForegroundWindow(window_) != 0; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been closed or hidden. if (!IsWindow(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } DesktopRect original_rect; DesktopRect cropped_rect; if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) { LOG(LS_WARNING) << "Failed to get window info: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( cropped_rect.size(), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes, including the first time of // capturing - it somehow affects what we get from BitBlt() on the subsequent // captures. if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, cropped_rect.left() - original_rect.left(), cropped_rect.top() - original_rect.top(), SRCCOPY); } SelectObject(mem_dc, previous_object); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); frame->mutable_updated_region()->SetRect( DesktopRect::MakeSize(frame->size())); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) { return new WindowCapturerWin(); } } // namespace webrtc <commit_msg>Remove trailing null character from std::string<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include "webrtc/base/win32.h" #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/modules/desktop_capture/win/window_capture_utils.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = rtc::ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; virtual bool BringSelectedWindowToFront() OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } bool WindowCapturerWin::BringSelectedWindowToFront() { if (!window_) return false; if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_)) return false; return SetForegroundWindow(window_) != 0; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been closed or hidden. if (!IsWindow(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } DesktopRect original_rect; DesktopRect cropped_rect; if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) { LOG(LS_WARNING) << "Failed to get window info: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( cropped_rect.size(), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes, including the first time of // capturing - it somehow affects what we get from BitBlt() on the subsequent // captures. if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, cropped_rect.left() - original_rect.left(), cropped_rect.top() - original_rect.top(), SRCCOPY); } SelectObject(mem_dc, previous_object); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); frame->mutable_updated_region()->SetRect( DesktopRect::MakeSize(frame->size())); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) { return new WindowCapturerWin(); } } // namespace webrtc <|endoftext|>
<commit_before>// // scalarReplace // // This pass implements scalar replacement of aggregates. // #include "astutil.h" #include "expr.h" #include "optimizations.h" #include "passes.h" #include "runtime.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "symscope.h" static bool unifyClassInstances(Symbol* sym) { bool change = false; if (sym->defs.n == 1) { if (CallExpr* call = toCallExpr(sym->defs.v[0]->parentExpr)) { if (call->isPrimitive(PRIMITIVE_MOVE)) { if (SymExpr* rhs = toSymExpr(call->get(2))) { forv_Vec(SymExpr, se, sym->uses) { se->var = rhs->var; rhs->var->uses.add(se); } call->remove(); sym->defPoint->remove(); change = true; } } } } return change; } static void scalarReplaceClassVar(ClassType* ct, Symbol* sym) { Map<Symbol*,int> field2id; // field to number map int nfields = 0; // number of fields // // compute field ordering numbers // for_fields(field, ct) { field2id.put(field, nfields++); } // // replace symbol definitions of structural type with multiple // symbol definitions of structural field types // Vec<Symbol*> syms; for_fields(field, ct) { Symbol* clone = new VarSymbol(astr(sym->name, "_", field->name), field->type); syms.add(clone); sym->defPoint->insertBefore(new DefExpr(clone)); clone->isCompilerTemp = sym->isCompilerTemp; } sym->defPoint->remove(); // // expand uses of symbols of structural type with multiple symbols // structural field types // forv_Vec(SymExpr, se, sym->uses) { if (CallExpr* call = toCallExpr(se->parentExpr)) { if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(new CallExpr(PRIMITIVE_SET_REF, use)); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(use); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); call->primitive = primitives[PRIMITIVE_MOVE]; call->get(2)->remove(); call->get(1)->remove(); SymExpr* def = new SymExpr(syms.v[id]); call->insertAtHead(def); syms.v[id]->defs.add(def); if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType) call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove())); } } } } static bool scalarReplaceClassVars(ClassType* ct, Symbol* sym) { bool change = false; if (sym->defs.n == 1) { if (CallExpr* call = toCallExpr(sym->defs.v[0]->parentExpr)) { if (call->isPrimitive(PRIMITIVE_MOVE)) { if (CallExpr* rhs = toCallExpr(call->get(2))) { if (rhs->isPrimitive(PRIMITIVE_CHPL_ALLOC)) { change = true; forv_Vec(SymExpr, se, sym->uses) { if (se->parentSymbol) { CallExpr* call = toCallExpr(se->parentExpr); if (!call || !(call->isPrimitive(PRIMITIVE_SET_MEMBER) || call->isPrimitive(PRIMITIVE_GET_MEMBER) || call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) || !(call->get(1) == se)) change = false; } } if (change) { call->remove(); scalarReplaceClassVar(ct, sym); } } } } } } return change; } static void scalarReplaceRecordVar(ClassType* ct, Symbol* sym) { Map<Symbol*,int> field2id; // field to number map int nfields = 0; // number of fields // // compute field ordering numbers // for_fields(field, ct) { field2id.put(field, nfields++); } // // replace symbol definitions of structural type with multiple // symbol definitions of structural field types // Vec<Symbol*> syms; for_fields(field, ct) { Symbol* clone = new VarSymbol(astr(sym->name, "_", field->name), field->type); syms.add(clone); sym->defPoint->insertBefore(new DefExpr(clone)); clone->isCompilerTemp = sym->isCompilerTemp; } sym->defPoint->remove(); // // expand uses of symbols of structural type with multiple symbols // structural field types // forv_Vec(SymExpr, se, sym->defs) { if (CallExpr* call = toCallExpr(se->parentExpr)) { if (call && call->isPrimitive(PRIMITIVE_MOVE)) { SymExpr* rhs = toSymExpr(call->get(2)); for_fields(field, ct) { SymExpr* rhsCopy = rhs->copy(); SymExpr* use = new SymExpr(syms.v[field2id.get(field)]); call->insertBefore( new CallExpr(PRIMITIVE_MOVE, use, new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, rhsCopy, field))); use->var->uses.add(use); rhsCopy->var->uses.add(rhsCopy); } call->remove(); } } } forv_Vec(SymExpr, se, sym->uses) { if (CallExpr* call = toCallExpr(se->parentExpr)) { if (call && call->isPrimitive(PRIMITIVE_MOVE)) { SymExpr* lhs = toSymExpr(call->get(1)); for_fields(field, ct) { SymExpr* lhsCopy = lhs->copy(); SymExpr* use = new SymExpr(syms.v[field2id.get(field)]); call->insertBefore( new CallExpr(PRIMITIVE_SET_MEMBER, lhsCopy, field, use)); use->var->uses.add(use); lhsCopy->var->uses.add(lhsCopy); } call->remove(); } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(new CallExpr(PRIMITIVE_SET_REF, use)); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(use); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); call->primitive = primitives[PRIMITIVE_MOVE]; call->get(2)->remove(); call->get(1)->remove(); SymExpr* def = new SymExpr(syms.v[id]); call->insertAtHead(def); syms.v[id]->defs.add(def); if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType) call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove())); } } } } static bool scalarReplaceRecordVars(ClassType* ct, Symbol* sym) { bool change = true; forv_Vec(SymExpr, se, sym->defs) { if (CallExpr* call = toCallExpr(se->parentExpr)) if (call->isPrimitive(PRIMITIVE_MOVE)) if (toSymExpr(call->get(2))) continue; change = false; } forv_Vec(SymExpr, se, sym->uses) { if (CallExpr* call = toCallExpr(se->parentExpr)) if ((call->isPrimitive(PRIMITIVE_SET_MEMBER) && call->get(1) == se) || call->isPrimitive(PRIMITIVE_GET_MEMBER) || call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE) || call->isPrimitive(PRIMITIVE_MOVE)) continue; change = false; } if (change) { scalarReplaceRecordVar(ct, sym); } return change; } static void scalarReplaceVars(FnSymbol* fn) { bool change = true; while (change) { singleAssignmentRefPropagation(fn); Vec<BaseAST*> asts; collect_asts(&asts, fn); Vec<DefExpr*> defs; forv_Vec(BaseAST, ast, asts) { if (DefExpr* def = toDefExpr(ast)) { if (def->sym->astTag == SYMBOL_VAR && toFnSymbol(def->parentSymbol)) { TypeSymbol* ts = def->sym->type->symbol; if (ts->hasPragma("iterator class") || ts->hasPragma("tuple")) defs.add(def); } } if (CallExpr* call = toCallExpr(ast)) { if (call->isPrimitive(PRIMITIVE_MOVE) && call->parentSymbol) { if (SymExpr* se1 = toSymExpr(call->get(1))) { if (SymExpr* se2 = toSymExpr(call->get(2))) { if (se1->var == se2->var) { call->remove(); } } } } } } compute_sym_uses(fn); change = false; forv_Vec(DefExpr, def, defs) { ClassType* ct = toClassType(def->sym->type); if (ct->symbol->hasPragma("iterator class")) { change |= unifyClassInstances(def->sym); } } // // NOTE - reenable scalar replacement // forv_Vec(DefExpr, def, defs) { ClassType* ct = toClassType(def->sym->type); if (ct->symbol->hasPragma("iterator class")) { change |= scalarReplaceClassVars(ct, def->sym); } else if (ct->symbol->hasPragma("tuple")) { change |= scalarReplaceRecordVars(ct, def->sym); } } } } // // eliminates a record type with a single field // static void scalarReplaceSingleFieldRecord(ClassType* ct) { ct->symbol->defPoint->remove(); ct->refType->symbol->defPoint->remove(); Type* fieldType = toDefExpr(ct->fields.only())->sym->type; // // update substitution map back pointers // important for ddata for which this substitution is looked at later // forv_Vec(TypeSymbol, ts, gTypes) { form_Map(ASTMapElem, e, ts->type->substitutions) { if (e->value == ct) e->value = fieldType; } } forv_Vec(BaseAST, ast, gAsts) { if (CallExpr* call = toCallExpr(ast)) { if (call->parentSymbol) { if (call->isPrimitive(PRIMITIVE_CHPL_ALLOC)) { CallExpr* parent = toCallExpr(call->parentExpr); if (parent && parent->isPrimitive(PRIMITIVE_SET_HEAPVAR)) { if (call->typeInfo() == ct) call->get(1)->replace(new SymExpr(fieldType->symbol)); } else if (call->typeInfo() == ct) call->getStmtExpr()->remove(); else if (call->typeInfo() == ct->refType) call->getStmtExpr()->remove(); } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER)) { if (call->get(1)->typeInfo() == ct || call->get(1)->typeInfo() == ct->refType) call->replace(call->get(1)->remove()); } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) { if (call->get(1)->typeInfo() == ct->refType) call->replace(new CallExpr(PRIMITIVE_GET_REF, call->get(1)->remove())); else if (call->get(1)->typeInfo() == ct) call->replace(call->get(1)->remove()); } else if (call->isPrimitive(PRIMITIVE_SET_MEMBER)) { if (call->get(1)->typeInfo() == ct || call->get(1)->typeInfo() == ct->refType) { Expr* rhs = call->get(3)->remove(); Expr* lhs = call->get(1)->remove(); call->replace(new CallExpr(PRIMITIVE_MOVE, lhs, rhs)); } } } } } forv_Vec(BaseAST, ast, gAsts) { if (DefExpr* def = toDefExpr(ast)) { if (def->parentSymbol) { if (def->sym->type == ct) { def->sym->type = fieldType; } else if (def->sym->type == ct->refType) { if (fieldType->refType) def->sym->type = fieldType->refType; else def->sym->type = fieldType; } if (FnSymbol* fn = toFnSymbol(def->sym)) { if (fn->retType == ct) { fn->retType = fieldType; } else if (fn->retType == ct->refType) { if (fieldType->refType) fn->retType = fieldType->refType; else fn->retType = fieldType; } } } } } } void scalarReplace() { if (fBaseline) return; if (!fNoScalarReplacement) { forv_Vec(FnSymbol, fn, gFns) { scalarReplaceVars(fn); } } if (!fNoScalarReplaceArrayWrappers) { forv_Vec(TypeSymbol, ts, gTypes) { if (ts->hasPragma("domain") || ts->hasPragma("array")) { scalarReplaceSingleFieldRecord(toClassType(ts->type)); } } } } <commit_msg>Modified the special scalar replacement of array and domain wrapper records optimization such that it does not rely on these records having a single field. In the array of array case, they will not have a single field since the type field will become a value.<commit_after>// // scalarReplace // // This pass implements scalar replacement of aggregates. // #include "astutil.h" #include "expr.h" #include "optimizations.h" #include "passes.h" #include "runtime.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "symscope.h" static bool unifyClassInstances(Symbol* sym) { bool change = false; if (sym->defs.n == 1) { if (CallExpr* call = toCallExpr(sym->defs.v[0]->parentExpr)) { if (call->isPrimitive(PRIMITIVE_MOVE)) { if (SymExpr* rhs = toSymExpr(call->get(2))) { forv_Vec(SymExpr, se, sym->uses) { se->var = rhs->var; rhs->var->uses.add(se); } call->remove(); sym->defPoint->remove(); change = true; } } } } return change; } static void scalarReplaceClassVar(ClassType* ct, Symbol* sym) { Map<Symbol*,int> field2id; // field to number map int nfields = 0; // number of fields // // compute field ordering numbers // for_fields(field, ct) { field2id.put(field, nfields++); } // // replace symbol definitions of structural type with multiple // symbol definitions of structural field types // Vec<Symbol*> syms; for_fields(field, ct) { Symbol* clone = new VarSymbol(astr(sym->name, "_", field->name), field->type); syms.add(clone); sym->defPoint->insertBefore(new DefExpr(clone)); clone->isCompilerTemp = sym->isCompilerTemp; } sym->defPoint->remove(); // // expand uses of symbols of structural type with multiple symbols // structural field types // forv_Vec(SymExpr, se, sym->uses) { if (CallExpr* call = toCallExpr(se->parentExpr)) { if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(new CallExpr(PRIMITIVE_SET_REF, use)); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(use); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); call->primitive = primitives[PRIMITIVE_MOVE]; call->get(2)->remove(); call->get(1)->remove(); SymExpr* def = new SymExpr(syms.v[id]); call->insertAtHead(def); syms.v[id]->defs.add(def); if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType) call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove())); } } } } static bool scalarReplaceClassVars(ClassType* ct, Symbol* sym) { bool change = false; if (sym->defs.n == 1) { if (CallExpr* call = toCallExpr(sym->defs.v[0]->parentExpr)) { if (call->isPrimitive(PRIMITIVE_MOVE)) { if (CallExpr* rhs = toCallExpr(call->get(2))) { if (rhs->isPrimitive(PRIMITIVE_CHPL_ALLOC)) { change = true; forv_Vec(SymExpr, se, sym->uses) { if (se->parentSymbol) { CallExpr* call = toCallExpr(se->parentExpr); if (!call || !(call->isPrimitive(PRIMITIVE_SET_MEMBER) || call->isPrimitive(PRIMITIVE_GET_MEMBER) || call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) || !(call->get(1) == se)) change = false; } } if (change) { call->remove(); scalarReplaceClassVar(ct, sym); } } } } } } return change; } static void scalarReplaceRecordVar(ClassType* ct, Symbol* sym) { Map<Symbol*,int> field2id; // field to number map int nfields = 0; // number of fields // // compute field ordering numbers // for_fields(field, ct) { field2id.put(field, nfields++); } // // replace symbol definitions of structural type with multiple // symbol definitions of structural field types // Vec<Symbol*> syms; for_fields(field, ct) { Symbol* clone = new VarSymbol(astr(sym->name, "_", field->name), field->type); syms.add(clone); sym->defPoint->insertBefore(new DefExpr(clone)); clone->isCompilerTemp = sym->isCompilerTemp; } sym->defPoint->remove(); // // expand uses of symbols of structural type with multiple symbols // structural field types // forv_Vec(SymExpr, se, sym->defs) { if (CallExpr* call = toCallExpr(se->parentExpr)) { if (call && call->isPrimitive(PRIMITIVE_MOVE)) { SymExpr* rhs = toSymExpr(call->get(2)); for_fields(field, ct) { SymExpr* rhsCopy = rhs->copy(); SymExpr* use = new SymExpr(syms.v[field2id.get(field)]); call->insertBefore( new CallExpr(PRIMITIVE_MOVE, use, new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, rhsCopy, field))); use->var->uses.add(use); rhsCopy->var->uses.add(rhsCopy); } call->remove(); } } } forv_Vec(SymExpr, se, sym->uses) { if (CallExpr* call = toCallExpr(se->parentExpr)) { if (call && call->isPrimitive(PRIMITIVE_MOVE)) { SymExpr* lhs = toSymExpr(call->get(1)); for_fields(field, ct) { SymExpr* lhsCopy = lhs->copy(); SymExpr* use = new SymExpr(syms.v[field2id.get(field)]); call->insertBefore( new CallExpr(PRIMITIVE_SET_MEMBER, lhsCopy, field, use)); use->var->uses.add(use); lhsCopy->var->uses.add(lhsCopy); } call->remove(); } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(new CallExpr(PRIMITIVE_SET_REF, use)); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); SymExpr* use = new SymExpr(syms.v[id]); call->replace(use); syms.v[id]->uses.add(use); } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) { SymExpr* member = toSymExpr(call->get(2)); int id = field2id.get(member->var); call->primitive = primitives[PRIMITIVE_MOVE]; call->get(2)->remove(); call->get(1)->remove(); SymExpr* def = new SymExpr(syms.v[id]); call->insertAtHead(def); syms.v[id]->defs.add(def); if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType) call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove())); } } } } static bool scalarReplaceRecordVars(ClassType* ct, Symbol* sym) { bool change = true; forv_Vec(SymExpr, se, sym->defs) { if (CallExpr* call = toCallExpr(se->parentExpr)) if (call->isPrimitive(PRIMITIVE_MOVE)) if (toSymExpr(call->get(2))) continue; change = false; } forv_Vec(SymExpr, se, sym->uses) { if (CallExpr* call = toCallExpr(se->parentExpr)) if ((call->isPrimitive(PRIMITIVE_SET_MEMBER) && call->get(1) == se) || call->isPrimitive(PRIMITIVE_GET_MEMBER) || call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE) || call->isPrimitive(PRIMITIVE_MOVE)) continue; change = false; } if (change) { scalarReplaceRecordVar(ct, sym); } return change; } static void scalarReplaceVars(FnSymbol* fn) { bool change = true; while (change) { singleAssignmentRefPropagation(fn); Vec<BaseAST*> asts; collect_asts(&asts, fn); Vec<DefExpr*> defs; forv_Vec(BaseAST, ast, asts) { if (DefExpr* def = toDefExpr(ast)) { if (def->sym->astTag == SYMBOL_VAR && toFnSymbol(def->parentSymbol)) { TypeSymbol* ts = def->sym->type->symbol; if (ts->hasPragma("iterator class") || ts->hasPragma("tuple")) defs.add(def); } } if (CallExpr* call = toCallExpr(ast)) { if (call->isPrimitive(PRIMITIVE_MOVE) && call->parentSymbol) { if (SymExpr* se1 = toSymExpr(call->get(1))) { if (SymExpr* se2 = toSymExpr(call->get(2))) { if (se1->var == se2->var) { call->remove(); } } } } } } compute_sym_uses(fn); change = false; forv_Vec(DefExpr, def, defs) { ClassType* ct = toClassType(def->sym->type); if (ct->symbol->hasPragma("iterator class")) { change |= unifyClassInstances(def->sym); } } // // NOTE - reenable scalar replacement // forv_Vec(DefExpr, def, defs) { ClassType* ct = toClassType(def->sym->type); if (ct->symbol->hasPragma("iterator class")) { change |= scalarReplaceClassVars(ct, def->sym); } else if (ct->symbol->hasPragma("tuple")) { change |= scalarReplaceRecordVars(ct, def->sym); } } } } // // eliminates a record type with a single field // static void scalarReplaceArrayDomainWrapper(ClassType* ct) { ct->symbol->defPoint->remove(); ct->refType->symbol->defPoint->remove(); Symbol* field = ct->getField("_value"); ClassType* fct = toClassType(field->type); // // update substitution map back pointers // important for ddata for which this substitution is looked at later // forv_Vec(TypeSymbol, ts, gTypes) { form_Map(ASTMapElem, e, ts->type->substitutions) { if (e->value == ct) e->value = fct; } } forv_Vec(BaseAST, ast, gAsts) { if (CallExpr* call = toCallExpr(ast)) { if (call->parentSymbol) { if (call->isPrimitive(PRIMITIVE_CHPL_ALLOC)) { CallExpr* parent = toCallExpr(call->parentExpr); if (parent && parent->isPrimitive(PRIMITIVE_SET_HEAPVAR)) { if (call->typeInfo() == ct) call->get(1)->replace(new SymExpr(fct->symbol)); } else if (call->typeInfo() == ct) call->getStmtExpr()->remove(); else if (call->typeInfo() == ct->refType) call->getStmtExpr()->remove(); } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER)) { if (call->get(2)->typeInfo() == fct && (call->get(1)->typeInfo() == ct || call->get(1)->typeInfo() == ct->refType)) call->replace(call->get(1)->remove()); } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) { if (call->get(2)->typeInfo() == fct) { if (call->get(1)->typeInfo() == ct->refType) call->replace(new CallExpr(PRIMITIVE_GET_REF, call->get(1)->remove())); else if (call->get(1)->typeInfo() == ct) call->replace(call->get(1)->remove()); } else if (call->get(1)->typeInfo() == ct->refType || call->get(1)->typeInfo() == ct) { SymExpr* se = toSymExpr(call->get(2)); INT_ASSERT(se); Symbol* newField = fct->getField(se->var->name); call->get(2)->replace(new SymExpr(newField)); } } else if (call->isPrimitive(PRIMITIVE_SET_MEMBER)) { if (call->get(1)->typeInfo() == ct || call->get(1)->typeInfo() == ct->refType) { Expr* rhs = call->get(3)->remove(); Expr* lhs = call->get(1)->remove(); call->replace(new CallExpr(PRIMITIVE_MOVE, lhs, rhs)); } } } } } forv_Vec(BaseAST, ast, gAsts) { if (DefExpr* def = toDefExpr(ast)) { if (def->parentSymbol) { if (def->sym->type == ct) { def->sym->type = fct; } else if (def->sym->type == ct->refType) { if (fct->refType) def->sym->type = fct->refType; else def->sym->type = fct; } if (FnSymbol* fn = toFnSymbol(def->sym)) { if (fn->retType == ct) { fn->retType = fct; } else if (fn->retType == ct->refType) { if (fct->refType) fn->retType = fct->refType; else fn->retType = fct; } } } } } } void scalarReplace() { if (fBaseline) return; if (!fNoScalarReplacement) { forv_Vec(FnSymbol, fn, gFns) { scalarReplaceVars(fn); } } if (!fNoScalarReplaceArrayWrappers) { forv_Vec(TypeSymbol, ts, gTypes) { if (ts->hasPragma("domain") || ts->hasPragma("array")) { scalarReplaceArrayDomainWrapper(toClassType(ts->type)); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cloneable.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-05-07 16:08:52 $ * * 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 FORMS_COMPONENT_CLONEABLE_HXX #define FORMS_COMPONENT_CLONEABLE_HXX #ifndef _COM_SUN_STAR_UNO_XAGGREGATION_HPP_ #include <com/sun/star/uno/XAggregation.hpp> #endif //......................................................................... namespace frm { //......................................................................... //==================================================================== //= OCloneableAggregation //==================================================================== class OCloneableAggregation { protected: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation> m_xAggregate; protected: static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > createAggregateClone( const OCloneableAggregation* _pOriginal ); }; //......................................................................... } // namespace frm //......................................................................... #endif // FORMS_COMPONENT_CLONEABLE_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.146); FILE MERGED 2005/09/05 13:50:35 rt 1.2.146.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cloneable.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:55:09 $ * * 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 FORMS_COMPONENT_CLONEABLE_HXX #define FORMS_COMPONENT_CLONEABLE_HXX #ifndef _COM_SUN_STAR_UNO_XAGGREGATION_HPP_ #include <com/sun/star/uno/XAggregation.hpp> #endif //......................................................................... namespace frm { //......................................................................... //==================================================================== //= OCloneableAggregation //==================================================================== class OCloneableAggregation { protected: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation> m_xAggregate; protected: static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > createAggregateClone( const OCloneableAggregation* _pOriginal ); }; //......................................................................... } // namespace frm //......................................................................... #endif // FORMS_COMPONENT_CLONEABLE_HXX <|endoftext|>
<commit_before>#include "CheatEngineParser.h" #include <iomanip> #include <sstream> #include <string> #include "../DolphinProcess/DolphinAccessor.h" #include "../GUI/GUICommon.h" CheatEngineParser::CheatEngineParser() { m_xmlReader = new QXmlStreamReader(); } CheatEngineParser::~CheatEngineParser() { delete m_xmlReader; } QString CheatEngineParser::getErrorMessages() const { return m_errorMessages; } bool CheatEngineParser::hasACriticalErrorOccured() const { return m_criticalErrorOccured; } void CheatEngineParser::setTableStartAddress(const u64 tableStartAddress) { m_tableStartAddress = tableStartAddress; } MemWatchTreeNode* CheatEngineParser::parseCTFile(QIODevice* CTFileIODevice, const bool useDolphinPointer) { m_xmlReader->setDevice(CTFileIODevice); if (m_xmlReader->readNextStartElement()) { std::string test = m_xmlReader->name().toString().toStdString(); if (m_xmlReader->name() == QString("CheatTable")) { MemWatchTreeNode* rootNode = new MemWatchTreeNode(nullptr); parseCheatTable(rootNode, useDolphinPointer); if (m_xmlReader->hasError()) { m_errorMessages = m_xmlReader->errorString(); m_criticalErrorOccured = true; return nullptr; } else if (!m_errorMessages.isEmpty()) { if (m_errorMessages.endsWith("\n\n")) m_errorMessages.remove(m_errorMessages.length() - 2, 2); } return rootNode; } } m_errorMessages = "The file provided is not a valid CT file"; m_criticalErrorOccured = true; return nullptr; } MemWatchTreeNode* CheatEngineParser::parseCheatTable(MemWatchTreeNode* rootNode, const bool useDolphinPointer) { while (!(m_xmlReader->isEndElement() && m_xmlReader->name() == QString("CheatTable"))) { if (m_xmlReader->readNextStartElement()) { std::string test = m_xmlReader->name().toString().toStdString(); if (m_xmlReader->name() == QString("CheatEntries")) parseCheatEntries(rootNode, useDolphinPointer); } if (m_xmlReader->hasError()) { m_criticalErrorOccured = true; break; } } if (m_criticalErrorOccured) return nullptr; return rootNode; } MemWatchTreeNode* CheatEngineParser::parseCheatEntries(MemWatchTreeNode* node, const bool useDolphinPointer) { while (!(m_xmlReader->isEndElement() && m_xmlReader->name() == QString("CheatEntries"))) { if (m_xmlReader->readNextStartElement()) { std::string test = m_xmlReader->name().toString().toStdString(); if (m_xmlReader->name() == QString("CheatEntry")) parseCheatEntry(node, useDolphinPointer); } if (m_xmlReader->hasError()) { m_criticalErrorOccured = true; break; } } if (m_criticalErrorOccured) return nullptr; return node; } void CheatEngineParser::parseCheatEntry(MemWatchTreeNode* node, const bool useDolphinPointer) { std::string label = "No label"; u32 consoleAddress = Common::MEM1_START; Common::MemType type = Common::MemType::type_byte; Common::MemBase base = Common::MemBase::base_decimal; bool isUnsigned = true; size_t length = 1; bool isGroup = false; cheatEntryParsingState currentCheatEntryState; currentCheatEntryState.lineNumber = m_xmlReader->lineNumber(); while (!(m_xmlReader->isEndElement() && m_xmlReader->name() == QString("CheatEntry"))) { if (m_xmlReader->readNextStartElement()) { if (m_xmlReader->name() == QString("Description")) { currentCheatEntryState.labelFound = true; label = m_xmlReader->readElementText().toStdString(); if (label.at(0) == '"') label.erase(0, 1); if (label.at(label.length() - 1) == '"') label.erase(label.length() - 1, 1); } else if (m_xmlReader->name() == QString("VariableType")) { std::string strVarType = m_xmlReader->readElementText().toStdString(); if (strVarType == "Custom") { continue; } else { currentCheatEntryState.typeFound = true; if (strVarType == "Byte" || strVarType == "Binary") type = Common::MemType::type_byte; else if (strVarType == "String") type = Common::MemType::type_string; else if (strVarType == "Array of byte") type = Common::MemType::type_byteArray; else currentCheatEntryState.validType = false; } } else if (m_xmlReader->name() == QString("CustomType")) { currentCheatEntryState.typeFound = true; std::string strVarType = m_xmlReader->readElementText().toStdString(); if (strVarType == "2 Byte Big Endian") type = Common::MemType::type_halfword; else if (strVarType == "4 Byte Big Endian") type = Common::MemType::type_word; else if (strVarType == "Float Big Endian") type = Common::MemType::type_float; else currentCheatEntryState.validType = false; } else if (m_xmlReader->name() == QString("Length") || m_xmlReader->name() == QString("ByteLength")) { currentCheatEntryState.lengthForStrFound = true; std::string strLength = m_xmlReader->readElementText().toStdString(); std::stringstream ss(strLength); size_t lengthCandiate = 0; ss >> lengthCandiate; if (ss.fail() || lengthCandiate == 0) currentCheatEntryState.validLengthForStr = false; else length = lengthCandiate; } else if (m_xmlReader->name() == QString("Address")) { if (useDolphinPointer) { m_xmlReader->skipCurrentElement(); } else { currentCheatEntryState.consoleAddressFound = true; u64 consoleAddressCandidate = 0; std::string strCEAddress = m_xmlReader->readElementText().toStdString(); std::stringstream ss(strCEAddress); ss >> std::hex; ss >> consoleAddressCandidate; if (ss.fail()) { currentCheatEntryState.validConsoleAddressHex = false; } else { consoleAddressCandidate -= m_tableStartAddress; consoleAddressCandidate += Common::MEM1_START; if (DolphinComm::DolphinAccessor::isValidConsoleAddress(consoleAddressCandidate)) consoleAddress = consoleAddressCandidate; else currentCheatEntryState.validConsoleAddress = false; } } } else if (m_xmlReader->name() == QString("Offsets")) { if (useDolphinPointer) { if (m_xmlReader->readNextStartElement()) { if (m_xmlReader->name() == QString("Offset")) { currentCheatEntryState.consoleAddressFound = true; u32 consoleAddressCandidate = 0; std::string strOffset = m_xmlReader->readElementText().toStdString(); std::stringstream ss(strOffset); ss >> std::hex; ss >> consoleAddressCandidate; if (ss.fail()) { currentCheatEntryState.validConsoleAddressHex = false; } else { consoleAddressCandidate += Common::MEM1_START; if (DolphinComm::DolphinAccessor::isValidConsoleAddress(consoleAddressCandidate)) consoleAddress = consoleAddressCandidate; else currentCheatEntryState.validConsoleAddress = false; } } } } else { m_xmlReader->skipCurrentElement(); } } else if (m_xmlReader->name() == QString("ShowAsHex")) { if (m_xmlReader->readElementText().toStdString() == "1") base = Common::MemBase::base_hexadecimal; } else if (m_xmlReader->name() == QString("ShowAsBinary")) { if (m_xmlReader->readElementText().toStdString() == "1") base = Common::MemBase::base_binary; } else if (m_xmlReader->name() == QString("ShowAsSigned")) { if (m_xmlReader->readElementText().toStdString() == "1") isUnsigned = false; } else if (m_xmlReader->name() == QString("CheatEntries")) { isGroup = true; MemWatchTreeNode* newNode = new MemWatchTreeNode(nullptr, node, true, QString::fromStdString(label)); node->appendChild(newNode); parseCheatEntries(newNode, useDolphinPointer); } else { m_xmlReader->skipCurrentElement(); } } if (m_xmlReader->hasError()) { m_criticalErrorOccured = true; break; } } if (m_criticalErrorOccured) return; if (!isGroup) { MemWatchEntry* entry = new MemWatchEntry(QString::fromStdString(label), consoleAddress, type, base, isUnsigned, length, false); MemWatchTreeNode* newNode = new MemWatchTreeNode(entry, node, false, ""); node->appendChild(newNode); verifyCheatEntryParsingErrors(currentCheatEntryState, entry, false, useDolphinPointer); } else { verifyCheatEntryParsingErrors(currentCheatEntryState, nullptr, true, useDolphinPointer); } } void CheatEngineParser::verifyCheatEntryParsingErrors(cheatEntryParsingState state, MemWatchEntry* entry, bool isGroup, const bool useDolphinPointer) { QString stateErrors = ""; QString consoleAddressFieldImport = useDolphinPointer ? "Dolphin pointer offset" : "Cheat Engine address"; if (!state.labelFound) stateErrors += "No description was found\n"; if (isGroup) { if (!stateErrors.isEmpty()) { stateErrors = "No description was found while importing the Cheat Entry located at line " + QString::number(state.lineNumber) + " of the CT file as group, the label \"No label\" was imported instead\n\n"; m_errorMessages += stateErrors; } } else { if (!state.typeFound) { stateErrors += "No type was found\n"; } else if (!state.validType) { stateErrors += "A type wa found, but was invalid\n"; } else if (entry->getType() == Common::MemType::type_string) { if (!state.lengthForStrFound) stateErrors += "No length for the String type was found\n"; else if (!state.validLengthForStr) stateErrors += "A length for the String type was found, but was invalid\n"; } if (!state.consoleAddressFound) stateErrors += "No " + consoleAddressFieldImport + " was found\n"; else if (!state.validConsoleAddressHex) stateErrors += "An " + consoleAddressFieldImport + " was found, but was not a valid hexadcimal number\n"; else if (!state.validConsoleAddress) stateErrors += "A valid " + consoleAddressFieldImport + " was found, but lead to an invalid console address\n"; if (!stateErrors.isEmpty()) { stateErrors.prepend( "The following error(s) occured while importing the Cheat Entry located at line " + QString::number(state.lineNumber) + " of the CT file as watch entry:\n\n"); stateErrors += "\nThe following informations were imported instead to accomodate for this/these " "error(s):\n\n"; stateErrors += formatImportedEntryBasicInfo(entry); stateErrors += "\n\n"; m_errorMessages += stateErrors; } } } QString CheatEngineParser::formatImportedEntryBasicInfo(const MemWatchEntry* entry) const { QString formatedEntry = ""; formatedEntry += "Label: " + entry->getLabel() + "\n"; formatedEntry += "Type: " + GUICommon::getStringFromType(entry->getType(), entry->getLength()) + "\n"; std::stringstream ss; ss << std::hex << std::uppercase << entry->getConsoleAddress(); formatedEntry += "Address: " + QString::fromStdString(ss.str()); return formatedEntry; } <commit_msg>CTParser: fix typo in error message<commit_after>#include "CheatEngineParser.h" #include <iomanip> #include <sstream> #include <string> #include "../DolphinProcess/DolphinAccessor.h" #include "../GUI/GUICommon.h" CheatEngineParser::CheatEngineParser() { m_xmlReader = new QXmlStreamReader(); } CheatEngineParser::~CheatEngineParser() { delete m_xmlReader; } QString CheatEngineParser::getErrorMessages() const { return m_errorMessages; } bool CheatEngineParser::hasACriticalErrorOccured() const { return m_criticalErrorOccured; } void CheatEngineParser::setTableStartAddress(const u64 tableStartAddress) { m_tableStartAddress = tableStartAddress; } MemWatchTreeNode* CheatEngineParser::parseCTFile(QIODevice* CTFileIODevice, const bool useDolphinPointer) { m_xmlReader->setDevice(CTFileIODevice); if (m_xmlReader->readNextStartElement()) { std::string test = m_xmlReader->name().toString().toStdString(); if (m_xmlReader->name() == QString("CheatTable")) { MemWatchTreeNode* rootNode = new MemWatchTreeNode(nullptr); parseCheatTable(rootNode, useDolphinPointer); if (m_xmlReader->hasError()) { m_errorMessages = m_xmlReader->errorString(); m_criticalErrorOccured = true; return nullptr; } else if (!m_errorMessages.isEmpty()) { if (m_errorMessages.endsWith("\n\n")) m_errorMessages.remove(m_errorMessages.length() - 2, 2); } return rootNode; } } m_errorMessages = "The file provided is not a valid CT file"; m_criticalErrorOccured = true; return nullptr; } MemWatchTreeNode* CheatEngineParser::parseCheatTable(MemWatchTreeNode* rootNode, const bool useDolphinPointer) { while (!(m_xmlReader->isEndElement() && m_xmlReader->name() == QString("CheatTable"))) { if (m_xmlReader->readNextStartElement()) { std::string test = m_xmlReader->name().toString().toStdString(); if (m_xmlReader->name() == QString("CheatEntries")) parseCheatEntries(rootNode, useDolphinPointer); } if (m_xmlReader->hasError()) { m_criticalErrorOccured = true; break; } } if (m_criticalErrorOccured) return nullptr; return rootNode; } MemWatchTreeNode* CheatEngineParser::parseCheatEntries(MemWatchTreeNode* node, const bool useDolphinPointer) { while (!(m_xmlReader->isEndElement() && m_xmlReader->name() == QString("CheatEntries"))) { if (m_xmlReader->readNextStartElement()) { std::string test = m_xmlReader->name().toString().toStdString(); if (m_xmlReader->name() == QString("CheatEntry")) parseCheatEntry(node, useDolphinPointer); } if (m_xmlReader->hasError()) { m_criticalErrorOccured = true; break; } } if (m_criticalErrorOccured) return nullptr; return node; } void CheatEngineParser::parseCheatEntry(MemWatchTreeNode* node, const bool useDolphinPointer) { std::string label = "No label"; u32 consoleAddress = Common::MEM1_START; Common::MemType type = Common::MemType::type_byte; Common::MemBase base = Common::MemBase::base_decimal; bool isUnsigned = true; size_t length = 1; bool isGroup = false; cheatEntryParsingState currentCheatEntryState; currentCheatEntryState.lineNumber = m_xmlReader->lineNumber(); while (!(m_xmlReader->isEndElement() && m_xmlReader->name() == QString("CheatEntry"))) { if (m_xmlReader->readNextStartElement()) { if (m_xmlReader->name() == QString("Description")) { currentCheatEntryState.labelFound = true; label = m_xmlReader->readElementText().toStdString(); if (label.at(0) == '"') label.erase(0, 1); if (label.at(label.length() - 1) == '"') label.erase(label.length() - 1, 1); } else if (m_xmlReader->name() == QString("VariableType")) { std::string strVarType = m_xmlReader->readElementText().toStdString(); if (strVarType == "Custom") { continue; } else { currentCheatEntryState.typeFound = true; if (strVarType == "Byte" || strVarType == "Binary") type = Common::MemType::type_byte; else if (strVarType == "String") type = Common::MemType::type_string; else if (strVarType == "Array of byte") type = Common::MemType::type_byteArray; else currentCheatEntryState.validType = false; } } else if (m_xmlReader->name() == QString("CustomType")) { currentCheatEntryState.typeFound = true; std::string strVarType = m_xmlReader->readElementText().toStdString(); if (strVarType == "2 Byte Big Endian") type = Common::MemType::type_halfword; else if (strVarType == "4 Byte Big Endian") type = Common::MemType::type_word; else if (strVarType == "Float Big Endian") type = Common::MemType::type_float; else currentCheatEntryState.validType = false; } else if (m_xmlReader->name() == QString("Length") || m_xmlReader->name() == QString("ByteLength")) { currentCheatEntryState.lengthForStrFound = true; std::string strLength = m_xmlReader->readElementText().toStdString(); std::stringstream ss(strLength); size_t lengthCandiate = 0; ss >> lengthCandiate; if (ss.fail() || lengthCandiate == 0) currentCheatEntryState.validLengthForStr = false; else length = lengthCandiate; } else if (m_xmlReader->name() == QString("Address")) { if (useDolphinPointer) { m_xmlReader->skipCurrentElement(); } else { currentCheatEntryState.consoleAddressFound = true; u64 consoleAddressCandidate = 0; std::string strCEAddress = m_xmlReader->readElementText().toStdString(); std::stringstream ss(strCEAddress); ss >> std::hex; ss >> consoleAddressCandidate; if (ss.fail()) { currentCheatEntryState.validConsoleAddressHex = false; } else { consoleAddressCandidate -= m_tableStartAddress; consoleAddressCandidate += Common::MEM1_START; if (DolphinComm::DolphinAccessor::isValidConsoleAddress(consoleAddressCandidate)) consoleAddress = consoleAddressCandidate; else currentCheatEntryState.validConsoleAddress = false; } } } else if (m_xmlReader->name() == QString("Offsets")) { if (useDolphinPointer) { if (m_xmlReader->readNextStartElement()) { if (m_xmlReader->name() == QString("Offset")) { currentCheatEntryState.consoleAddressFound = true; u32 consoleAddressCandidate = 0; std::string strOffset = m_xmlReader->readElementText().toStdString(); std::stringstream ss(strOffset); ss >> std::hex; ss >> consoleAddressCandidate; if (ss.fail()) { currentCheatEntryState.validConsoleAddressHex = false; } else { consoleAddressCandidate += Common::MEM1_START; if (DolphinComm::DolphinAccessor::isValidConsoleAddress(consoleAddressCandidate)) consoleAddress = consoleAddressCandidate; else currentCheatEntryState.validConsoleAddress = false; } } } } else { m_xmlReader->skipCurrentElement(); } } else if (m_xmlReader->name() == QString("ShowAsHex")) { if (m_xmlReader->readElementText().toStdString() == "1") base = Common::MemBase::base_hexadecimal; } else if (m_xmlReader->name() == QString("ShowAsBinary")) { if (m_xmlReader->readElementText().toStdString() == "1") base = Common::MemBase::base_binary; } else if (m_xmlReader->name() == QString("ShowAsSigned")) { if (m_xmlReader->readElementText().toStdString() == "1") isUnsigned = false; } else if (m_xmlReader->name() == QString("CheatEntries")) { isGroup = true; MemWatchTreeNode* newNode = new MemWatchTreeNode(nullptr, node, true, QString::fromStdString(label)); node->appendChild(newNode); parseCheatEntries(newNode, useDolphinPointer); } else { m_xmlReader->skipCurrentElement(); } } if (m_xmlReader->hasError()) { m_criticalErrorOccured = true; break; } } if (m_criticalErrorOccured) return; if (!isGroup) { MemWatchEntry* entry = new MemWatchEntry(QString::fromStdString(label), consoleAddress, type, base, isUnsigned, length, false); MemWatchTreeNode* newNode = new MemWatchTreeNode(entry, node, false, ""); node->appendChild(newNode); verifyCheatEntryParsingErrors(currentCheatEntryState, entry, false, useDolphinPointer); } else { verifyCheatEntryParsingErrors(currentCheatEntryState, nullptr, true, useDolphinPointer); } } void CheatEngineParser::verifyCheatEntryParsingErrors(cheatEntryParsingState state, MemWatchEntry* entry, bool isGroup, const bool useDolphinPointer) { QString stateErrors = ""; QString consoleAddressFieldImport = useDolphinPointer ? "Dolphin pointer offset" : "Cheat Engine address"; if (!state.labelFound) stateErrors += "No description was found\n"; if (isGroup) { if (!stateErrors.isEmpty()) { stateErrors = "No description was found while importing the Cheat Entry located at line " + QString::number(state.lineNumber) + " of the CT file as group, the label \"No label\" was imported instead\n\n"; m_errorMessages += stateErrors; } } else { if (!state.typeFound) { stateErrors += "No type was found\n"; } else if (!state.validType) { stateErrors += "A type was found, but was invalid\n"; } else if (entry->getType() == Common::MemType::type_string) { if (!state.lengthForStrFound) stateErrors += "No length for the String type was found\n"; else if (!state.validLengthForStr) stateErrors += "A length for the String type was found, but was invalid\n"; } if (!state.consoleAddressFound) stateErrors += "No " + consoleAddressFieldImport + " was found\n"; else if (!state.validConsoleAddressHex) stateErrors += "An " + consoleAddressFieldImport + " was found, but was not a valid hexadcimal number\n"; else if (!state.validConsoleAddress) stateErrors += "A valid " + consoleAddressFieldImport + " was found, but lead to an invalid console address\n"; if (!stateErrors.isEmpty()) { stateErrors.prepend( "The following error(s) occured while importing the Cheat Entry located at line " + QString::number(state.lineNumber) + " of the CT file as watch entry:\n\n"); stateErrors += "\nThe following informations were imported instead to accomodate for this/these " "error(s):\n\n"; stateErrors += formatImportedEntryBasicInfo(entry); stateErrors += "\n\n"; m_errorMessages += stateErrors; } } } QString CheatEngineParser::formatImportedEntryBasicInfo(const MemWatchEntry* entry) const { QString formatedEntry = ""; formatedEntry += "Label: " + entry->getLabel() + "\n"; formatedEntry += "Type: " + GUICommon::getStringFromType(entry->getType(), entry->getLength()) + "\n"; std::stringstream ss; ss << std::hex << std::uppercase << entry->getConsoleAddress(); formatedEntry += "Address: " + QString::fromStdString(ss.str()); return formatedEntry; } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * 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 "config.h" #include "RenderCombineText.h" #include "TextRun.h" namespace WebCore { const float textCombineMargin = 1.1; // Allow em + 10% margin RenderCombineText::RenderCombineText(Node* node, PassRefPtr<StringImpl> string) : RenderText(node, string) , m_combinedTextWidth(0) , m_isCombined(false) , m_needsFontUpdate(false) { } void RenderCombineText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderText::styleDidChange(diff, oldStyle); if (m_isCombined) RenderText::setTextInternal(originalText()); // This RenderCombineText has been combined once. Restore the original text for the next combineText(). m_needsFontUpdate = true; } void RenderCombineText::setTextInternal(PassRefPtr<StringImpl> text) { RenderText::setTextInternal(text); m_needsFontUpdate = true; } unsigned RenderCombineText::width(unsigned from, unsigned length, const Font& font, int xPosition, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const { if (!characters()) return 0; if (m_isCombined) return font.size(); return RenderText::width(from, length, font, xPosition, fallbackFonts, glyphOverflow); } void RenderCombineText::adjustTextOrigin(IntPoint& textOrigin, const IntRect& boxRect) const { if (m_isCombined) textOrigin.move(boxRect.height() / 2 - ceilf(m_combinedTextWidth) / 2, style()->font().pixelSize()); } void RenderCombineText::charactersToRender(int start, const UChar*& characters, int& length) const { if (m_isCombined) { length = originalText()->length(); characters = originalText()->characters(); return; } characters = text()->characters() + start; } void RenderCombineText::combineText() { if (!m_needsFontUpdate) return; m_isCombined = false; m_needsFontUpdate = false; // CSS3 spec says text-combine works only in vertical writing mode. if (style()->isHorizontalWritingMode()) return; TextRun run = TextRun(String(text())); float emWidth = style()->font().fontDescription().computedSize() * textCombineMargin; m_combinedTextWidth = style()->font().floatWidth(run); m_isCombined = m_combinedTextWidth <= emWidth; if (!m_isCombined) { // Need to try compressed glyphs. static const FontWidthVariant widthVariants[] = { HalfWidth, ThirdWidth, QuarterWidth }; FontDescription compressedFontDescription = style()->font().fontDescription(); for (size_t i = 0 ; i < WTF_ARRAY_LENGTH(widthVariants) ; ++i) { compressedFontDescription.setWidthVariant(widthVariants[i]); Font compressedFont = Font(compressedFontDescription, style()->font().letterSpacing(), style()->font().wordSpacing()); compressedFont.update(style()->font().fontSelector()); float runWidth = compressedFont.floatWidth(run); if (runWidth <= emWidth) { m_combinedTextWidth = runWidth; m_isCombined = true; // Replace my font with the new one. if (style()->setFontDescription(compressedFontDescription)) style()->font().update(style()->font().fontSelector()); break; } } } if (m_isCombined) { static const UChar newCharacter = objectReplacementCharacter; DEFINE_STATIC_LOCAL(String, objectReplacementCharacterString, (&newCharacter, 1)); RenderText::setTextInternal(objectReplacementCharacterString.impl()); } } } // namespace WebCore <commit_msg>Fix 32-bit build bustage.<commit_after>/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * 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 "config.h" #include "RenderCombineText.h" #include "TextRun.h" namespace WebCore { const float textCombineMargin = 1.1f; // Allow em + 10% margin RenderCombineText::RenderCombineText(Node* node, PassRefPtr<StringImpl> string) : RenderText(node, string) , m_combinedTextWidth(0) , m_isCombined(false) , m_needsFontUpdate(false) { } void RenderCombineText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { RenderText::styleDidChange(diff, oldStyle); if (m_isCombined) RenderText::setTextInternal(originalText()); // This RenderCombineText has been combined once. Restore the original text for the next combineText(). m_needsFontUpdate = true; } void RenderCombineText::setTextInternal(PassRefPtr<StringImpl> text) { RenderText::setTextInternal(text); m_needsFontUpdate = true; } unsigned RenderCombineText::width(unsigned from, unsigned length, const Font& font, int xPosition, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const { if (!characters()) return 0; if (m_isCombined) return font.size(); return RenderText::width(from, length, font, xPosition, fallbackFonts, glyphOverflow); } void RenderCombineText::adjustTextOrigin(IntPoint& textOrigin, const IntRect& boxRect) const { if (m_isCombined) textOrigin.move(boxRect.height() / 2 - ceilf(m_combinedTextWidth) / 2, style()->font().pixelSize()); } void RenderCombineText::charactersToRender(int start, const UChar*& characters, int& length) const { if (m_isCombined) { length = originalText()->length(); characters = originalText()->characters(); return; } characters = text()->characters() + start; } void RenderCombineText::combineText() { if (!m_needsFontUpdate) return; m_isCombined = false; m_needsFontUpdate = false; // CSS3 spec says text-combine works only in vertical writing mode. if (style()->isHorizontalWritingMode()) return; TextRun run = TextRun(String(text())); float emWidth = style()->font().fontDescription().computedSize() * textCombineMargin; m_combinedTextWidth = style()->font().floatWidth(run); m_isCombined = m_combinedTextWidth <= emWidth; if (!m_isCombined) { // Need to try compressed glyphs. static const FontWidthVariant widthVariants[] = { HalfWidth, ThirdWidth, QuarterWidth }; FontDescription compressedFontDescription = style()->font().fontDescription(); for (size_t i = 0 ; i < WTF_ARRAY_LENGTH(widthVariants) ; ++i) { compressedFontDescription.setWidthVariant(widthVariants[i]); Font compressedFont = Font(compressedFontDescription, style()->font().letterSpacing(), style()->font().wordSpacing()); compressedFont.update(style()->font().fontSelector()); float runWidth = compressedFont.floatWidth(run); if (runWidth <= emWidth) { m_combinedTextWidth = runWidth; m_isCombined = true; // Replace my font with the new one. if (style()->setFontDescription(compressedFontDescription)) style()->font().update(style()->font().fontSelector()); break; } } } if (m_isCombined) { static const UChar newCharacter = objectReplacementCharacter; DEFINE_STATIC_LOCAL(String, objectReplacementCharacterString, (&newCharacter, 1)); RenderText::setTextInternal(objectReplacementCharacterString.impl()); } } } // namespace WebCore <|endoftext|>
<commit_before>/**************************************************************************/ /** ** C H I L D ** ** CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL ** ** OXFORD VERSION 2003 ** ** Designed and created by Gregory E. Tucker, Stephen T. Lancaster, ** Nicole M. Gasparini, and Rafael L. Bras ** ** ** @file childmain.cpp ** @brief This file contains the main() routine that handles ** top-level initialization and implements the main ** time-loop. ** ** NOTE: This source code is copyrighted material. It is distributed ** solely for noncommercial research and educational purposes ** only. Use in whole or in part for commercial purposes without ** a written license from the copyright holder(s) is expressly ** prohibited. Copies of this source code or any of its components ** may not be transferred to any other individuals or organizations ** without written consent. Copyright (C) Massachusetts Institute ** of Technology, 1997-2000. All rights reserved. ** ** For information regarding this program, please contact Greg Tucker at: ** ** School of Geography and the Environment ** University of Oxford ** Mansfield Road ** Oxford OX1 3TB United Kingdom ** ** $Id: childmain.cpp,v 1.16 2004-01-07 15:10:15 childcvs Exp $ */ /**************************************************************************/ /* set traps for some floating point exceptions on Linux */ #include "trapfpe.h" #include "Inclusions.h" #include "tFloodplain/tFloodplain.h" #include "tEolian/tEolian.h" Predicates predicate; int main( int argc, char **argv ) { bool silent_mode; // Option for silent mode (no time output to stdout) int optDetachLim, // Option for detachment-limited erosion only optFloodplainDep, // Option for floodplain (overbank) deposition optLoessDep, // Option for eolian deposition optVegetation=0, // Option for dynamic vegetation cover optMeander, // Option for stream meandering optDiffuseDepo; // Option for deposition / no deposition by diff'n tVegetation *vegetation(0); // -> vegetation object tFloodplain *floodplain(0); // -> floodplain object tEolian *loess(0); // -> eolian deposition object tStreamMeander *strmMeander(0); // -> stream meander object /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments if( argc<2 ) { cerr << "Usage: " << argv[0] << " <input file>" << endl; ReportFatalError( "You need to give the name of an input file." ); } // Check whether we're in silent mode silent_mode = BOOL( argc>2 && argv[2][1]=='s' ); // Say hello cout << "\nThis is CHILD, version " << VERSION << " (compiled " __DATE__ " " __TIME__ ")" << endl << endl; // Open main input file tInputFile inputFile( argv[1] ); // Create a random number generator for the simulation itself tRand rand( inputFile ); // Create and initialize objects: cout << "Creating mesh...\n"; tMesh<tLNode> mesh( inputFile ); cout << "Creating output files...\n"; tLOutput<tLNode> output( &mesh, inputFile, &rand ); tStorm storm( inputFile, &rand ); cout << "Creating stream network...\n"; tStreamNet strmNet( mesh, storm, inputFile ); tErosion erosion( &mesh, inputFile ); tUplift uplift( inputFile ); // Get various options optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" ); optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" ); optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" ); optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" ); optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" ); optMeander = inputFile.ReadItem( optMeander, "OPTMEANDER" ); // If applicable, create Vegetation object if( optVegetation ) vegetation = new tVegetation( &mesh, inputFile ); // If applicable, create floodplain object if( optFloodplainDep ) floodplain = new tFloodplain( inputFile, &mesh ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // If applicable, create Stream Meander object if( optMeander ) strmMeander = new tStreamMeander( strmNet, mesh, inputFile, &rand ); cout << "Writing data for time zero...\n"; tRunTimer time( inputFile, BOOL(!silent_mode) ); output.WriteOutput( 0. ); cout << "Initialization done.\n"; // Option for time series output (IN PROGRESS) /* switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. cout << "here" << endl; if( time.CheckTSOutputTime() ){ cout << "there" << endl; output.WriteVolVegOutput();} break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." ); } */ /**************** MAIN LOOP ******************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Meandering (if applicable) ** Floodplain deposition (if applicable) ** Do interstorm... ** Hillslope transport ** Vegetation (if applicable) ** Exposure history ** Mesh densification (if applicable) ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ while( !time.IsFinished() ) { time.ReportTimeStatus(); // Do storm... storm.GenerateStorm( time.getCurrentTime(), strmNet.getInfilt(), strmNet.getSoilStore() ); /*cout << "Storm: " << storm.getRainrate() << " " << storm.getStormDuration() << " " << storm.interstormDur() << endl;*/ strmNet.UpdateNet( time.getCurrentTime(), storm ); if( optDetachLim ) erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet, vegetation ); else erosion.DetachErode( storm.getStormDuration(), &strmNet, time.getCurrentTime(), vegetation ); if( optMeander ) strmMeander->Migrate( time.getCurrentTime() ); if( optFloodplainDep ) { if( floodplain->OptControlMainChan() ) floodplain->UpdateMainChannelHeight( time.getCurrentTime(), strmNet.getInletNodePtr() ); floodplain->DepositOverbank( storm.getRainrate(), storm.getStormDuration(), time.getCurrentTime() ); } #define NEWVEG 1 if( optVegetation ) { if( NEWVEG ) vegetation->GrowVegetation( &mesh, storm.interstormDur() ); else vegetation->UpdateVegetation( &mesh, storm.getStormDuration(), storm.interstormDur() ); } #undef NEWVEG // Do interstorm... erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(), optDiffuseDepo ); erosion.UpdateExposureTime( storm.getStormDuration() + storm.interstormDur() ); if( optLoessDep ) loess->DepositLoess( &mesh, storm.getStormDuration()+storm.interstormDur(), time.getCurrentTime() ); if( time.getCurrentTime() < uplift.getDuration() ) uplift.DoUplift( &mesh, storm.getStormDuration() + storm.interstormDur() ); time.Advance( storm.getStormDuration() + storm.interstormDur() ); if( time.CheckOutputTime() ) output.WriteOutput( time.getCurrentTime() ); if( output.OptTSOutput() ) output.WriteTSOutput(); /* IN PROGRESS switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. if( time.CheckTSOutputTime() ) output.WriteVolVegOutput(); break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." */ /*tMeshListIter<tLNode> ni( mesh.getNodeList() ); tLNode *cn; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 ) cn->TellAll(); }*/ } // end of main loop delete vegetation; delete floodplain; delete loess; delete strmMeander; return 0; } <commit_msg>Quintijn Clevis Call the tStratGrid infrastructure.<commit_after>/**************************************************************************/ /** ** C H I L D ** ** CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL ** ** OXFORD VERSION 2003 ** ** Designed and created by Gregory E. Tucker, Stephen T. Lancaster, ** Nicole M. Gasparini, and Rafael L. Bras ** ** ** @file childmain.cpp ** @brief This file contains the main() routine that handles ** top-level initialization and implements the main ** time-loop. ** ** NOTE: This source code is copyrighted material. It is distributed ** solely for noncommercial research and educational purposes ** only. Use in whole or in part for commercial purposes without ** a written license from the copyright holder(s) is expressly ** prohibited. Copies of this source code or any of its components ** may not be transferred to any other individuals or organizations ** without written consent. Copyright (C) Massachusetts Institute ** of Technology, 1997-2000. All rights reserved. ** ** For information regarding this program, please contact Greg Tucker at: ** ** School of Geography and the Environment ** University of Oxford ** Mansfield Road ** Oxford OX1 3TB United Kingdom ** ** $Id: childmain.cpp,v 1.17 2004-03-05 17:12:33 childcvs Exp $ */ /**************************************************************************/ /* set traps for some floating point exceptions on Linux */ #include "trapfpe.h" #include "Inclusions.h" #include "tFloodplain/tFloodplain.h" #include "tStratGrid/tStratGrid.h" #include "tEolian/tEolian.h" Predicates predicate; int main( int argc, char **argv ) { bool silent_mode; // Option for silent mode (no time output to stdout) int optDetachLim, // Option for detachment-limited erosion only optFloodplainDep, // Option for floodplain (overbank) deposition optLoessDep, // Option for eolian deposition optVegetation=0, // Option for dynamic vegetation cover optMeander, // Option for stream meandering optDiffuseDepo, // Option for deposition / no deposition by diff'n optStratGrid; // Option to enable stratigraphy grid tVegetation *vegetation(0); // -> vegetation object tFloodplain *floodplain(0); // -> floodplain object tStratGrid *stratGrid(0); // -> Stratigraphy Grid object tEolian *loess(0); // -> eolian deposition object tStreamMeander *strmMeander(0); // -> stream meander object /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments if( argc<2 ) { cerr << "Usage: " << argv[0] << " <input file>" << endl; ReportFatalError( "You need to give the name of an input file." ); } // Check whether we're in silent mode silent_mode = BOOL( argc>2 && argv[2][1]=='s' ); // Say hello cout << "\nThis is CHILD, version " << VERSION << " (compiled " __DATE__ " " __TIME__ ")" << endl << endl; // Open main input file tInputFile inputFile( argv[1] ); // Create a random number generator for the simulation itself tRand rand( inputFile ); // Create and initialize objects: cout << "Creating mesh...\n"; tMesh<tLNode> mesh( inputFile ); cout << "Creating output files...\n"; tLOutput<tLNode> output( &mesh, inputFile, &rand ); tStorm storm( inputFile, &rand ); cout << "Creating stream network...\n"; tStreamNet strmNet( mesh, storm, inputFile ); tErosion erosion( &mesh, inputFile ); tUplift uplift( inputFile ); // Get various options optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" ); optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" ); optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" ); optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" ); optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" ); optMeander = inputFile.ReadItem( optMeander, "OPTMEANDER" ); optStratGrid = inputFile.ReadItem( optStratGrid, "OPTSTRATGRID" ,false); // If applicable, create Vegetation object if( optVegetation ) vegetation = new tVegetation( &mesh, inputFile ); // If applicable, create floodplain object if( optFloodplainDep ) floodplain = new tFloodplain( inputFile, &mesh ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // If applicable, create Stream Meander object if( optMeander ) strmMeander = new tStreamMeander( strmNet, mesh, inputFile, &rand ); // If applicable, create Stratigraphy Grid object // and pass it to output if( optStratGrid ) { if (!optFloodplainDep) ReportFatalError("OPTFLOODPLAIN must be enabled."); stratGrid = new tStratGrid (inputFile, &mesh); output.SetStratGrid( stratGrid, &strmNet ); } cout << "Writing data for time zero...\n"; tRunTimer time( inputFile, BOOL(!silent_mode) ); output.WriteOutput( 0. ); cout << "Initialization done.\n"; // Option for time series output (IN PROGRESS) /* switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. cout << "here" << endl; if( time.CheckTSOutputTime() ){ cout << "there" << endl; output.WriteVolVegOutput();} break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." ); } */ /**************** MAIN LOOP ******************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Meandering (if applicable) ** Floodplain deposition (if applicable) ** Do interstorm... ** Hillslope transport ** Vegetation (if applicable) ** Exposure history ** Mesh densification (if applicable) ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ while( !time.IsFinished() ) { cout << " " << endl; time.ReportTimeStatus(); // Do storm... storm.GenerateStorm( time.getCurrentTime(), strmNet.getInfilt(), strmNet.getSoilStore() ); /*cout << "Storm: " << storm.getRainrate() << " " << storm.getStormDuration() << " " << storm.interstormDur() << endl;*/ strmNet.UpdateNet( time.getCurrentTime(), storm ); cout << "UpdateNet::Done.." << endl; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(0, time.getCurrentTime()); if( optDetachLim ) erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet, vegetation ); else erosion.DetachErode( storm.getStormDuration(), &strmNet, time.getCurrentTime(), vegetation ); cout << "Erosion::Done.." << endl; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(1,time.getCurrentTime() ); if( optMeander ) strmMeander->Migrate( time.getCurrentTime() ); cout << "Meander-Migrate::Done..\n"; // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(2,time.getCurrentTime()); //----------------FLOODPLAIN--------------------------------- if( optFloodplainDep ) { if( floodplain->OptControlMainChan() ) floodplain->UpdateMainChannelHeight( time.getCurrentTime(), strmNet.getInletNodePtr() ); cout << "UpdateChannelHeight::Done..\n"; if( optStratGrid ){ stratGrid->UpdateStratGrid(3,time.getCurrentTime()); } floodplain->DepositOverbank( storm.getRainrate(), storm.getStormDuration(), time.getCurrentTime() ); cout << "tFloodplain::Done..\n"; if( optStratGrid ){ stratGrid->UpdateStratGrid(4,time.getCurrentTime()); } } // end of floodplain stuff #define NEWVEG 1 if( optVegetation ) { if( NEWVEG ) vegetation->GrowVegetation( &mesh, storm.interstormDur() ); else vegetation->UpdateVegetation( &mesh, storm.getStormDuration(), storm.interstormDur() ); } #undef NEWVEG // Do interstorm... erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(), optDiffuseDepo ); erosion.UpdateExposureTime( storm.getStormDuration() + storm.interstormDur() ); if( optLoessDep ) loess->DepositLoess( &mesh, storm.getStormDuration()+storm.interstormDur(), time.getCurrentTime() ); if( time.getCurrentTime() < uplift.getDuration() ) uplift.DoUplift( &mesh, storm.getStormDuration() + storm.interstormDur() ); time.Advance( storm.getStormDuration() + storm.interstormDur() ); if( time.CheckOutputTime() ) output.WriteOutput( time.getCurrentTime() ); if( output.OptTSOutput() ) output.WriteTSOutput(); /* IN PROGRESS switch( optTSOutput ){ case 1: // Volume output each N years. if( time.CheckTSOutputTime() ) output.WriteVolOutput(); break; case 2: // Volume and vegetation cover output each N years. if( time.CheckTSOutputTime() ) output.WriteVolVegOutput(); break; case 3: // All data at each storm. output.WriteTSOutput(); break; case 0: // No additional timeseries output. break; default: // Invalid option. ReportFatalError( "The input file contains an invalid value for OptTSOutput." */ /*tMeshListIter<tLNode> ni( mesh.getNodeList() ); tLNode *cn; for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() ) { if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 ) cn->TellAll(); }*/ } // end of main loop delete vegetation; delete floodplain; delete loess; delete strmMeander; delete stratGrid; return 0; } <|endoftext|>
<commit_before>#include "Toast.h" #include "../utils/compiler.h" USING_NS_CC; Toast *Toast::makeText(cocos2d::Scene *scene, const std::string &text, Duration duration) { Toast *ret = new (std::nothrow) Toast(); if (ret != nullptr && ret->initWithText(scene, text, duration)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool Toast::initWithText(cocos2d::Scene *scene, const std::string &text, Duration duration) { if (UNLIKELY(!Node::init())) { return false; } _scene = scene; _duration = duration; const float width = maxWidth(); Label *label = Label::createWithSystemFont(text, "Arail", 12); Size size = label->getContentSize(); if (size.width > width - 8.0f) { label->setHorizontalAlignment(TextHAlignment::CENTER); label->setDimensions(width - 8.0f, 0.0f); size = label->getContentSize(); } size.width += 8.0f; size.height += 8.0f; this->setContentSize(Size(size.width, size.height)); this->addChild(label); label->setPosition(Vec2(size.width * 0.5f, size.height * 0.5f)); this->addChild(LayerColor::create(Color4B(0x60, 0x60, 0x60, 0xFF), size.width, size.height), -1); this->setIgnoreAnchorPointForPosition(false); this->setAnchorPoint(Vec2::ANCHOR_MIDDLE); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); this->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + std::min(visibleSize.height * 0.2f, size.height * 0.5f + 40.0f))); return true; } void Toast::show() { _scene->addChild(this, 100); _scene = nullptr; float dt = _duration == LENGTH_LONG ? 3.5f : 2.0f; this->runAction(Sequence::create(DelayTime::create(dt), FadeOut::create(0.2f), RemoveSelf::create(), NULL)); } <commit_msg>调整Toast效果<commit_after>#include "Toast.h" #include "../utils/compiler.h" USING_NS_CC; Toast *Toast::makeText(cocos2d::Scene *scene, const std::string &text, Duration duration) { Toast *ret = new (std::nothrow) Toast(); if (ret != nullptr && ret->initWithText(scene, text, duration)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool Toast::initWithText(cocos2d::Scene *scene, const std::string &text, Duration duration) { if (UNLIKELY(!Node::init())) { return false; } _scene = scene; _duration = duration; const float width = maxWidth(); Label *label = Label::createWithSystemFont(text, "Arail", 12); Size size = label->getContentSize(); if (size.width > width - 15.0f) { label->setHorizontalAlignment(TextHAlignment::CENTER); label->setDimensions(width - 15.0f, 0.0f); size = label->getContentSize(); } size.width += 15.0f; size.height += 15.0f; this->setContentSize(Size(size.width, size.height)); this->addChild(label); label->setPosition(Vec2(size.width * 0.5f, size.height * 0.5f)); this->addChild(LayerColor::create(Color4B(0x20, 0x20, 0x20, 0xF0), size.width, size.height), -1); this->setIgnoreAnchorPointForPosition(false); this->setAnchorPoint(Vec2::ANCHOR_MIDDLE); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); float yPos = visibleSize.height * 0.15f; if (yPos + size.height * 0.5f > visibleSize.height) { yPos = visibleSize.height * 0.5f; } this->setPosition(Vec2(origin.x + visibleSize.width * 0.5f, origin.y + yPos)); return true; } void Toast::show() { _scene->addChild(this, 100); _scene = nullptr; float dt = _duration == LENGTH_LONG ? 3.5f : 2.0f; this->runAction(Sequence::create(DelayTime::create(dt), FadeOut::create(0.2f), RemoveSelf::create(), NULL)); } <|endoftext|>
<commit_before>#include "../yahttp/yahttp.hpp" #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <ext/stdio_filebuf.h> #include <string.h> /** Helper class for keeping single request/response pair */ class ServerRequestResponse { public: YaHTTP::Request req; YaHTTP::Response resp; YaHTTP::AsyncRequestLoader arl; int state; int id; time_t last; ServerRequestResponse() { state = 0; id = -1; }; void initialize() { req.initialize(); resp.initialize(); } }; /** Really basic simple server */ class Server { public: /** Connection pool */ ServerRequestResponse pool[100]; int port; int lfd; Server(int port) { this->port = port; } void bind() { struct sockaddr_in sa; int val = 1; lfd = ::socket(AF_INET, SOCK_STREAM, 6); // tcp // some modern options ::setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); ::setsockopt(lfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = 0; sa.sin_port = htons(port); ::bind(lfd, reinterpret_cast<struct sockaddr*>(&sa), sizeof(sa)); ::listen(lfd, 100); } void accept() { struct sockaddr_in sa; socklen_t salen; int fd; int val=1; char ipaddr[INET_ADDRSTRLEN]; salen = sizeof(sa); memset(&sa,0,sizeof(sa)); fd = ::accept(lfd, reinterpret_cast<struct sockaddr*>(&sa), &salen); if (fd < 0) return; // false alarm inet_ntop(AF_INET, &sa.sin_addr, ipaddr, sizeof ipaddr); ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); ::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); val = 0; ::setsockopt(fd, SOL_SOCKET, SO_LINGER, &val, sizeof(val)); pool[fd].initialize(); pool[fd].id = fd; std::cout << "Connection from " << ipaddr << ":" << ntohs(sa.sin_port) << " accepted on fd=" << fd << std::endl; } // handle a request void handle(ServerRequestResponse &rr) { try { if (rr.state == 0) { rr.arl.initialize(&rr.req); rr.state = 1; } if (rr.state == 1) { char buf[4096]; size_t r; r = ::read(rr.id, buf, sizeof(buf)); if (r>0) { rr.arl.feed(std::string(buf,r)); } if (rr.arl.ready()) { rr.arl.finalize(); rr.state = 2; } else { if (r == 0) { // EOF ::close(rr.id); rr.state = 0; rr.id = -1; } return; } } } catch (YaHTTP::Error &err) { ::close(rr.id); rr.state = 0; rr.id = -1; std::cout << "YaHTTP::Error: " << err.what() << std::endl; return; } rr.resp.headers["content-type"] = "text/html; charset=utf-8"; rr.resp.headers["connection"] = "close"; rr.resp.version = rr.req.version; if (rr.req.url.path == "/") { rr.resp.url = rr.req.url; rr.resp.status = 200; rr.resp.body = "<!DOCTYPE html>\n<html lang=\"en\"><head><title>Hello, world</title><link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" /></head><body><h1>200 OK</h1><p>Hello, world</p></body></html>"; } else if (rr.req.url.path == "/style.css") { rr.resp.url = rr.req.url; rr.resp.status = 200; rr.resp.headers["content-type"] = "text/css; charset=utf-8"; rr.resp.renderer = YaHTTP::HTTPBase::SendFileRender("style.css"); } else if (rr.req.url.path == "/bg.jpg") { rr.resp.url = rr.req.url; rr.resp.status = 200; rr.resp.headers["content-type"] = "image/jpeg"; // rr.resp.headers["content-length"] = "810816"; rr.resp.renderer = YaHTTP::HTTPBase::SendFileRender("bg.jpg"); } else { rr.resp.url = rr.req.url; rr.resp.status = 404; rr.resp.body = "<!DOCTYPE html>\n<html lang=\"en\"><head><title>404 Not Found</title><link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" /></head><body><h1>404 Not Found</h1><p>Requested URL not found</p></body></html>"; } std::cout << "Sending " << rr.resp.status << " for " << rr.resp.url.path << std::endl; std::ostringstream tmp; tmp << rr.resp; ::write(rr.id, tmp.str().c_str(), tmp.str().size()); ::close(rr.id); rr.id = -1; rr.state = 0; } void run() { int idx; struct timeval tv; int maxfd; fd_set rfd; bind(); std::cout << "Listening on 0.0.0.0:" << port << std::endl; while(true) { FD_ZERO(&rfd); maxfd = lfd; FD_SET(lfd, &rfd); for(idx = lfd+1; idx < 100; idx++) { if (pool[idx].id>-1) { FD_SET( idx, &rfd ); maxfd = idx; } } tv.tv_sec = 0; tv.tv_usec = 100; if (select(maxfd+1, &rfd, NULL, NULL, &tv)>0) { // we have a winner if (FD_ISSET( lfd, &rfd )) { accept(); } for(idx = lfd+1; idx < 100; idx++) { if (FD_ISSET( idx, &rfd )) { handle(pool[idx]); } } } } } }; int main(void) { Server(2828).run(); } <commit_msg>Remove code duplication<commit_after>#include "../yahttp/yahttp.hpp" #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <ext/stdio_filebuf.h> #include <string.h> /** Helper class for keeping single request/response pair */ class ServerRequestResponse { public: YaHTTP::Request req; YaHTTP::Response resp; YaHTTP::AsyncRequestLoader arl; int state; int id; time_t last; ServerRequestResponse() { state = 0; id = -1; }; void initialize() { req.initialize(); resp.initialize(); } }; /** Really basic simple server */ class Server { public: /** Connection pool */ ServerRequestResponse pool[100]; int port; int lfd; Server(int port) { this->port = port; } void bind() { struct sockaddr_in sa; int val = 1; lfd = ::socket(AF_INET, SOCK_STREAM, 6); // tcp // some modern options ::setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); ::setsockopt(lfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = 0; sa.sin_port = htons(port); ::bind(lfd, reinterpret_cast<struct sockaddr*>(&sa), sizeof(sa)); ::listen(lfd, 100); } void accept() { struct sockaddr_in sa; socklen_t salen; int fd; int val=1; char ipaddr[INET_ADDRSTRLEN]; salen = sizeof(sa); memset(&sa,0,sizeof(sa)); fd = ::accept(lfd, reinterpret_cast<struct sockaddr*>(&sa), &salen); if (fd < 0) return; // false alarm inet_ntop(AF_INET, &sa.sin_addr, ipaddr, sizeof ipaddr); ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); ::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)); val = 0; ::setsockopt(fd, SOL_SOCKET, SO_LINGER, &val, sizeof(val)); pool[fd].initialize(); pool[fd].id = fd; std::cout << "Connection from " << ipaddr << ":" << ntohs(sa.sin_port) << " accepted on fd=" << fd << std::endl; } // handle a request void handle(ServerRequestResponse &rr) { try { if (rr.state == 0) { rr.arl.initialize(&rr.req); rr.state = 1; } if (rr.state == 1) { char buf[4096]; size_t r; r = ::read(rr.id, buf, sizeof(buf)); if (r>0) { rr.arl.feed(std::string(buf,r)); } if (rr.arl.ready()) { rr.arl.finalize(); rr.state = 2; } else { if (r == 0) { // EOF ::close(rr.id); rr.state = 0; rr.id = -1; } return; } } } catch (YaHTTP::Error &err) { ::close(rr.id); rr.state = 0; rr.id = -1; std::cout << "YaHTTP::Error: " << err.what() << std::endl; return; } rr.resp.headers["content-type"] = "text/html; charset=utf-8"; rr.resp.headers["connection"] = "close"; rr.resp.version = rr.req.version; rr.resp.url = rr.req.url; if (rr.req.url.path == "/") { rr.resp.status = 200; rr.resp.body = "<!DOCTYPE html>\n<html lang=\"en\"><head><title>Hello, world</title><link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" /></head><body><h1>200 OK</h1><p>Hello, world</p></body></html>"; } else if (rr.req.url.path == "/style.css") { rr.resp.status = 200; rr.resp.headers["content-type"] = "text/css; charset=utf-8"; rr.resp.renderer = YaHTTP::HTTPBase::SendFileRender("style.css"); } else if (rr.req.url.path == "/bg.jpg") { rr.resp.status = 200; rr.resp.headers["content-type"] = "image/jpeg"; // rr.resp.headers["content-length"] = "810816"; rr.resp.renderer = YaHTTP::HTTPBase::SendFileRender("bg.jpg"); } else { rr.resp.status = 404; rr.resp.body = "<!DOCTYPE html>\n<html lang=\"en\"><head><title>404 Not Found</title><link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" /></head><body><h1>404 Not Found</h1><p>Requested URL not found</p></body></html>"; } std::cout << "Sending " << rr.resp.status << " for " << rr.resp.url.path << std::endl; std::ostringstream tmp; tmp << rr.resp; ::write(rr.id, tmp.str().c_str(), tmp.str().size()); ::close(rr.id); rr.id = -1; rr.state = 0; } void run() { int idx; struct timeval tv; int maxfd; fd_set rfd; bind(); std::cout << "Listening on 0.0.0.0:" << port << std::endl; while(true) { FD_ZERO(&rfd); maxfd = lfd; FD_SET(lfd, &rfd); for(idx = lfd+1; idx < 100; idx++) { if (pool[idx].id>-1) { FD_SET( idx, &rfd ); maxfd = idx; } } tv.tv_sec = 0; tv.tv_usec = 100; if (select(maxfd+1, &rfd, NULL, NULL, &tv)>0) { // we have a winner if (FD_ISSET( lfd, &rfd )) { accept(); } for(idx = lfd+1; idx < 100; idx++) { if (FD_ISSET( idx, &rfd )) { handle(pool[idx]); } } } } } }; int main(void) { Server(2828).run(); } <|endoftext|>
<commit_before>#include "MultiTuProcessor.hpp" #include "CgStr.hpp" #include "SimpleTemplate.hpp" #include "basicHl.hpp" #include "xref.hpp" #include <boost/filesystem.hpp> #include <boost/variant/variant.hpp> #include <algorithm> #include <climits> #include <iostream> using namespace synth; static fs::path normalAbsolute(fs::path const& p) { fs::path r = fs::absolute(p).lexically_normal(); if (r.filename() == ".") r.remove_filename(); return r; } // Idea from http://stackoverflow.com/a/15549954/2128694, user Rob Kennedy static bool isPathSuffix(fs::path const& dir, fs::path const& p) { return std::mismatch(dir.begin(), dir.end(), p.begin(), p.end()).first == dir.end(); } static fs::path commonPrefix(fs::path const& p1, fs::path const& p2) { auto it1 = p1.begin(), it2 = p2.begin(); fs::path r; while (it1 != p1.end() && it2 != p2.end()) { if (*it1 != *it2) break; r /= *it1; ++it1; ++it2; } return r; } MultiTuProcessor::MultiTuProcessor( PathMap const& dirs, ExternalRefLinker&& refLinker) : m_refLinker(std::move(refLinker)) { if (dirs.empty()) return; m_rootInDir = dirs.begin()->first; for (auto const& kv : dirs) { fs::path inDir = normalAbsolute(kv.first); m_dirs.push_back({inDir, kv.second}); m_rootInDir = commonPrefix(std::move(m_rootInDir), inDir); } } bool MultiTuProcessor::isFileIncluded(fs::path const& p) const { return getFileMapping(p) != nullptr; } PathMap::value_type const* MultiTuProcessor::getFileMapping( fs::path const& p) const { fs::path cleanP = normalAbsolute(p); if (!isPathSuffix(m_rootInDir, cleanP)) return nullptr; for (auto const& kv : m_dirs) { if (isPathSuffix(kv.first, cleanP)) return &kv; } return nullptr; } HighlightedFile* MultiTuProcessor::prepareToProcess(CXFile f) { FileEntry* fentry = obtainFileEntry(f); if (!fentry || fentry->processed.test_and_set()) return nullptr; return &fentry->hlFile; } void synth::MultiTuProcessor::registerDef( std::string && usr, SymbolDeclaration const* def) { std::lock_guard<std::mutex> lock(m_mut); m_defs.insert({ std::move(usr), std::move(def) }); } FileEntry* MultiTuProcessor::obtainFileEntry(CXFile f) { CXFileUniqueID fuid; if (!f || clang_getFileUniqueID(f, &fuid) != 0) return nullptr; std::lock_guard<std::mutex> lock(m_mut); auto it = m_processedFiles.find(fuid); if (it != m_processedFiles.end()) return &it->second; fs::path fname(CgStr(clang_getFileName(f)).gets()); if (fname.empty()) return nullptr; auto mapping = getFileMapping(fname); if (!mapping) return nullptr; fname = fs::relative(std::move(fname), mapping->first); FileEntry& e = m_processedFiles.emplace( std::piecewise_construct, std::forward_as_tuple(std::move(fuid)), std::forward_as_tuple()) .first->second; e.hlFile.fname = std::move(fname); e.hlFile.inOutDir = mapping; return &e; } void MultiTuProcessor::writeOutput(SimpleTemplate const& tpl) { if (m_dirs.empty()) return; auto it = m_dirs.begin(); fs::path rootOutDir = it->second; fs::path normAbsRootOutDir = normalAbsolute(rootOutDir); for (++it; it != m_dirs.end(); ++it) { rootOutDir = commonPrefix(rootOutDir, it->second); normAbsRootOutDir = commonPrefix(normAbsRootOutDir, normalAbsolute(it->second)); } bool commonRoot = !normAbsRootOutDir.empty() && isPathSuffix( normalAbsolute(fs::current_path()), normAbsRootOutDir); if (commonRoot && rootOutDir.empty()) rootOutDir = "."; SimpleTemplate::Context ctx; std::clog << "Writing " << m_processedFiles.size() << " HTML files...\n"; for (auto& fentry : m_processedFiles) { auto& hlFile = fentry.second.hlFile; auto dstPath = hlFile.dstPath(); auto hldir = dstPath.parent_path(); if (hldir != "." && !hldir.empty()) fs::create_directories(hldir); sortMarkups(hlFile.markups); fs::ifstream srcfile(hlFile.srcPath(), std::ios::binary); fs::ofstream outfile; try { srcfile.exceptions(std::ios::badbit); std::vector<Markup> suppMarkups; basicHighlightFile(srcfile, suppMarkups); sortMarkups(suppMarkups); hlFile.supplementMarkups(suppMarkups); srcfile.clear(); srcfile.seekg(0); outfile.open(dstPath, std::ios::binary); outfile.exceptions(std::ios::badbit | std::ios::failbit); ctx["code"] = SimpleTemplate::ValCallback(std::bind( &HighlightedFile::writeTo, &hlFile, std::placeholders::_1, std::ref(*this), std::ref(srcfile))); ctx["filename"] = hlFile.fname.string(); fs::path rootpath = fs::relative( commonRoot ? rootOutDir : hlFile.inOutDir->second, hldir) .lexically_normal(); ctx["rootpath"] = rootpath.empty() ? "." : rootpath.string(); tpl.writeTo(outfile, ctx); } catch (std::ios::failure& e) { if (!srcfile) { throw std::runtime_error( "Error reading from or opening " + hlFile.srcPath().string() + ": " + e.what()); } if (!outfile) { throw std::runtime_error( "Error writing to or opening " + hlFile.dstPath().string() + ": " + e.what()); } assert("ios::failure but no file with badbit or failbit" && false); throw; } } } <commit_msg>Fix broken cross-outroot links.<commit_after>#include "MultiTuProcessor.hpp" #include "CgStr.hpp" #include "SimpleTemplate.hpp" #include "basicHl.hpp" #include "xref.hpp" #include <boost/filesystem.hpp> #include <boost/variant/variant.hpp> #include <algorithm> #include <climits> #include <iostream> using namespace synth; static fs::path normalAbsolute(fs::path const& p) { fs::path r = fs::absolute(p).lexically_normal(); if (r.filename() == ".") r.remove_filename(); return r; } // Idea from http://stackoverflow.com/a/15549954/2128694, user Rob Kennedy static bool isPathSuffix(fs::path const& dir, fs::path const& p) { return std::mismatch(dir.begin(), dir.end(), p.begin(), p.end()).first == dir.end(); } static fs::path commonPrefix(fs::path const& p1, fs::path const& p2) { auto it1 = p1.begin(), it2 = p2.begin(); fs::path r; while (it1 != p1.end() && it2 != p2.end()) { if (*it1 != *it2) break; r /= *it1; ++it1; ++it2; } return r; } MultiTuProcessor::MultiTuProcessor( PathMap const& dirs, ExternalRefLinker&& refLinker) : m_refLinker(std::move(refLinker)) { if (dirs.empty()) return; m_rootInDir = dirs.begin()->first; for (auto const& kv : dirs) { fs::path inDir = normalAbsolute(kv.first); m_dirs.push_back({inDir, normalAbsolute(kv.second)}); m_rootInDir = commonPrefix(std::move(m_rootInDir), inDir); } } bool MultiTuProcessor::isFileIncluded(fs::path const& p) const { return getFileMapping(p) != nullptr; } PathMap::value_type const* MultiTuProcessor::getFileMapping( fs::path const& p) const { fs::path cleanP = normalAbsolute(p); if (!isPathSuffix(m_rootInDir, cleanP)) return nullptr; for (auto const& kv : m_dirs) { if (isPathSuffix(kv.first, cleanP)) return &kv; } return nullptr; } HighlightedFile* MultiTuProcessor::prepareToProcess(CXFile f) { FileEntry* fentry = obtainFileEntry(f); if (!fentry || fentry->processed.test_and_set()) return nullptr; return &fentry->hlFile; } void synth::MultiTuProcessor::registerDef( std::string && usr, SymbolDeclaration const* def) { std::lock_guard<std::mutex> lock(m_mut); m_defs.insert({ std::move(usr), std::move(def) }); } FileEntry* MultiTuProcessor::obtainFileEntry(CXFile f) { CXFileUniqueID fuid; if (!f || clang_getFileUniqueID(f, &fuid) != 0) return nullptr; std::lock_guard<std::mutex> lock(m_mut); auto it = m_processedFiles.find(fuid); if (it != m_processedFiles.end()) return &it->second; fs::path fname(CgStr(clang_getFileName(f)).gets()); if (fname.empty()) return nullptr; auto mapping = getFileMapping(fname); if (!mapping) return nullptr; fname = fs::relative(std::move(fname), mapping->first); FileEntry& e = m_processedFiles.emplace( std::piecewise_construct, std::forward_as_tuple(std::move(fuid)), std::forward_as_tuple()) .first->second; e.hlFile.fname = std::move(fname); e.hlFile.inOutDir = mapping; return &e; } void MultiTuProcessor::writeOutput(SimpleTemplate const& tpl) { if (m_dirs.empty()) return; auto it = m_dirs.begin(); fs::path rootOutDir = it->second; for (++it; it != m_dirs.end(); ++it) rootOutDir = commonPrefix(rootOutDir, it->second); bool commonRoot = !rootOutDir.empty() && isPathSuffix( normalAbsolute(fs::current_path()), rootOutDir); if (commonRoot && rootOutDir.empty()) rootOutDir = "."; SimpleTemplate::Context ctx; std::clog << "Writing " << m_processedFiles.size() << " HTML files...\n"; for (auto& fentry : m_processedFiles) { auto& hlFile = fentry.second.hlFile; auto dstPath = hlFile.dstPath(); auto hldir = dstPath.parent_path(); if (hldir != "." && !hldir.empty()) fs::create_directories(hldir); sortMarkups(hlFile.markups); fs::ifstream srcfile(hlFile.srcPath(), std::ios::binary); fs::ofstream outfile; try { srcfile.exceptions(std::ios::badbit); std::vector<Markup> suppMarkups; basicHighlightFile(srcfile, suppMarkups); sortMarkups(suppMarkups); hlFile.supplementMarkups(suppMarkups); srcfile.clear(); srcfile.seekg(0); outfile.open(dstPath, std::ios::binary); outfile.exceptions(std::ios::badbit | std::ios::failbit); ctx["code"] = SimpleTemplate::ValCallback(std::bind( &HighlightedFile::writeTo, &hlFile, std::placeholders::_1, std::ref(*this), std::ref(srcfile))); ctx["filename"] = hlFile.fname.string(); fs::path rootpath = fs::relative( commonRoot ? rootOutDir : hlFile.inOutDir->second, hldir) .lexically_normal(); ctx["rootpath"] = rootpath.empty() ? "." : rootpath.string(); tpl.writeTo(outfile, ctx); } catch (std::ios::failure& e) { if (!srcfile) { throw std::runtime_error( "Error reading from or opening " + hlFile.srcPath().string() + ": " + e.what()); } if (!outfile) { throw std::runtime_error( "Error writing to or opening " + hlFile.dstPath().string() + ": " + e.what()); } assert("ios::failure but no file with badbit or failbit" && false); throw; } } } <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" #include <IniFiles.hpp> #include "Unit2.h" #define HISTORY_SIZE 5 //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; bool isStart = false; int count = 0; bool isTochu = false; time_t startTime; int endTime; int historyTime[HISTORY_SIZE] = {180,180,180,180,180}; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { if(isStart){ isStart = false; Button1->Caption = "Start"; Timer1->Enabled = false; endTime -= difftime(time(NULL),startTime); }else{ if(!isTochu){ if(Edit1->Text == EmptyStr || Edit2->Text == EmptyStr){ Edit1->Text = "0"; Edit2->Text = "0"; return; } count = StrToInt(Edit1->Text) * 60 + StrToInt(Edit2->Text); HistorySetting(count); isTochu = true; endTime = count; } startTime = time(NULL); isStart = true; Button1->Caption = "Stop"; Label1->Caption = AnsiString().sprintf("%02d:%02d:%02d",count / 3600,(count - (count / 3600) * 3600)/ 60,count % 60); Timer1->Enabled = true; } } //--------------------------------------------------------------------------- void __fastcall TForm1::HistorySetting(int num) { bool isExist = false; int tmp,i; UnicodeString str; for(i = 0;i < HISTORY_SIZE;i++){ if(historyTime[i] == num){ isExist = true; break; } } if(isExist){ if(i == 0){ return; } tmp = historyTime[i]; for(int j = i;j > 0;j--){ historyTime[j] = historyTime[j - 1]; } historyTime[0] = tmp; }else{ historyTime[4] = historyTime[3]; historyTime[3] = historyTime[2]; historyTime[2] = historyTime[1]; historyTime[1] = historyTime[0]; historyTime[0] = count; } for(int i = 0;i < HISTORY_SIZE;i++){ str = IntToStr(historyTime[i] / 60) + "" + IntToStr(historyTime[i] % 60) + "b"; PopupMenu1->Items->Items[i + 2]->Caption = str; } } //-------------------- void __fastcall TForm1::Timer1Timer(TObject *Sender) { count = endTime - difftime(time(NULL),startTime); Label1->Caption = AnsiString().sprintf("%02d:%02d:%02d",count / 3600,(count - (count / 3600) * 3600)/ 60,count % 60); if(count <= 0){ if(count > -3){ //b0 Label1->Caption = "00:00:00"; } EndProcessing(); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button3Click(TObject *Sender) { isTochu = false; isStart = false; Timer1->Enabled = false; if(Edit1->Text == EmptyStr || Edit2->Text == EmptyStr){ Edit1->Text = "0"; Edit2->Text = "0"; }else{ Label1->Caption = AnsiString().sprintf("%02d:%02d:%02d",StrToInt(Edit1->Text) / 60,StrToInt(Edit1->Text) % 60,StrToInt(Edit2->Text)); } Button1->Caption = "Start"; } //--------------------------------------------------------------------------- void __fastcall TForm1::EndProcessing() { UnicodeString message = Form2->EditNotifyMessage->Text; isStart = false; isTochu = false; Form1->Timer1->Enabled = false; Form1->Button1->Caption = "ReStart"; if(Form2->CheckBox3->Checked){ TNotification *MyNotification = NotificationCenter1->CreateNotification(); try{ MyNotification->Name = "mytimer"; MyNotification->AlertBody = message; MyNotification->Title = "^C}["; NotificationCenter1->PresentNotification(MyNotification); }__finally{ delete MyNotification; } if(count < -3){ ShowWindow(Form1->Handle,SW_RESTORE); SetWindowPos(Form1->Handle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); Application->MessageBoxW(message.c_str(),L"^C}[",MB_OK); SetWindowPos(Form1->Handle,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); } }else{ if(Form2->CheckBox1->Checked){ MessageBeep(MB_OK); } if(Form2->CheckBox4->Checked){ Application->MessageBox(message.c_str(),L"^C}[",MB_OK); }else{ ShowWindow(Form1->Handle,SW_RESTORE); SetWindowPos(Form1->Handle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); Application->MessageBox(message.c_str(),L"^C}[",MB_OK); SetWindowPos(Form1->Handle,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); } } return; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { //ݒʂ̕\ Form2->Show(); Form2->Left = Form1->Left + 50; Form2->Top = Form1->Top + 50; } //--------------------------------------------------------------------------- //ݒ̓ǂݍ void __fastcall TForm1::FormShow(TObject *Sender) { TIniFile *ini; UnicodeString str; try{ ini = new TIniFile( ChangeFileExt( Application->ExeName, ".ini" ) ); Edit1->Text = ini->ReadInteger("Form", "DefaultMinute", 30); Form2->Edit1->Text = Edit1->Text; Edit2->Text = ini->ReadInteger("Form", "DefaultSecond", 0); Form2->Edit2->Text = Edit2->Text; Form2->EditNotifyMessage->Text = ini->ReadString("Form","NotifyMessage","Ԃł"); Form2->CheckBox1->Checked = ini->ReadBool("Form","NotificationSound",True); //Form2->CheckBox2->Checked = ini->ReadBool("Form","DoubleBuffering",False); Form2->CheckBox3->Checked = ini->ReadBool("Form","UseActionCenter",False); Form2->CheckBox4->Checked = ini->ReadBool("Form","DisplayTopMost",False); for(int i = 0;i < HISTORY_SIZE;i++){ historyTime[i] = ini->ReadInteger("History", "His" + IntToStr(i),180); } }__finally{ delete ini; } //ȉύX if(Form2->CheckBox4->Checked){ SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOREDRAW); } for(int i = 0;i < HISTORY_SIZE;i++){ str = IntToStr(historyTime[i] / 60) + "" + IntToStr(historyTime[i] % 60) + "b"; PopupMenu1->Items->Items[i + 2]->Caption = str; } str = Form2->Edit1->Text + "" + Form2->Edit2->Text + "b"; PopupMenu1->Items->Items[0]->Caption = str; //Form1->DoubleBuffered = Form2->CheckBox2->Checked; } //--------------------------------------------------------------------------- void __fastcall TForm1::SetDefaultClick(TObject *Sender) { Edit1->Text = Form2->Edit1->Text; Edit2->Text = Form2->Edit2->Text; } //--------------------------------------------------------------------------- void __fastcall TForm1::Set1Click(TObject *Sender) { SetClick(0); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set2Click(TObject *Sender) { SetClick(1); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set3Click(TObject *Sender) { SetClick(2); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set4Click(TObject *Sender) { SetClick(3); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set5Click(TObject *Sender) { SetClick(4); } //--------------------------------------------------------------------------- void __fastcall TForm1::SetClick(int num) { Edit1->Text = historyTime[num] / 60; Edit2->Text = historyTime[num] % 60; } //--------------------------------------------------------------------------- void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action) { TIniFile *ini; try{ ini = new TIniFile( ChangeFileExt( Application->ExeName, ".ini" ) ); for(int i = 0;i < HISTORY_SIZE;i++){ ini->WriteInteger("History", "His" + IntToStr(i), historyTime[i]); } }__finally{ delete ini; } } //--------------------------------------------------------------------------- <commit_msg>mearge<commit_after>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" #include <IniFiles.hpp> #include "Unit2.h" #define HISTORY_SIZE 5 //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; bool isStart = false; int count = 0; bool isTochu = false; time_t startTime; int endTime; int historyTime[HISTORY_SIZE] = {180,180,180,180,180}; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { if(isStart){ isStart = false; Button1->Caption = "Start"; Timer1->Enabled = false; endTime -= difftime(time(NULL),startTime); }else{ if(!isTochu){ if(Edit1->Text == EmptyStr || Edit2->Text == EmptyStr){ Edit1->Text = "0"; Edit2->Text = "0"; return; } count = StrToInt(Edit1->Text) * 60 + StrToInt(Edit2->Text); HistorySetting(count); <<<<<<< HEAD ======= >>>>>>> 3235aa40e6d1b1aa28120a49933b25fdb26bb62f isTochu = true; endTime = count; } startTime = time(NULL); isStart = true; Button1->Caption = "Stop"; Label1->Caption = AnsiString().sprintf("%02d:%02d:%02d",count / 3600,(count - (count / 3600) * 3600)/ 60,count % 60); Timer1->Enabled = true; } } //--------------------------------------------------------------------------- void __fastcall TForm1::HistorySetting(int num) { bool isExist = false; int tmp,i; UnicodeString str; for(i = 0;i < HISTORY_SIZE;i++){ if(historyTime[i] == num){ isExist = true; break; } } if(isExist){ if(i == 0){ return; } tmp = historyTime[i]; for(int j = i;j > 0;j--){ historyTime[j] = historyTime[j - 1]; } historyTime[0] = tmp; }else{ historyTime[4] = historyTime[3]; historyTime[3] = historyTime[2]; historyTime[2] = historyTime[1]; historyTime[1] = historyTime[0]; historyTime[0] = count; } for(int i = 0;i < HISTORY_SIZE;i++){ str = IntToStr(historyTime[i] / 60) + "" + IntToStr(historyTime[i] % 60) + "b"; PopupMenu1->Items->Items[i + 2]->Caption = str; } } //-------------------- void __fastcall TForm1::Timer1Timer(TObject *Sender) { count = endTime - difftime(time(NULL),startTime); Label1->Caption = AnsiString().sprintf("%02d:%02d:%02d",count / 3600,(count - (count / 3600) * 3600)/ 60,count % 60); if(count <= 0){ if(count > -3){ //b0 Label1->Caption = "00:00:00"; } EndProcessing(); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button3Click(TObject *Sender) { isTochu = false; isStart = false; Timer1->Enabled = false; if(Edit1->Text == EmptyStr || Edit2->Text == EmptyStr){ Edit1->Text = "0"; Edit2->Text = "0"; }else{ Label1->Caption = AnsiString().sprintf("%02d:%02d:%02d",StrToInt(Edit1->Text) / 60,StrToInt(Edit1->Text) % 60,StrToInt(Edit2->Text)); } Button1->Caption = "Start"; } //--------------------------------------------------------------------------- void __fastcall TForm1::EndProcessing() { UnicodeString message = Form2->EditNotifyMessage->Text; isStart = false; isTochu = false; Form1->Timer1->Enabled = false; Form1->Button1->Caption = "ReStart"; if(Form2->CheckBox3->Checked){ TNotification *MyNotification = NotificationCenter1->CreateNotification(); try{ MyNotification->Name = "mytimer"; MyNotification->AlertBody = message; MyNotification->Title = "^C}["; NotificationCenter1->PresentNotification(MyNotification); }__finally{ delete MyNotification; } if(count < -3){ ShowWindow(Form1->Handle,SW_RESTORE); SetWindowPos(Form1->Handle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); Application->MessageBoxW(message.c_str(),L"^C}[",MB_OK); SetWindowPos(Form1->Handle,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); } }else{ if(Form2->CheckBox1->Checked){ MessageBeep(MB_OK); } if(Form2->CheckBox4->Checked){ Application->MessageBox(message.c_str(),L"^C}[",MB_OK); }else{ ShowWindow(Form1->Handle,SW_RESTORE); SetWindowPos(Form1->Handle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); Application->MessageBox(message.c_str(),L"^C}[",MB_OK); SetWindowPos(Form1->Handle,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE); } } return; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { //ݒʂ̕\ Form2->Show(); Form2->Left = Form1->Left + 50; Form2->Top = Form1->Top + 50; } //--------------------------------------------------------------------------- //ݒ̓ǂݍ void __fastcall TForm1::FormShow(TObject *Sender) { TIniFile *ini; UnicodeString str; try{ ini = new TIniFile( ChangeFileExt( Application->ExeName, ".ini" ) ); Edit1->Text = ini->ReadInteger("Form", "DefaultMinute", 30); Form2->Edit1->Text = Edit1->Text; Edit2->Text = ini->ReadInteger("Form", "DefaultSecond", 0); Form2->Edit2->Text = Edit2->Text; Form2->EditNotifyMessage->Text = ini->ReadString("Form","NotifyMessage","Ԃł"); Form2->CheckBox1->Checked = ini->ReadBool("Form","NotificationSound",True); //Form2->CheckBox2->Checked = ini->ReadBool("Form","DoubleBuffering",False); Form2->CheckBox3->Checked = ini->ReadBool("Form","UseActionCenter",False); Form2->CheckBox4->Checked = ini->ReadBool("Form","DisplayTopMost",False); for(int i = 0;i < HISTORY_SIZE;i++){ historyTime[i] = ini->ReadInteger("History", "His" + IntToStr(i),180); } }__finally{ delete ini; } //ȉύX if(Form2->CheckBox4->Checked){ SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOREDRAW); } for(int i = 0;i < HISTORY_SIZE;i++){ str = IntToStr(historyTime[i] / 60) + "" + IntToStr(historyTime[i] % 60) + "b"; PopupMenu1->Items->Items[i + 2]->Caption = str; } <<<<<<< HEAD str = Form2->Edit1->Text + "" + Form2->Edit2->Text + "b"; PopupMenu1->Items->Items[0]->Caption = str; ======= >>>>>>> 3235aa40e6d1b1aa28120a49933b25fdb26bb62f //Form1->DoubleBuffered = Form2->CheckBox2->Checked; } //--------------------------------------------------------------------------- void __fastcall TForm1::SetDefaultClick(TObject *Sender) { Edit1->Text = Form2->Edit1->Text; Edit2->Text = Form2->Edit2->Text; } //--------------------------------------------------------------------------- void __fastcall TForm1::Set1Click(TObject *Sender) { SetClick(0); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set2Click(TObject *Sender) { SetClick(1); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set3Click(TObject *Sender) { SetClick(2); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set4Click(TObject *Sender) { SetClick(3); } //--------------------------------------------------------------------------- void __fastcall TForm1::Set5Click(TObject *Sender) { SetClick(4); } //--------------------------------------------------------------------------- void __fastcall TForm1::SetClick(int num) { Edit1->Text = historyTime[num] / 60; Edit2->Text = historyTime[num] % 60; } //--------------------------------------------------------------------------- void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action) { TIniFile *ini; try{ ini = new TIniFile( ChangeFileExt( Application->ExeName, ".ini" ) ); for(int i = 0;i < HISTORY_SIZE;i++){ ini->WriteInteger("History", "His" + IntToStr(i), historyTime[i]); } }__finally{ delete ini; } } //--------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "boomerang.h" #include "gc.h" #ifdef WIN32 #include <direct.h> // For Windows mkdir #endif #include <signal.h> #ifdef SPARC_DEBUG void segv_handler(int a, siginfo_t *b, void *c) { fprintf(stderr, "Boomerang has encounted a fatal error.\n"); ucontext_t *uc = (ucontext_t *) c; #if 0 fprintf(stderr, "\n*** SIGNAL TRAPPED: SIGNAL %d ***\n", a); fprintf(stderr, "si_signo = %d\n", b->si_signo); fprintf(stderr, "si_code = %d\n", b->si_code); fprintf(stderr, "si_errno = %d\n", b->si_errno); fprintf(stderr, "si_addr = %p\n", b->si_addr); fprintf(stderr, "si_trapno= %p\n", b->si_trapno); fprintf(stderr, "si_pc = %p\n\n", b->si_pc); fprintf(stderr, "stack info:\nsp: %8x size: %8x\n" "flags: %d\n\n", uc->uc_stack.ss_sp, uc->uc_stack.ss_size, uc->uc_stack.ss_flags); fprintf(stderr, "Registers:\npc: %8x npc: %8x\n" "o0: %8x o1: %8x o2: %8x o3: %8x\n" "o4: %8x o5: %8x o6: %8x o7: %8x\n\n" "g1: %8x g2: %8x g3: %8x g4: %8x\n" "g5: %8x g6: %8x g7: %8x\n\n", uc->uc_mcontext.gregs[REG_PC], uc->uc_mcontext.gregs[REG_nPC], uc->uc_mcontext.gregs[REG_O0], uc->uc_mcontext.gregs[REG_O1], uc->uc_mcontext.gregs[REG_O2], uc->uc_mcontext.gregs[REG_O3], uc->uc_mcontext.gregs[REG_O4], uc->uc_mcontext.gregs[REG_O5], uc->uc_mcontext.gregs[REG_O6], uc->uc_mcontext.gregs[REG_O7], uc->uc_mcontext.gregs[REG_G1], uc->uc_mcontext.gregs[REG_G2], uc->uc_mcontext.gregs[REG_G3], uc->uc_mcontext.gregs[REG_G4], uc->uc_mcontext.gregs[REG_G5], uc->uc_mcontext.gregs[REG_G6], uc->uc_mcontext.gregs[REG_G7]); fprintf(stderr, "stack: "); for (int i = 0; i < 100; i++) { unsigned int *sp = (unsigned int*)uc->uc_mcontext.gregs[REG_O6]; fprintf(stderr, "(%08X) %08X %08X %08X %08X", sp+i*4, sp[i*4], sp[i*4+1], sp[i*4+2], sp[i*4+3]); fprintf(stderr, "\n "); } #endif fprintf(stderr, "\napproximate stack trace:\n"); for (int i = 0; i < 100; i++) { unsigned int *sp = (unsigned int*)uc->uc_mcontext.gregs[REG_O6]; if (sp[i] - (unsigned int)(sp+i) < 100) fprintf(stderr, "%08X\n", sp[++i]); } exit(0); } int main(int argc, const char* argv[]) { struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); act.sa_sigaction = segv_handler; act.sa_flags = (SA_SIGINFO | SA_ONSTACK); sigaction(SIGSEGV, &act, NULL); #else int main(int argc, const char* argv[]) { #endif return Boomerang::get()->commandLine(argc, argv); } /* This makes sure that the garbage collector sees all allocations, even those that we can't be bothered collecting, especially standard STL objects */ void* operator new(size_t n) { #ifdef DONT_COLLECT_STL return GC_malloc_uncollectable(n); // Don't collect, but mark #else return GC_malloc(n); // Collect everything #endif } void operator delete(void* p) { #ifdef DONT_COLLECT_STL GC_free(p); // Important to call this if you call GC_malloc_uncollectable // #else do nothing! #endif } <commit_msg>Pull gc.h from the standard location of gc/gc.h<commit_after>#include "boomerang.h" #include "gc/gc.h" #ifdef WIN32 #include <direct.h> // For Windows mkdir #endif #include <signal.h> #ifdef SPARC_DEBUG void segv_handler(int a, siginfo_t *b, void *c) { fprintf(stderr, "Boomerang has encounted a fatal error.\n"); ucontext_t *uc = (ucontext_t *) c; #if 0 fprintf(stderr, "\n*** SIGNAL TRAPPED: SIGNAL %d ***\n", a); fprintf(stderr, "si_signo = %d\n", b->si_signo); fprintf(stderr, "si_code = %d\n", b->si_code); fprintf(stderr, "si_errno = %d\n", b->si_errno); fprintf(stderr, "si_addr = %p\n", b->si_addr); fprintf(stderr, "si_trapno= %p\n", b->si_trapno); fprintf(stderr, "si_pc = %p\n\n", b->si_pc); fprintf(stderr, "stack info:\nsp: %8x size: %8x\n" "flags: %d\n\n", uc->uc_stack.ss_sp, uc->uc_stack.ss_size, uc->uc_stack.ss_flags); fprintf(stderr, "Registers:\npc: %8x npc: %8x\n" "o0: %8x o1: %8x o2: %8x o3: %8x\n" "o4: %8x o5: %8x o6: %8x o7: %8x\n\n" "g1: %8x g2: %8x g3: %8x g4: %8x\n" "g5: %8x g6: %8x g7: %8x\n\n", uc->uc_mcontext.gregs[REG_PC], uc->uc_mcontext.gregs[REG_nPC], uc->uc_mcontext.gregs[REG_O0], uc->uc_mcontext.gregs[REG_O1], uc->uc_mcontext.gregs[REG_O2], uc->uc_mcontext.gregs[REG_O3], uc->uc_mcontext.gregs[REG_O4], uc->uc_mcontext.gregs[REG_O5], uc->uc_mcontext.gregs[REG_O6], uc->uc_mcontext.gregs[REG_O7], uc->uc_mcontext.gregs[REG_G1], uc->uc_mcontext.gregs[REG_G2], uc->uc_mcontext.gregs[REG_G3], uc->uc_mcontext.gregs[REG_G4], uc->uc_mcontext.gregs[REG_G5], uc->uc_mcontext.gregs[REG_G6], uc->uc_mcontext.gregs[REG_G7]); fprintf(stderr, "stack: "); for (int i = 0; i < 100; i++) { unsigned int *sp = (unsigned int*)uc->uc_mcontext.gregs[REG_O6]; fprintf(stderr, "(%08X) %08X %08X %08X %08X", sp+i*4, sp[i*4], sp[i*4+1], sp[i*4+2], sp[i*4+3]); fprintf(stderr, "\n "); } #endif fprintf(stderr, "\napproximate stack trace:\n"); for (int i = 0; i < 100; i++) { unsigned int *sp = (unsigned int*)uc->uc_mcontext.gregs[REG_O6]; if (sp[i] - (unsigned int)(sp+i) < 100) fprintf(stderr, "%08X\n", sp[++i]); } exit(0); } int main(int argc, const char* argv[]) { struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); act.sa_sigaction = segv_handler; act.sa_flags = (SA_SIGINFO | SA_ONSTACK); sigaction(SIGSEGV, &act, NULL); #else int main(int argc, const char* argv[]) { #endif return Boomerang::get()->commandLine(argc, argv); } /* This makes sure that the garbage collector sees all allocations, even those that we can't be bothered collecting, especially standard STL objects */ void* operator new(size_t n) { #ifdef DONT_COLLECT_STL return GC_malloc_uncollectable(n); // Don't collect, but mark #else return GC_malloc(n); // Collect everything #endif } void operator delete(void* p) { #ifdef DONT_COLLECT_STL GC_free(p); // Important to call this if you call GC_malloc_uncollectable // #else do nothing! #endif } <|endoftext|>
<commit_before>/// The MIT License (MIT) /// Copyright (c) 2016 Peter Goldsborough /// /// 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 <iostream> #include "lru/lru.hpp" using Cache = LRU::Cache<int, int>; int fibonacci(int n, Cache& cache) { if (n < 2) return 1; // We internally keep track of the last accessed key, meaning a // `contains(key)` + `lookup(key)` sequence will involve only a single hash // table lookup. if (cache.contains(n)) return cache[n]; auto value = fibonacci(n - 1, cache) + fibonacci(n - 2, cache); // Caches are 100% move-aware and we have implemented // `unordered_map` style emplacement and insertion. cache.emplace(n, value); return value; } int fibonacci(int n) { // Use a capacity of 100 (after 100 insertions, the next insertion will evict // the least-recently inserted element). The default capacity is 128. Note // that for fibonacci, a capacity of 2 is sufficient (and ideal). Cache cache(100); return fibonacci(n, cache); } auto main() -> int { std::cout << fibonacci(32) << std::endl; } <commit_msg>Update fibonacci-basic.cpp<commit_after>/// The MIT License (MIT) /// Copyright (c) 2016 Peter Goldsborough /// /// 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 <iostream> #include "lru/lru.hpp" using Cache = LRU::Cache<int, int>; int fibonacci(int n, Cache& cache) { if (n < 2) return 1; // We internally keep track of the last accessed key, meaning a // `contains(key)` + `lookup(key)` sequence will involve only a single hash // table lookup. if (cache.contains(n)) return cache[n]; auto value = fibonacci(n - 1, cache) + fibonacci(n - 2, cache); // Caches are 100% move-aware and we have implemented // `unordered_map` style emplacement and insertion. cache.emplace(n, value); return value; } int fibonacci(int n) { // Use a capacity of 100 (after 100 insertions, the next insertion will evict // the least-recently accessed element). The default capacity is 128. Note // that for fibonacci, a capacity of 2 is sufficient (and ideal). Cache cache(100); return fibonacci(n, cache); } auto main() -> int { std::cout << fibonacci(32) << std::endl; } <|endoftext|>
<commit_before>/* Copyright (C) 2010 Jochen Gerhard <gerhard@compeng.uni-frankfurt.de> Copyright (C) 2010 Matthias Kretz <kretz@kde.org> Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /*! Finite difference method example We calculate central differences for a given function and compare it to the analytical solution. */ #include <Vc/Vc> #include <iostream> #include <iomanip> #include <cmath> #include "../../tsc.h" #define USE_SCALAR_SINCOS enum { N = 10240000, PrintStep = 1000000 }; static const float epsilon = 1e-7; static const float lower = 0.f; static const float upper = 40000.f; static const float h = (upper - lower) / N; // dfu is the derivative of fu. This is really easy for sine and cosine: static inline float fu(float x) { return ( std::sin(x) ); } static inline float dfu(float x) { return ( std::cos(x) ); } static inline Vc::float_v fu(Vc::float_v x) { #ifdef USE_SCALAR_SINCOS Vc::float_v r; for (size_t i = 0; i < Vc::float_v::Size; ++i) { r[i] = std::sin(x[i]); } return r; #else return Vc::sin(x); #endif } static inline Vc::float_v dfu(Vc::float_v x) { #ifdef USE_SCALAR_SINCOS Vc::float_v r; for (size_t i = 0; i < Vc::float_v::Size; ++i) { r[i] = std::cos(x[i]); } return r; #else return Vc::cos(x); #endif } using Vc::float_v; // It is important for this example that the following variables (especially dy_points) are global // variables. Else the compiler can optimze all calculations of dy away except for the few places // where the value is used in printResults. Vc::Memory<float_v, N> x_points; Vc::Memory<float_v, N> y_points; float *VC_RESTRICT dy_points; void printResults() { std::cout << "------------------------------------------------------------\n" << std::setw(15) << "fu(x_i)" << std::setw(15) << "FD fu'(x_i)" << std::setw(15) << "SYM fu'(x)" << std::setw(15) << "error %\n"; for (int i = 0; i < N; i += PrintStep) { std::cout << std::setw(15) << y_points[i] << std::setw(15) << dy_points[i] << std::setw(15) << dfu(x_points[i]) << std::setw(15) << std::abs((dy_points[i] - dfu(x_points[i])) / (dfu(x_points[i] + epsilon)) * 100) << "\n"; } std::cout << std::setw(15) << y_points[N - 1] << std::setw(15) << dy_points[N - 1] << std::setw(15) << dfu(x_points[N - 1]) << std::setw(15) << std::abs((dy_points[N - 1] - dfu(x_points[N - 1])) / (dfu(x_points[N - 1] + epsilon)) * 100) << std::endl; } int main() { { float_v x_i(float_v::IndexType::IndexesFromZero()); for ( unsigned int i = 0; i < x_points.vectorsCount(); ++i, x_i += float_v::Size ) { const float_v x = x_i * h; x_points.vector(i) = x; y_points.vector(i) = fu(x); } } dy_points = Vc::malloc<float, Vc::AlignOnVector>(N + float_v::Size - 1) + (float_v::Size - 1); double speedup; TimeStampCounter timer; { ///////// ignore this part - it only wakes up the CPU //////////////////////////// const float oneOver2h = 0.5f / h; // set borders explicit as up- or downdifferential dy_points[0] = (y_points[1] - y_points[0]) / h; // GCC auto-vectorizes the following loop. It is interesting to see that both Vc::Scalar and // Vc::SSE are faster, though. for ( int i = 1; i < N - 1; ++i) { dy_points[i] = (y_points[i + 1] - y_points[i - 1]) * oneOver2h; } dy_points[N - 1] = (y_points[N - 1] - y_points[N - 2]) / h; } ////////////////////////////////////////////////////////////////////////////////// { std::cout << "\n" << std::setw(60) << "Classical finite difference method" << std::endl; timer.Start(); const float oneOver2h = 0.5f / h; // set borders explicit as up- or downdifferential dy_points[0] = (y_points[1] - y_points[0]) / h; // GCC auto-vectorizes the following loop. It is interesting to see that both Vc::Scalar and // Vc::SSE are faster, though. for ( int i = 1; i < N - 1; ++i) { dy_points[i] = (y_points[i + 1] - y_points[i - 1]) * oneOver2h; } dy_points[N - 1] = (y_points[N - 1] - y_points[N - 2]) / h; timer.Stop(); printResults(); std::cout << "cycle count: " << timer.Cycles() << " | " << static_cast<double>(N * 2) / timer.Cycles() << " FLOP/cycle" << " | " << static_cast<double>(N * 2 * sizeof(float)) / timer.Cycles() << " Byte/cycle" << "\n"; } speedup = timer.Cycles(); { std::cout << std::setw(60) << "Vectorized finite difference method" << std::endl; timer.Start(); // All the differentials require to calculate (r - l) / 2h, where we calculate 1/2h as a // constant before the loop to avoid unnecessary calculations. Note that a good compiler can // already do this for you. const float_v oneOver2h = 0.5f / h; // Calculate the left border dy_points[0] = (y_points[1] - y_points[0]) / h; // Calculate the differentials streaming through the y and dy memory. The picture below // should give an idea of what values in y get read and what values are written to dy in // each iteration: // // y [...................................] // 00001111222233334444555566667777 // 00001111222233334444555566667777 // dy [...................................] // 00001111222233334444555566667777 // // The loop is manually unrolled four times to improve instruction level parallelism and // prefetching on architectures where four vectors fill one cache line. (Note that this // unrolling breaks auto-vectorization of the Vc::Scalar implementation when compiling with // GCC.) for (unsigned int i = 0; i < (y_points.entriesCount() - 2) / float_v::Size; i += 4) { // Prefetches make sure the data which is going to be used in 24/4 iterations is already // in the L1 cache. The prefetchForOneRead additionally instructs the CPU to not evict // these cache lines to L2/L3. Vc::prefetchForOneRead(&y_points[(i + 24) * float_v::Size]); // calculate float_v::Size differentials per (left - right) / 2h const float_v dy0 = (y_points.vector(i + 0, 2) - y_points.vector(i + 0)) * oneOver2h; const float_v dy1 = (y_points.vector(i + 1, 2) - y_points.vector(i + 1)) * oneOver2h; const float_v dy2 = (y_points.vector(i + 2, 2) - y_points.vector(i + 2)) * oneOver2h; const float_v dy3 = (y_points.vector(i + 3, 2) - y_points.vector(i + 3)) * oneOver2h; // Use streaming stores to reduce the required memory bandwidth. Without streaming // stores the CPU would first have to load the cache line, where the store occurs, from // memory into L1, then overwrite the data, and finally write it back to memory. But // since we never actually need the data that the CPU fetched from memory we'd like to // keep that bandwidth free for real work. Streaming stores allow us to issue stores // which the CPU gathers in store buffers to form full cache lines, which then get // written back to memory directly without the costly read. Thus we make better use of // the available memory bandwidth. dy0.store(&dy_points[(i + 0) * float_v::Size + 1], Vc::Streaming); dy1.store(&dy_points[(i + 1) * float_v::Size + 1], Vc::Streaming); dy2.store(&dy_points[(i + 2) * float_v::Size + 1], Vc::Streaming); dy3.store(&dy_points[(i + 3) * float_v::Size + 1], Vc::Streaming); } // Process the last vector. Note that this works for any N because Vc::Memory adds padding // to y_points and dy_points such that the last scalar value is somewhere inside lastVector. // The correct right border value for dy_points is overwritten in the last step unless N is // a multiple of float_v::Size + 2. // y [...................................] // 8888 // 8888 // dy [...................................] // 8888 { const unsigned int i = y_points.vectorsCount() - 1; const float_v left = y_points.vector(i, -2); const float_v right = y_points.lastVector(); ((right - left) * oneOver2h).store(&dy_points[i * float_v::Size - 1], Vc::Unaligned); } // ... and finally the right border dy_points[N - 1] = (y_points[N - 1] - y_points[N - 2]) / h; timer.Stop(); printResults(); std::cout << "cycle count: " << timer.Cycles() << " | " << static_cast<double>(N * 2) / timer.Cycles() << " FLOP/cycle" << " | " << static_cast<double>(N * 2 * sizeof(float)) / timer.Cycles() << " Byte/cycle" << "\n"; } speedup /= timer.Cycles(); std::cout << "Speedup: " << speedup << "\n"; Vc::free(dy_points - float_v::Size + 1); return 0; } <commit_msg>fix argument passing for MSVC and declare constant as sp float<commit_after>/* Copyright (C) 2010 Jochen Gerhard <gerhard@compeng.uni-frankfurt.de> Copyright (C) 2010 Matthias Kretz <kretz@kde.org> Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /*! Finite difference method example We calculate central differences for a given function and compare it to the analytical solution. */ #include <Vc/Vc> #include <iostream> #include <iomanip> #include <cmath> #include "../../tsc.h" #define USE_SCALAR_SINCOS enum { N = 10240000, PrintStep = 1000000 }; static const float epsilon = 1e-7f; static const float lower = 0.f; static const float upper = 40000.f; static const float h = (upper - lower) / N; // dfu is the derivative of fu. This is really easy for sine and cosine: static inline float fu(float x) { return ( std::sin(x) ); } static inline float dfu(float x) { return ( std::cos(x) ); } static inline Vc::float_v fu(Vc::float_v::AsArg x) { #ifdef USE_SCALAR_SINCOS Vc::float_v r; for (size_t i = 0; i < Vc::float_v::Size; ++i) { r[i] = std::sin(x[i]); } return r; #else return Vc::sin(x); #endif } static inline Vc::float_v dfu(Vc::float_v::AsArg x) { #ifdef USE_SCALAR_SINCOS Vc::float_v r; for (size_t i = 0; i < Vc::float_v::Size; ++i) { r[i] = std::cos(x[i]); } return r; #else return Vc::cos(x); #endif } using Vc::float_v; // It is important for this example that the following variables (especially dy_points) are global // variables. Else the compiler can optimze all calculations of dy away except for the few places // where the value is used in printResults. Vc::Memory<float_v, N> x_points; Vc::Memory<float_v, N> y_points; float *VC_RESTRICT dy_points; void printResults() { std::cout << "------------------------------------------------------------\n" << std::setw(15) << "fu(x_i)" << std::setw(15) << "FD fu'(x_i)" << std::setw(15) << "SYM fu'(x)" << std::setw(15) << "error %\n"; for (int i = 0; i < N; i += PrintStep) { std::cout << std::setw(15) << y_points[i] << std::setw(15) << dy_points[i] << std::setw(15) << dfu(x_points[i]) << std::setw(15) << std::abs((dy_points[i] - dfu(x_points[i])) / (dfu(x_points[i] + epsilon)) * 100) << "\n"; } std::cout << std::setw(15) << y_points[N - 1] << std::setw(15) << dy_points[N - 1] << std::setw(15) << dfu(x_points[N - 1]) << std::setw(15) << std::abs((dy_points[N - 1] - dfu(x_points[N - 1])) / (dfu(x_points[N - 1] + epsilon)) * 100) << std::endl; } int main() { { float_v x_i(float_v::IndexType::IndexesFromZero()); for ( unsigned int i = 0; i < x_points.vectorsCount(); ++i, x_i += float_v::Size ) { const float_v x = x_i * h; x_points.vector(i) = x; y_points.vector(i) = fu(x); } } dy_points = Vc::malloc<float, Vc::AlignOnVector>(N + float_v::Size - 1) + (float_v::Size - 1); double speedup; TimeStampCounter timer; { ///////// ignore this part - it only wakes up the CPU //////////////////////////// const float oneOver2h = 0.5f / h; // set borders explicit as up- or downdifferential dy_points[0] = (y_points[1] - y_points[0]) / h; // GCC auto-vectorizes the following loop. It is interesting to see that both Vc::Scalar and // Vc::SSE are faster, though. for ( int i = 1; i < N - 1; ++i) { dy_points[i] = (y_points[i + 1] - y_points[i - 1]) * oneOver2h; } dy_points[N - 1] = (y_points[N - 1] - y_points[N - 2]) / h; } ////////////////////////////////////////////////////////////////////////////////// { std::cout << "\n" << std::setw(60) << "Classical finite difference method" << std::endl; timer.Start(); const float oneOver2h = 0.5f / h; // set borders explicit as up- or downdifferential dy_points[0] = (y_points[1] - y_points[0]) / h; // GCC auto-vectorizes the following loop. It is interesting to see that both Vc::Scalar and // Vc::SSE are faster, though. for ( int i = 1; i < N - 1; ++i) { dy_points[i] = (y_points[i + 1] - y_points[i - 1]) * oneOver2h; } dy_points[N - 1] = (y_points[N - 1] - y_points[N - 2]) / h; timer.Stop(); printResults(); std::cout << "cycle count: " << timer.Cycles() << " | " << static_cast<double>(N * 2) / timer.Cycles() << " FLOP/cycle" << " | " << static_cast<double>(N * 2 * sizeof(float)) / timer.Cycles() << " Byte/cycle" << "\n"; } speedup = timer.Cycles(); { std::cout << std::setw(60) << "Vectorized finite difference method" << std::endl; timer.Start(); // All the differentials require to calculate (r - l) / 2h, where we calculate 1/2h as a // constant before the loop to avoid unnecessary calculations. Note that a good compiler can // already do this for you. const float_v oneOver2h = 0.5f / h; // Calculate the left border dy_points[0] = (y_points[1] - y_points[0]) / h; // Calculate the differentials streaming through the y and dy memory. The picture below // should give an idea of what values in y get read and what values are written to dy in // each iteration: // // y [...................................] // 00001111222233334444555566667777 // 00001111222233334444555566667777 // dy [...................................] // 00001111222233334444555566667777 // // The loop is manually unrolled four times to improve instruction level parallelism and // prefetching on architectures where four vectors fill one cache line. (Note that this // unrolling breaks auto-vectorization of the Vc::Scalar implementation when compiling with // GCC.) for (unsigned int i = 0; i < (y_points.entriesCount() - 2) / float_v::Size; i += 4) { // Prefetches make sure the data which is going to be used in 24/4 iterations is already // in the L1 cache. The prefetchForOneRead additionally instructs the CPU to not evict // these cache lines to L2/L3. Vc::prefetchForOneRead(&y_points[(i + 24) * float_v::Size]); // calculate float_v::Size differentials per (left - right) / 2h const float_v dy0 = (y_points.vector(i + 0, 2) - y_points.vector(i + 0)) * oneOver2h; const float_v dy1 = (y_points.vector(i + 1, 2) - y_points.vector(i + 1)) * oneOver2h; const float_v dy2 = (y_points.vector(i + 2, 2) - y_points.vector(i + 2)) * oneOver2h; const float_v dy3 = (y_points.vector(i + 3, 2) - y_points.vector(i + 3)) * oneOver2h; // Use streaming stores to reduce the required memory bandwidth. Without streaming // stores the CPU would first have to load the cache line, where the store occurs, from // memory into L1, then overwrite the data, and finally write it back to memory. But // since we never actually need the data that the CPU fetched from memory we'd like to // keep that bandwidth free for real work. Streaming stores allow us to issue stores // which the CPU gathers in store buffers to form full cache lines, which then get // written back to memory directly without the costly read. Thus we make better use of // the available memory bandwidth. dy0.store(&dy_points[(i + 0) * float_v::Size + 1], Vc::Streaming); dy1.store(&dy_points[(i + 1) * float_v::Size + 1], Vc::Streaming); dy2.store(&dy_points[(i + 2) * float_v::Size + 1], Vc::Streaming); dy3.store(&dy_points[(i + 3) * float_v::Size + 1], Vc::Streaming); } // Process the last vector. Note that this works for any N because Vc::Memory adds padding // to y_points and dy_points such that the last scalar value is somewhere inside lastVector. // The correct right border value for dy_points is overwritten in the last step unless N is // a multiple of float_v::Size + 2. // y [...................................] // 8888 // 8888 // dy [...................................] // 8888 { const unsigned int i = y_points.vectorsCount() - 1; const float_v left = y_points.vector(i, -2); const float_v right = y_points.lastVector(); ((right - left) * oneOver2h).store(&dy_points[i * float_v::Size - 1], Vc::Unaligned); } // ... and finally the right border dy_points[N - 1] = (y_points[N - 1] - y_points[N - 2]) / h; timer.Stop(); printResults(); std::cout << "cycle count: " << timer.Cycles() << " | " << static_cast<double>(N * 2) / timer.Cycles() << " FLOP/cycle" << " | " << static_cast<double>(N * 2 * sizeof(float)) / timer.Cycles() << " Byte/cycle" << "\n"; } speedup /= timer.Cycles(); std::cout << "Speedup: " << speedup << "\n"; Vc::free(dy_points - float_v::Size + 1); return 0; } <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * 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 <modules/space/translation/horizonstranslation.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/util/updatestructures.h> #include <ghoul/fmt.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/lua/ghoul_lua.h> #include <ghoul/lua/lua_helper.h> #include <filesystem> #include <fstream> namespace { constexpr const char* _loggerCat = "HorizonsTranslation"; constexpr int8_t CurrentCacheVersion = 1; } // namespace namespace { constexpr openspace::properties::Property::PropertyInfo HorizonsTextFileInfo = { "HorizonsTextFile", "Horizons Text File", "This value is the path to the text file or files generated by Horizons with " "observer range and Galactiv longitude and latitude for different timestamps." }; struct [[codegen::Dictionary(HorizonsTranslation)]] Parameters { // [[codegen::verbatim(HorizonsTextFileInfo.description)]] std::variant<std::string, std::vector<std::string>> horizonsTextFile; }; #include "horizonstranslation_codegen.cpp" } // namespace namespace openspace { documentation::Documentation HorizonsTranslation::Documentation() { return codegen::doc<Parameters>("base_transform_translation_horizons"); } HorizonsTranslation::HorizonsTranslation() : _horizonsTextFiles(HorizonsTextFileInfo) { addProperty(_horizonsTextFiles); _horizonsTextFiles.onChange([&](){ requireUpdate(); notifyObservers(); loadData(); }); } HorizonsTranslation::HorizonsTranslation(const ghoul::Dictionary& dictionary) : HorizonsTranslation() { const Parameters p = codegen::bake<Parameters>(dictionary); if (std::holds_alternative<std::string>(p.horizonsTextFile)) { std::string file = std::get<std::string>(p.horizonsTextFile); if (!std::filesystem::is_regular_file(absPath(file))) { LWARNING(fmt::format("The Horizons text file '{}' could not be found", file)); return; } std::vector<std::string> files; files.reserve(1); files.push_back(file); _horizonsTextFiles.set(files); } else if (std::holds_alternative<std::vector<std::string>>(p.horizonsTextFile)) { std::vector<std::string> files = std::get<std::vector<std::string>>(p.horizonsTextFile); for (std::string file : files) { if (!std::filesystem::is_regular_file(absPath(file))) { LWARNING(fmt::format("The Horizons text file '{}' could not be found", file) ); return; } } _horizonsTextFiles.set(files); } else { throw ghoul::MissingCaseException(); } } glm::dvec3 HorizonsTranslation::position(const UpdateData& data) const { glm::dvec3 interpolatedPos = glm::dvec3(0.0); auto lastBefore = _timeline.lastKeyframeBefore(data.time.j2000Seconds(), true); auto firstAfter = _timeline.firstKeyframeAfter(data.time.j2000Seconds(), false); if (lastBefore && firstAfter) { // We're inbetween first and last value. double timelineDiff = firstAfter->timestamp - lastBefore->timestamp; double timeDiff = data.time.j2000Seconds() - lastBefore->timestamp; double diff = (timelineDiff > DBL_EPSILON) ? timeDiff / timelineDiff : 0.0; glm::dvec3 dir = firstAfter->data - lastBefore->data; interpolatedPos = lastBefore->data + dir * diff; } else if (lastBefore) { // Requesting a time after last value. Return last known position. interpolatedPos = lastBefore->data; } else if (firstAfter) { // Requesting a time before first value. Return last known position. interpolatedPos = firstAfter->data; } return interpolatedPos; } void HorizonsTranslation::loadData() { for (const std::string filePath : _horizonsTextFiles.value()) { std::filesystem::path file = absPath(filePath); if (!std::filesystem::is_regular_file(file)) { LWARNING(fmt::format("The Horizons text file '{}' could not be found", file)); return; } std::filesystem::path cachedFile = FileSys.cacheManager()->cachedFilename(file); bool hasCachedFile = std::filesystem::is_regular_file(cachedFile); if (hasCachedFile) { LINFO(fmt::format( "Cached file '{}' used for Horizon file '{}'", cachedFile, file )); if (loadCachedFile(cachedFile)) { return; } else { FileSys.cacheManager()->removeCacheFile(file); // Intentional fall-through to the 'else' computation to generate the // cache file for the next run } } else { LINFO(fmt::format("Cache for Horizon file '{}' not found", file)); } LINFO(fmt::format("Loading Horizon file '{}'", file)); readHorizonsTextFile(file); LINFO("Saving cache"); saveCachedFile(cachedFile); } } void HorizonsTranslation::readHorizonsTextFile(const std::filesystem::path& file) { std::ifstream fileStream(file); if (!fileStream.good()) { LERROR(fmt::format( "Failed to open Horizons text file '{}'", file )); return; } // The beginning of a Horizons file has a header with a lot of information about the // query that we do not care about. Ignore everything until data starts, including // the row marked by $$SOE (i.e. Start Of Ephemerides). std::string line; while (line[0] != '$') { std::getline(fileStream, line); } // Read data line by line until $$EOE (i.e. End Of Ephemerides). // Skip the rest of the file. std::getline(fileStream, line); while (line[0] != '$') { std::stringstream str(line); std::string date; std::string time; double range = 0; double gLon = 0; double gLat = 0; // File is structured by: // YYYY-MM-DD // HH:MM:SS // Range-to-observer (km) // Range-delta (km/s) -- suppressed! // Galactic Longitude (degrees) // Galactic Latitude (degrees) str >> date >> time >> range >> gLon >> gLat; // Convert date and time to seconds after 2000 // and pos to Galactic positions in meter from Observer. std::string timeString = date + " " + time; double timeInJ2000 = Time::convertTime(timeString); glm::dvec3 gPos = glm::dvec3( 1000 * range * cos(glm::radians(gLat)) * cos(glm::radians(gLon)), 1000 * range * cos(glm::radians(gLat)) * sin(glm::radians(gLon)), 1000 * range * sin(glm::radians(gLat)) ); // Add position to stored timeline. _timeline.addKeyframe(timeInJ2000, std::move(gPos)); std::getline(fileStream, line); } fileStream.close(); } bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { std::ifstream fileStream(file, std::ifstream::binary); if (!fileStream.good()) { LERROR(fmt::format("Error opening file {} for loading cache file", file)); return false; } // Check the caching version int8_t version = 0; fileStream.read(reinterpret_cast<char*>(&version), sizeof(int8_t)); if (version != CurrentCacheVersion) { LINFO("The format of the cached file has changed: deleting old cache"); fileStream.close(); FileSys.cacheManager()->removeCacheFile(file); return false; } // Read how many keyframes to read int32_t nKeyframes = 0; fileStream.read(reinterpret_cast<char*>(&nKeyframes), sizeof(int32_t)); if (nKeyframes == 0) { throw ghoul::RuntimeError("Error reading cache: No values were loaded"); } // Read the values in same order as they were written for (int i = 0; i < nKeyframes; ++i) { double timestamp, x, y, z; glm::dvec3 gPos; // Timestamp fileStream.read(reinterpret_cast<char*>(&timestamp), sizeof(double)); // Position vector components fileStream.read(reinterpret_cast<char*>(&x), sizeof(double)); fileStream.read(reinterpret_cast<char*>(&y), sizeof(double)); fileStream.read(reinterpret_cast<char*>(&z), sizeof(double)); // Recreate the position vector gPos = glm::dvec3(x, y, z); // Add keyframe in timeline _timeline.addKeyframe(timestamp, std::move(gPos)); } return fileStream.good(); } void HorizonsTranslation::saveCachedFile(const std::filesystem::path& file) const { std::ofstream fileStream(file, std::ofstream::binary); if (!fileStream.good()) { LERROR(fmt::format("Error opening file {} for save cache file", file)); return; } // Write which version of caching that is used fileStream.write( reinterpret_cast<const char*>(&CurrentCacheVersion), sizeof(int8_t) ); // Write how many keyframes are to be written int32_t nKeyframes = static_cast<int32_t>(_timeline.nKeyframes()); if (nKeyframes == 0) { throw ghoul::RuntimeError("Error writing cache: No values were loaded"); } fileStream.write(reinterpret_cast<const char*>(&nKeyframes), sizeof(int32_t)); // Write data std::deque<Keyframe<glm::dvec3>> keyframes = _timeline.keyframes(); for (int i = 0; i < nKeyframes; i++) { // First write timestamp fileStream.write(reinterpret_cast<const char*>( &keyframes[i].timestamp), sizeof(double) ); // and then the components of the position vector one by one fileStream.write(reinterpret_cast<const char*>( &keyframes[i].data.x), sizeof(double) ); fileStream.write(reinterpret_cast<const char*>( &keyframes[i].data.y), sizeof(double) ); fileStream.write(reinterpret_cast<const char*>( &keyframes[i].data.z), sizeof(double) ); } } } // namespace openspace <commit_msg>Fix so all horizons files in list gets loaded<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * 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 <modules/space/translation/horizonstranslation.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/util/updatestructures.h> #include <ghoul/fmt.h> #include <ghoul/filesystem/cachemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/lua/ghoul_lua.h> #include <ghoul/lua/lua_helper.h> #include <filesystem> #include <fstream> namespace { constexpr const char* _loggerCat = "HorizonsTranslation"; constexpr int8_t CurrentCacheVersion = 1; } // namespace namespace { constexpr openspace::properties::Property::PropertyInfo HorizonsTextFileInfo = { "HorizonsTextFile", "Horizons Text File", "This value is the path to the text file or files generated by Horizons with " "observer range and Galactiv longitude and latitude for different timestamps." }; struct [[codegen::Dictionary(HorizonsTranslation)]] Parameters { // [[codegen::verbatim(HorizonsTextFileInfo.description)]] std::variant<std::string, std::vector<std::string>> horizonsTextFile; }; #include "horizonstranslation_codegen.cpp" } // namespace namespace openspace { documentation::Documentation HorizonsTranslation::Documentation() { return codegen::doc<Parameters>("base_transform_translation_horizons"); } HorizonsTranslation::HorizonsTranslation() : _horizonsTextFiles(HorizonsTextFileInfo) { addProperty(_horizonsTextFiles); _horizonsTextFiles.onChange([&](){ requireUpdate(); notifyObservers(); loadData(); }); } HorizonsTranslation::HorizonsTranslation(const ghoul::Dictionary& dictionary) : HorizonsTranslation() { const Parameters p = codegen::bake<Parameters>(dictionary); if (std::holds_alternative<std::string>(p.horizonsTextFile)) { std::string file = std::get<std::string>(p.horizonsTextFile); if (!std::filesystem::is_regular_file(absPath(file))) { LWARNING(fmt::format("The Horizons text file '{}' could not be found", file)); return; } std::vector<std::string> files; files.reserve(1); files.push_back(file); _horizonsTextFiles.set(files); } else if (std::holds_alternative<std::vector<std::string>>(p.horizonsTextFile)) { std::vector<std::string> files = std::get<std::vector<std::string>>(p.horizonsTextFile); for (std::string file : files) { if (!std::filesystem::is_regular_file(absPath(file))) { LWARNING(fmt::format("The Horizons text file '{}' could not be found", file) ); return; } } _horizonsTextFiles.set(files); } else { throw ghoul::MissingCaseException(); } } glm::dvec3 HorizonsTranslation::position(const UpdateData& data) const { glm::dvec3 interpolatedPos = glm::dvec3(0.0); auto lastBefore = _timeline.lastKeyframeBefore(data.time.j2000Seconds(), true); auto firstAfter = _timeline.firstKeyframeAfter(data.time.j2000Seconds(), false); if (lastBefore && firstAfter) { // We're inbetween first and last value. double timelineDiff = firstAfter->timestamp - lastBefore->timestamp; double timeDiff = data.time.j2000Seconds() - lastBefore->timestamp; double diff = (timelineDiff > DBL_EPSILON) ? timeDiff / timelineDiff : 0.0; glm::dvec3 dir = firstAfter->data - lastBefore->data; interpolatedPos = lastBefore->data + dir * diff; } else if (lastBefore) { // Requesting a time after last value. Return last known position. interpolatedPos = lastBefore->data; } else if (firstAfter) { // Requesting a time before first value. Return last known position. interpolatedPos = firstAfter->data; } return interpolatedPos; } void HorizonsTranslation::loadData() { for (const std::string filePath : _horizonsTextFiles.value()) { std::filesystem::path file = absPath(filePath); if (!std::filesystem::is_regular_file(file)) { LWARNING(fmt::format("The Horizons text file '{}' could not be found", file)); return; } std::filesystem::path cachedFile = FileSys.cacheManager()->cachedFilename(file); bool hasCachedFile = std::filesystem::is_regular_file(cachedFile); if (hasCachedFile) { LINFO(fmt::format( "Cached file '{}' used for Horizon file '{}'", cachedFile, file )); if (loadCachedFile(cachedFile)) { continue; } else { FileSys.cacheManager()->removeCacheFile(file); // Intentional fall-through to the 'else' computation to generate the // cache file for the next run } } else { LINFO(fmt::format("Cache for Horizon file '{}' not found", file)); } LINFO(fmt::format("Loading Horizon file '{}'", file)); readHorizonsTextFile(file); LINFO("Saving cache"); saveCachedFile(cachedFile); } } void HorizonsTranslation::readHorizonsTextFile(const std::filesystem::path& file) { std::ifstream fileStream(file); if (!fileStream.good()) { LERROR(fmt::format( "Failed to open Horizons text file '{}'", file )); return; } // The beginning of a Horizons file has a header with a lot of information about the // query that we do not care about. Ignore everything until data starts, including // the row marked by $$SOE (i.e. Start Of Ephemerides). std::string line; while (line[0] != '$') { std::getline(fileStream, line); } // Read data line by line until $$EOE (i.e. End Of Ephemerides). // Skip the rest of the file. std::getline(fileStream, line); while (line[0] != '$') { std::stringstream str(line); std::string date; std::string time; double range = 0; double gLon = 0; double gLat = 0; // File is structured by: // YYYY-MM-DD // HH:MM:SS // Range-to-observer (km) // Range-delta (km/s) -- suppressed! // Galactic Longitude (degrees) // Galactic Latitude (degrees) str >> date >> time >> range >> gLon >> gLat; // Convert date and time to seconds after 2000 // and pos to Galactic positions in meter from Observer. std::string timeString = date + " " + time; double timeInJ2000 = Time::convertTime(timeString); glm::dvec3 gPos = glm::dvec3( 1000 * range * cos(glm::radians(gLat)) * cos(glm::radians(gLon)), 1000 * range * cos(glm::radians(gLat)) * sin(glm::radians(gLon)), 1000 * range * sin(glm::radians(gLat)) ); // Add position to stored timeline. _timeline.addKeyframe(timeInJ2000, std::move(gPos)); std::getline(fileStream, line); } fileStream.close(); } bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { std::ifstream fileStream(file, std::ifstream::binary); if (!fileStream.good()) { LERROR(fmt::format("Error opening file {} for loading cache file", file)); return false; } // Check the caching version int8_t version = 0; fileStream.read(reinterpret_cast<char*>(&version), sizeof(int8_t)); if (version != CurrentCacheVersion) { LINFO("The format of the cached file has changed: deleting old cache"); fileStream.close(); FileSys.cacheManager()->removeCacheFile(file); return false; } // Read how many keyframes to read int32_t nKeyframes = 0; fileStream.read(reinterpret_cast<char*>(&nKeyframes), sizeof(int32_t)); if (nKeyframes == 0) { throw ghoul::RuntimeError("Error reading cache: No values were loaded"); } // Read the values in same order as they were written for (int i = 0; i < nKeyframes; ++i) { double timestamp, x, y, z; glm::dvec3 gPos; // Timestamp fileStream.read(reinterpret_cast<char*>(&timestamp), sizeof(double)); // Position vector components fileStream.read(reinterpret_cast<char*>(&x), sizeof(double)); fileStream.read(reinterpret_cast<char*>(&y), sizeof(double)); fileStream.read(reinterpret_cast<char*>(&z), sizeof(double)); // Recreate the position vector gPos = glm::dvec3(x, y, z); // Add keyframe in timeline _timeline.addKeyframe(timestamp, std::move(gPos)); } return fileStream.good(); } void HorizonsTranslation::saveCachedFile(const std::filesystem::path& file) const { std::ofstream fileStream(file, std::ofstream::binary); if (!fileStream.good()) { LERROR(fmt::format("Error opening file {} for save cache file", file)); return; } // Write which version of caching that is used fileStream.write( reinterpret_cast<const char*>(&CurrentCacheVersion), sizeof(int8_t) ); // Write how many keyframes are to be written int32_t nKeyframes = static_cast<int32_t>(_timeline.nKeyframes()); if (nKeyframes == 0) { throw ghoul::RuntimeError("Error writing cache: No values were loaded"); } fileStream.write(reinterpret_cast<const char*>(&nKeyframes), sizeof(int32_t)); // Write data std::deque<Keyframe<glm::dvec3>> keyframes = _timeline.keyframes(); for (int i = 0; i < nKeyframes; i++) { // First write timestamp fileStream.write(reinterpret_cast<const char*>( &keyframes[i].timestamp), sizeof(double) ); // and then the components of the position vector one by one fileStream.write(reinterpret_cast<const char*>( &keyframes[i].data.x), sizeof(double) ); fileStream.write(reinterpret_cast<const char*>( &keyframes[i].data.y), sizeof(double) ); fileStream.write(reinterpret_cast<const char*>( &keyframes[i].data.z), sizeof(double) ); } } } // namespace openspace <|endoftext|>
<commit_before>#include "HedgeLib/Offsets.h" #include "HedgeLib/Endian.h" void hl_FixOffset32(uint32_t* off, const void* data, bool isBigEndian) { // Null pointers should remain null if (*off == 0) { #ifdef x64 *off = hl_x64AddAbsPtr32(0); #endif return; } // Endian swap offset if (isBigEndian) hl_SwapUInt32(off); // Get absolute pointer uintptr_t absPtr = (reinterpret_cast <uintptr_t>(data) + *off); // Fix offset #ifdef x86 *off = static_cast<uint32_t>(absPtr); #elif x64 *off = hl_x64AddAbsPtr32(absPtr); #endif } void hl_FixOffset64(uint64_t* off, const void* data, bool isBigEndian) { // Null pointers should remain null if (*off == 0) return; // Endian swap offset if (isBigEndian) hl_SwapUInt64(off); // Get absolute pointer uintptr_t absPtr = (reinterpret_cast <uintptr_t>(data) + *off); // Fix offset *off = static_cast<uint64_t>(absPtr); } hl_OffsetTable* hl_CreateOffsetTable() { return new hl_OffsetTable(); } void hl_AddOffset(hl_OffsetTable* offTable, long offset) { offTable->push_back(offset); } long* hl_GetOffsetsPtr(hl_OffsetTable* offTable) { return offTable->data(); } size_t hl_GetOffsetCount(const hl_OffsetTable* offTable) { return offTable->size(); } void hl_GetOffsets(hl_OffsetTable* offTable, long** offsets, size_t* count) { *offsets = offTable->data(); *count = offTable->size(); } void hl_DestroyOffsetTable(hl_OffsetTable* offTable) { delete offTable; } #ifdef x64 std::vector<uintptr_t> ptrs = { 0 }; static std::vector<bool> ptrFlags = { false }; static size_t nextFreeIndex = 1; uintptr_t hl_x64GetAbsPtr32(hl_DataOff32 index) { return ptrs[index]; } hl_DataOff32 hl_x64AddAbsPtr32(uintptr_t ptr) { hl_DataOff32 index = static_cast<hl_DataOff32>(nextFreeIndex); if (nextFreeIndex == ptrs.size()) { // No "free" (unused) spots available; Add pointer ptrs.push_back(ptr); ptrFlags.push_back(true); ++nextFreeIndex; } else { // Set pointer ptrs[nextFreeIndex] = ptr; ptrFlags[nextFreeIndex] = true; // Determine next free index while (++nextFreeIndex < ptrs.size()) { if (!ptrFlags[nextFreeIndex]) break; } } return index; } void hl_x64SetAbsPtr32(hl_DataOff32 index, uintptr_t ptr) { ptrs[index] = ptr; } void hl_x64RemoveAbsPtr32(hl_DataOff32 index) { if (index == 0) return; if (index == (ptrs.size() - 1) && nextFreeIndex == ptrs.size()) { ptrs.pop_back(); ptrFlags.pop_back(); --nextFreeIndex; } else { ptrFlags[index] = false; if (index < nextFreeIndex) { nextFreeIndex = index; } } } #endif <commit_msg>x86 FixOffset64 casting fix<commit_after>#include "HedgeLib/Offsets.h" #include "HedgeLib/Endian.h" void hl_FixOffset32(uint32_t* off, const void* data, bool isBigEndian) { // Null pointers should remain null if (*off == 0) { #ifdef x64 *off = hl_x64AddAbsPtr32(0); #endif return; } // Endian swap offset if (isBigEndian) hl_SwapUInt32(off); // Get absolute pointer uintptr_t absPtr = (reinterpret_cast <uintptr_t>(data) + *off); // Fix offset #ifdef x86 *off = static_cast<uint32_t>(absPtr); #elif x64 *off = hl_x64AddAbsPtr32(absPtr); #endif } void hl_FixOffset64(uint64_t* off, const void* data, bool isBigEndian) { // Null pointers should remain null if (*off == 0) return; // Endian swap offset if (isBigEndian) hl_SwapUInt64(off); // Get absolute pointer uintptr_t absPtr = (reinterpret_cast<uintptr_t>( data) + static_cast<uintptr_t>(*off)); // Fix offset *off = static_cast<uint64_t>(absPtr); } hl_OffsetTable* hl_CreateOffsetTable() { return new hl_OffsetTable(); } void hl_AddOffset(hl_OffsetTable* offTable, long offset) { offTable->push_back(offset); } long* hl_GetOffsetsPtr(hl_OffsetTable* offTable) { return offTable->data(); } size_t hl_GetOffsetCount(const hl_OffsetTable* offTable) { return offTable->size(); } void hl_GetOffsets(hl_OffsetTable* offTable, long** offsets, size_t* count) { *offsets = offTable->data(); *count = offTable->size(); } void hl_DestroyOffsetTable(hl_OffsetTable* offTable) { delete offTable; } #ifdef x64 std::vector<uintptr_t> ptrs = { 0 }; static std::vector<bool> ptrFlags = { false }; static size_t nextFreeIndex = 1; uintptr_t hl_x64GetAbsPtr32(hl_DataOff32 index) { return ptrs[index]; } hl_DataOff32 hl_x64AddAbsPtr32(uintptr_t ptr) { hl_DataOff32 index = static_cast<hl_DataOff32>(nextFreeIndex); if (nextFreeIndex == ptrs.size()) { // No "free" (unused) spots available; Add pointer ptrs.push_back(ptr); ptrFlags.push_back(true); ++nextFreeIndex; } else { // Set pointer ptrs[nextFreeIndex] = ptr; ptrFlags[nextFreeIndex] = true; // Determine next free index while (++nextFreeIndex < ptrs.size()) { if (!ptrFlags[nextFreeIndex]) break; } } return index; } void hl_x64SetAbsPtr32(hl_DataOff32 index, uintptr_t ptr) { ptrs[index] = ptr; } void hl_x64RemoveAbsPtr32(hl_DataOff32 index) { if (index == 0) return; if (index == (ptrs.size() - 1) && nextFreeIndex == ptrs.size()) { ptrs.pop_back(); ptrFlags.pop_back(); --nextFreeIndex; } else { ptrFlags[index] = false; if (index < nextFreeIndex) { nextFreeIndex = index; } } } #endif <|endoftext|>
<commit_before>#include "aten.h" #include "atenscene.h" #include <cmdline.h> struct Options { std::string input; std::string output; }; bool parseOption( int argc, char* argv[], cmdline::parser& cmd, Options& opt) { { cmd.add<std::string>("input", 'i', "input filename", true); cmd.add<std::string>("output", 'o', "output filename base", false, "result"); cmd.add<std::string>("help", '?', "print usage", false); } bool isCmdOk = cmd.parse(argc, argv); if (cmd.exist("help")) { std::cerr << cmd.usage(); return false; } if (!isCmdOk) { std::cerr << cmd.error() << std::endl << cmd.usage(); return false; } if (cmd.exist("input")) { opt.input = cmd.get<std::string>("input"); } else { std::cerr << cmd.error() << std::endl << cmd.usage(); return false; } if (cmd.exist("output")) { opt.output = cmd.get<std::string>("output"); } else { // TODO opt.output = "result.sbvh"; } return true; } int main(int argc, char* argv[]) { Options opt; cmdline::parser cmd; if (!parseOption(argc, argv, cmd, opt)) { return 0; } aten::window::SetCurrentDirectoryFromExe(); aten::AssetManager::suppressWarnings(); auto obj = aten::ObjLoader::load(opt.input); if (!obj) { // TODO return 0; } // Not use. // But specify internal accelerator type in constructor... aten::AcceleratedScene<aten::sbvh> scene; try { obj->exportInternalAccelTree(opt.output.c_str()); } catch (std::exception* e) { // TODO return 0; } return 1; } <commit_msg>Modify to export separated data.<commit_after>#include "aten.h" #include "atenscene.h" #include <cmdline.h> struct Options { std::string input; std::string output; }; bool parseOption( int argc, char* argv[], cmdline::parser& cmd, Options& opt) { { cmd.add<std::string>("input", 'i', "input filename", true); cmd.add<std::string>("output", 'o', "output filename base", false, "result"); cmd.add<std::string>("help", '?', "print usage", false); } bool isCmdOk = cmd.parse(argc, argv); if (cmd.exist("help")) { std::cerr << cmd.usage(); return false; } if (!isCmdOk) { std::cerr << cmd.error() << std::endl << cmd.usage(); return false; } if (cmd.exist("input")) { opt.input = cmd.get<std::string>("input"); } else { std::cerr << cmd.error() << std::endl << cmd.usage(); return false; } if (cmd.exist("output")) { opt.output = cmd.get<std::string>("output"); } else { // TODO opt.output = "result.sbvh"; } return true; } int main(int argc, char* argv[]) { Options opt; cmdline::parser cmd; if (!parseOption(argc, argv, cmd, opt)) { return 0; } aten::window::SetCurrentDirectoryFromExe(); aten::AssetManager::suppressWarnings(); // TODO // Specify material by command line... auto emit = new aten::emissive(aten::vec3(1)); aten::AssetManager::registerMtrl("light", emit); std::vector<aten::object*> objs; aten::ObjLoader::load(objs, opt.input); if (objs.empty()) { // TODO return 0; } // Not use. // But specify internal accelerator type in constructor... aten::AcceleratedScene<aten::sbvh> scene; try { static char buf[2048] = { 0 }; for (int i = 0; i < objs.size(); i++) { auto obj = objs[i]; std::string output; if (i == 0) { output = opt.output; } else { // TODO sprintf(buf, "%d_%s\0", i, opt.output.c_str()); output = std::string(buf); } obj->exportInternalAccelTree(output.c_str()); } } catch (const std::exception& e) { // TODO return 0; } return 1; } <|endoftext|>
<commit_before>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <gmock/gmock.h> #include <franka/exception.h> #include <franka/gripper.h> #include "helpers.h" #include "mock_server.h" using franka::CommandException; using franka::Gripper; using franka::GripperState; using franka::IncompatibleVersionException; using franka::Network; using namespace research_interface::gripper; template <typename T> class GripperCommand : public ::testing::Test { public: using TCommand = T; bool executeCommand(Gripper& gripper); typename T::Request getExpected(); typename T::Status getSuccess(); bool compare(const typename T::Request& request_one, const typename T::Request& request_two); typename T::Response createResponse(const typename T::Request& request, const typename T::Status status); }; template <typename T> typename T::Status GripperCommand<T>::getSuccess() { return T::Status::kSuccess; } template <typename T> bool GripperCommand<T>::compare(const typename T::Request&, const typename T::Request&) { return true; } template <> bool GripperCommand<Grasp>::compare(const Grasp::Request& request_one, const Grasp::Request& request_two) { return request_one.width == request_two.width && request_one.speed == request_two.speed && request_one.force == request_two.force; } template <> bool GripperCommand<Move>::compare(const Move::Request& request_one, const Move::Request& request_two) { return request_one.width == request_two.width && request_one.speed == request_two.speed; } template <typename T> typename T::Request GripperCommand<T>::getExpected() { return typename T::Request(); } template <> Move::Request GripperCommand<Move>::getExpected() { double width = 0.05; double speed = 0.1; return Move::Request(width, speed); } template <> Grasp::Request GripperCommand<Grasp>::getExpected() { double width = 0.05; double speed = 0.1; double force = 400.0; return Grasp::Request(width, speed, force); } template <> bool GripperCommand<Move>::executeCommand(Gripper& gripper) { double width = 0.05; double speed = 0.1; return gripper.move(width, speed); } template <> bool GripperCommand<Grasp>::executeCommand(Gripper& gripper) { double width = 0.05; double speed = 0.1; double force = 400.0; return gripper.grasp(width, speed, force); } template <> bool GripperCommand<Stop>::executeCommand(Gripper& gripper) { return gripper.stop(); } template <> bool GripperCommand<Homing>::executeCommand(Gripper& gripper) { return gripper.homing(); } template <typename T> typename T::Response GripperCommand<T>::createResponse(const typename T::Request&, const typename T::Status status) { return typename T::Response(status); } using CommandTypes = ::testing::Types<Homing, Move, Grasp, Stop>; TYPED_TEST_CASE(GripperCommand, CommandTypes); TYPED_TEST(GripperCommand, CanSendAndReceiveSuccess) { GripperMockServer server; Gripper gripper("127.0.0.1"); server .waitForCommand<typename TestFixture::TCommand>( [this](const typename TestFixture::TCommand::Request& request) -> typename TestFixture::TCommand::Response { EXPECT_TRUE(this->compare(request, this->getExpected())); return this->createResponse(request, this->getSuccess()); }) .spinOnce(); EXPECT_NO_THROW(TestFixture::executeCommand(gripper)); } TYPED_TEST(GripperCommand, CanSendAndReceiveFail) { GripperMockServer server; Gripper gripper("127.0.0.1"); server .waitForCommand<typename TestFixture::TCommand>( [this](const typename TestFixture::TCommand::Request& request) -> typename TestFixture::TCommand::Response { EXPECT_TRUE(this->compare(request, this->getExpected())); return this->createResponse(request, TestFixture::TCommand::Status::kFail); }) .spinOnce(); EXPECT_THROW(TestFixture::executeCommand(gripper), CommandException); } TYPED_TEST(GripperCommand, CanSendAndReceiveUnsucessful) { GripperMockServer server; Gripper gripper("127.0.0.1"); server .waitForCommand<typename TestFixture::TCommand>( [this](const typename TestFixture::TCommand::Request& request) -> typename TestFixture::TCommand::Response { EXPECT_TRUE(this->compare(request, this->getExpected())); return this->createResponse(request, TestFixture::TCommand::Status::kUnsuccessful); }) .spinOnce(); EXPECT_FALSE(TestFixture::executeCommand(gripper)); } <commit_msg>Run clang-format<commit_after>// Copyright (c) 2017 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <gmock/gmock.h> #include <franka/exception.h> #include <franka/gripper.h> #include "helpers.h" #include "mock_server.h" using franka::CommandException; using franka::Gripper; using franka::GripperState; using franka::IncompatibleVersionException; using franka::Network; using namespace research_interface::gripper; template <typename T> class GripperCommand : public ::testing::Test { public: using TCommand = T; bool executeCommand(Gripper& gripper); typename T::Request getExpected(); typename T::Status getSuccess(); bool compare(const typename T::Request& request_one, const typename T::Request& request_two); typename T::Response createResponse(const typename T::Request& request, const typename T::Status status); }; template <typename T> typename T::Status GripperCommand<T>::getSuccess() { return T::Status::kSuccess; } template <typename T> bool GripperCommand<T>::compare(const typename T::Request&, const typename T::Request&) { return true; } template <> bool GripperCommand<Grasp>::compare(const Grasp::Request& request_one, const Grasp::Request& request_two) { return request_one.width == request_two.width && request_one.speed == request_two.speed && request_one.force == request_two.force; } template <> bool GripperCommand<Move>::compare(const Move::Request& request_one, const Move::Request& request_two) { return request_one.width == request_two.width && request_one.speed == request_two.speed; } template <typename T> typename T::Request GripperCommand<T>::getExpected() { return typename T::Request(); } template <> Move::Request GripperCommand<Move>::getExpected() { double width = 0.05; double speed = 0.1; return Move::Request(width, speed); } template <> Grasp::Request GripperCommand<Grasp>::getExpected() { double width = 0.05; double speed = 0.1; double force = 400.0; return Grasp::Request(width, speed, force); } template <> bool GripperCommand<Move>::executeCommand(Gripper& gripper) { double width = 0.05; double speed = 0.1; return gripper.move(width, speed); } template <> bool GripperCommand<Grasp>::executeCommand(Gripper& gripper) { double width = 0.05; double speed = 0.1; double force = 400.0; return gripper.grasp(width, speed, force); } template <> bool GripperCommand<Stop>::executeCommand(Gripper& gripper) { return gripper.stop(); } template <> bool GripperCommand<Homing>::executeCommand(Gripper& gripper) { return gripper.homing(); } template <typename T> typename T::Response GripperCommand<T>::createResponse(const typename T::Request&, const typename T::Status status) { return typename T::Response(status); } using CommandTypes = ::testing::Types<Homing, Move, Grasp, Stop>; TYPED_TEST_CASE(GripperCommand, CommandTypes); TYPED_TEST(GripperCommand, CanSendAndReceiveSuccess) { GripperMockServer server; Gripper gripper("127.0.0.1"); server .waitForCommand<typename TestFixture::TCommand>( [this](const typename TestFixture::TCommand::Request& request) -> typename TestFixture::TCommand::Response { EXPECT_TRUE(this->compare(request, this->getExpected())); return this->createResponse(request, this->getSuccess()); }) .spinOnce(); EXPECT_NO_THROW(TestFixture::executeCommand(gripper)); } TYPED_TEST(GripperCommand, CanSendAndReceiveFail) { GripperMockServer server; Gripper gripper("127.0.0.1"); server .waitForCommand<typename TestFixture::TCommand>( [this](const typename TestFixture::TCommand::Request& request) -> typename TestFixture::TCommand::Response { EXPECT_TRUE(this->compare(request, this->getExpected())); return this->createResponse(request, TestFixture::TCommand::Status::kFail); }) .spinOnce(); EXPECT_THROW(TestFixture::executeCommand(gripper), CommandException); } TYPED_TEST(GripperCommand, CanSendAndReceiveUnsucessful) { GripperMockServer server; Gripper gripper("127.0.0.1"); server .waitForCommand<typename TestFixture::TCommand>( [this](const typename TestFixture::TCommand::Request& request) -> typename TestFixture::TCommand::Response { EXPECT_TRUE(this->compare(request, this->getExpected())); return this->createResponse(request, TestFixture::TCommand::Status::kUnsuccessful); }) .spinOnce(); EXPECT_FALSE(TestFixture::executeCommand(gripper)); } <|endoftext|>
<commit_before>/* Copyright (C) 2003 Justin Karneges Copyright (C) 2005 Brad Hards 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 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 <QtCrypto> #include <iostream> int main(int argc, char **argv) { // The Initializer object sets things up, and also // does cleanup when it goes out of scope QCA::Initializer init; QCoreApplication app(argc, argv); // we use the first argument if provided, or // use "hello" if no arguments QSecureArray arg = (argc >= 2) ? argv[1] : "hello"; // We demonstrate PEM usage here, so we need to test for // supportedIOTypes, not just supportedTypes if(!QCA::isSupported("pkey") || !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA)) printf("RSA not supported!\n"); else { // When creating a public / private key pair, you make the // private key, and then extract the public key component from it // Using RSA is very common, however DSA can provide equivalent // signature/verification. This example applies to DSA to the // extent that the operations work on that key type. // QCA provides KeyGenerator as a convenient source of new keys, // however you could also import an existing key instead. QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024); if(seckey.isNull()) { std::cout << "Failed to make private RSA key" << std::endl; return 1; } QCA::PublicKey pubkey = seckey.toPublicKey(); // check if the key can encrypt if(!pubkey.canEncrypt()) { std::cout << "Error: this kind of key cannot encrypt" << std::endl; return 1; } // encrypt some data - note that only the public key is required // you must also choose the algorithm to be used QSecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP); if(result.isEmpty()) { std::cout << "Error encrypting" << std::endl; return 1; } // output the encrypted data QString rstr = QCA::arrayToHex(result); std::cout << "\"" << arg.data() << "\" encrypted with RSA is \""; std::cout << qPrintable(rstr) << "\"" << std::endl; // save the private key - in a real example, make sure this goes // somewhere secure and has a good pass phrase // You can use the same technique with the public key too. QSecureArray passPhrase = "pass phrase"; seckey.toPEMFile("keyprivate.pem", passPhrase); // Read that key back in, checking if the read succeeded QCA::ConvertResult conversionResult; QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem", passPhrase, &conversionResult); if (! (QCA::ConvertGood == conversionResult) ) { std::cout << "Private key read failed" << std::endl; } // now decrypt that encrypted data using the private key that // we read in. The algorithm is the same. QSecureArray decrypt; if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) { printf("Error decrypting.\n"); return 1; } // output the resulting decrypted string std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \""; std::cout << decrypt.data() << "\"" << std::endl; // Some private keys can also be used for producing signatures if(!privateKey.canSign()) { std::cout << "Error: this kind of key cannot sign" << std::endl; return 1; } privateKey.startSign( QCA::EMSA3_MD5 ); privateKey.update( arg ); // just reuse the same message QSecureArray argSig = privateKey.signature(); // instead of using the startSign(), update(), signature() calls, // you may be better doing the whole thing in one go, using the // signMessage call. Of course you need the whole message in one // hit, which may or may not be a problem // output the resulting signature rstr = QCA::arrayToHex(argSig); std::cout << "Signature for \"" << arg.data() << "\" using RSA, is "; std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl; // to check a signature, we must check that the key is // appropriate if(pubkey.canVerify()) { pubkey.startVerify( QCA::EMSA3_MD5 ); pubkey.update( arg ); if ( pubkey.validSignature( argSig ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Bad signature" << std::endl; } } // We can also do the verification in a single step if we // have all the message if ( pubkey.canVerify() && pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Signature could not be verified" << std::endl; } } return 0; } <commit_msg>trivial whitespace cleanups + add email address.<commit_after>/* Copyright (C) 2003 Justin Karneges Copyright (C) 2005 Brad Hards <bradh@frogmouth.net> 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 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 <QtCrypto> #include <iostream> int main(int argc, char **argv) { // The Initializer object sets things up, and also // does cleanup when it goes out of scope QCA::Initializer init; QCoreApplication app(argc, argv); // we use the first argument if provided, or // use "hello" if no arguments QSecureArray arg = (argc >= 2) ? argv[1] : "hello"; // We demonstrate PEM usage here, so we need to test for // supportedIOTypes, not just supportedTypes if(!QCA::isSupported("pkey") || !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA)) printf("RSA not supported!\n"); else { // When creating a public / private key pair, you make the // private key, and then extract the public key component from it // Using RSA is very common, however DSA can provide equivalent // signature/verification. This example applies to DSA to the // extent that the operations work on that key type. // QCA provides KeyGenerator as a convenient source of new keys, // however you could also import an existing key instead. QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024); if(seckey.isNull()) { std::cout << "Failed to make private RSA key" << std::endl; return 1; } QCA::PublicKey pubkey = seckey.toPublicKey(); // check if the key can encrypt if(!pubkey.canEncrypt()) { std::cout << "Error: this kind of key cannot encrypt" << std::endl; return 1; } // encrypt some data - note that only the public key is required // you must also choose the algorithm to be used QSecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP); if(result.isEmpty()) { std::cout << "Error encrypting" << std::endl; return 1; } // output the encrypted data QString rstr = QCA::arrayToHex(result); std::cout << "\"" << arg.data() << "\" encrypted with RSA is \""; std::cout << qPrintable(rstr) << "\"" << std::endl; // save the private key - in a real example, make sure this goes // somewhere secure and has a good pass phrase // You can use the same technique with the public key too. QSecureArray passPhrase = "pass phrase"; seckey.toPEMFile("keyprivate.pem", passPhrase); // Read that key back in, checking if the read succeeded QCA::ConvertResult conversionResult; QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem", passPhrase, &conversionResult); if (! (QCA::ConvertGood == conversionResult) ) { std::cout << "Private key read failed" << std::endl; } // now decrypt that encrypted data using the private key that // we read in. The algorithm is the same. QSecureArray decrypt; if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) { printf("Error decrypting.\n"); return 1; } // output the resulting decrypted string std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \""; std::cout << decrypt.data() << "\"" << std::endl; // Some private keys can also be used for producing signatures if(!privateKey.canSign()) { std::cout << "Error: this kind of key cannot sign" << std::endl; return 1; } privateKey.startSign( QCA::EMSA3_MD5 ); privateKey.update( arg ); // just reuse the same message QSecureArray argSig = privateKey.signature(); // instead of using the startSign(), update(), signature() calls, // you may be better doing the whole thing in one go, using the // signMessage call. Of course you need the whole message in one // hit, which may or may not be a problem // output the resulting signature rstr = QCA::arrayToHex(argSig); std::cout << "Signature for \"" << arg.data() << "\" using RSA, is "; std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl; // to check a signature, we must check that the key is // appropriate if(pubkey.canVerify()) { pubkey.startVerify( QCA::EMSA3_MD5 ); pubkey.update( arg ); if ( pubkey.validSignature( argSig ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Bad signature" << std::endl; } } // We can also do the verification in a single step if we // have all the message if ( pubkey.canVerify() && pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) { std::cout << "Signature is valid" << std::endl; } else { std::cout << "Signature could not be verified" << std::endl; } } return 0; } <|endoftext|>
<commit_before>// // File: DKBvh.cpp // Author: Hongtae Kim (tiff2766@gmail.com) // // Copyright (c) 2004-2015 Hongtae Kim. All rights reserved. // #include <algorithm> #include <cstdlib> #include "DKMath.h" #include "DKBvh.h" #define MAX_NODE_COUNT (0x7fffffff >> 1) using namespace DKFoundation; using namespace DKFramework; DKBvh::DKBvh(void) : volume(NULL) { } DKBvh::~DKBvh(void) { } void DKBvh::Build(VolumeInterface* vi) { this->volume = vi; BuildInternal(); } void DKBvh::Rebuild(void) { BuildInternal(); } void DKBvh::BuildInternal(void) { if (this->volume) { this->volume->Lock(); nodes.Clear(); DKArray<QuantizedAabbNode> quantizedLeafNodes; // Query all leaf-nodes (all triangles) int numTriangles = this->volume->NumberOfObjects(); if (numTriangles > 0) { struct LeafNode { DKAabb aabb; int objectIndex; }; DKAabb aabb; aabb.positionMin = DKVector3(FLT_MAX, FLT_MAX, FLT_MAX); aabb.positionMax = DKVector3(-FLT_MAX, -FLT_MAX, -FLT_MAX); DKArray<LeafNode> leafNodes; leafNodes.Reserve(numTriangles); for (int i = 0; i < numTriangles; ++i) { DKAabb box = this->volume->AabbForObjectAtIndex(i); if (box.IsValid()) { LeafNode info = { box, i }; leafNodes.Add(info); // Update AABB for (int k = 0; k < 3; ++k) { if (aabb.positionMin.val[k] > info.aabb.positionMin.val[k]) aabb.positionMin.val[k] = info.aabb.positionMin.val[k]; if (aabb.positionMax.val[k] < info.aabb.positionMax.val[k]) aabb.positionMax.val[k] = info.aabb.positionMax.val[k]; } } } DKVector3 scale = aabb.positionMax - aabb.positionMin; this->aabbScale.x = Max(scale.x, 0.00001); this->aabbScale.y = Max(scale.y, 0.00001); this->aabbScale.z = Max(scale.z, 0.00001); this->aabbOffset = aabb.positionMin; quantizedLeafNodes.Reserve(leafNodes.Count()); for (LeafNode& n : leafNodes) { DKVector3 aabbMin = (n.aabb.positionMin - this->aabbOffset) / this->aabbScale * float(0xffff); DKVector3 aabbMax = (n.aabb.positionMax - this->aabbOffset) / this->aabbScale * float(0xffff); QuantizedAabbNode node; node.aabbMin[0] = aabbMin.val[0]; node.aabbMin[1] = aabbMin.val[1]; node.aabbMin[2] = aabbMin.val[2]; node.aabbMax[0] = aabbMax.val[0]; node.aabbMax[1] = aabbMax.val[1]; node.aabbMax[2] = aabbMax.val[2]; node.objectIndex = n.objectIndex; quantizedLeafNodes.Add(node); } } if (quantizedLeafNodes.Count() > 0 && quantizedLeafNodes.Count() < MAX_NODE_COUNT) { nodes.Reserve(quantizedLeafNodes.Count() * 2); BuildTree(quantizedLeafNodes, (int)quantizedLeafNodes.Count()); } this->volume->Unlock(); } else nodes.Clear(); } DKAabb DKBvh::Aabb(void) const { if (volume) { return DKAabb(aabbOffset, aabbOffset + aabbScale); } return DKAabb(); } #define BVH_PARTITION_FULL_SORT 1 void DKBvh::BuildTree(QuantizedAabbNode* leafNodes, int count) { DKASSERT_DEBUG(leafNodes); DKASSERT_DEBUG(count > 0); if (count == 1) // leaf-node { this->nodes.Add(leafNodes[0]); return; } using VectorI64 = int64_t[3]; using VectorI32 = int32_t[3]; using VectorI16 = int16_t[3]; // calculate means VectorI32 means; if (1) { VectorI64 tmp = { 0, 0, 0 }; for (int i = 0; i < count; ++i) { QuantizedAabbNode& node = leafNodes[i]; tmp[0] += node.aabbMin[0] + node.aabbMax[0]; tmp[1] += node.aabbMin[1] + node.aabbMax[1]; tmp[2] += node.aabbMin[2] + node.aabbMax[2]; } int c = count << 1; means[0] = (int32_t)(tmp[0] / c); means[1] = (int32_t)(tmp[1] / c); means[2] = (int32_t)(tmp[2] / c); } // calculate axis (0: x-axis, 1: y-axis, 2: z-axis, DKVector3::val order) int splitAxis = 0; if (1) { VectorI32 center, variance = { 0, 0, 0 }; for (int i = 0; i < count; ++i) { QuantizedAabbNode& node = leafNodes[i]; center[0] = (node.aabbMin[0] + node.aabbMax[0]) >> 1; center[1] = (node.aabbMin[1] + node.aabbMax[1]) >> 1; center[2] = (node.aabbMin[2] + node.aabbMax[2]) >> 1; variance[0] += std::abs(center[0] - means[0]); variance[1] += std::abs(center[1] - means[1]); variance[2] += std::abs(center[2] - means[2]); } splitAxis = (variance[0] < variance[1] ? (variance[1] < variance[2] ? 2 : 1) : (variance[0] < variance[2] ? 2 : 0)); } // partitioning int splitValue = means[splitAxis]; int splitIndex = 0; #if BVH_PARTITION_FULL_SORT // soft leaf-nodes, place larger value front. std::sort(leafNodes, leafNodes + count, [splitAxis](const QuantizedAabbNode& a, const QuantizedAabbNode& b)->bool { return (a.aabbMax[splitAxis] + a.aabbMin[splitAxis]) > (b.aabbMax[splitAxis] + b.aabbMin[splitAxis]); }); splitIndex = count / 2; #else // sort leaf-nodes, place larger than splitValue to left. for (int i = 0; i < count; ++i) { QuantizedAabbNode& node = leafNodes[i]; if (node.aabbMax[splitAxis] + node.aabbMin[splitAxis] > splitValue) { QuantizedAabbNode tmp = leafNodes[i]; leafNodes[i] = leafNodes[splitIndex]; leafNodes[splitIndex] = tmp; splitIndex++; } } int balancedRangeMin = count / 3; int balancedRangeMax = count - balancedRangeMin - 1; if (splitIndex <= balancedRangeMin || splitIndex >= balancedRangeMax) { splitIndex = count / 2; } DKASSERT_DEBUG(splitIndex < count); #endif // recursion int currentNodeIndex = (int)nodes.Add(QuantizedAabbNode()); // build left sub tree int leftChildNodeIndex = (int)nodes.Count(); BuildTree(leafNodes, splitIndex); // build right sub tree int rightChildNodeIndex = (int)nodes.Count(); BuildTree(&leafNodes[splitIndex], count - splitIndex); QuantizedAabbNode& node = nodes.Value(currentNodeIndex); QuantizedAabbNode& left = nodes.Value(leftChildNodeIndex); QuantizedAabbNode& right = nodes.Value(rightChildNodeIndex); for (int i = 0; i < 3; ++i) { node.aabbMin[i] = Min(left.aabbMin[i], right.aabbMin[i]); node.aabbMax[i] = Max(left.aabbMax[i], right.aabbMax[i]); } node.negativeTreeSize = currentNodeIndex - static_cast<int>(nodes.Count()); } template <typename T> FORCEINLINE static bool IsAabbOverlapped(const T(& min1)[3], const T(&min2)[3], const T(&max1)[3], const T(&max2)[3]) { if (min1[0] > max2[0] || max1[0] < min2[0] || min1[1] > max2[1] || max1[1] < min2[1] || min1[2] > max2[2] || max1[2] < min2[2]) return false; return true; } bool DKBvh::RayTest(const DKLine& ray, RayCastResultCallback* cb) const { if (this->volume) { DKAabb bvhAabb = this->Aabb(); DKVector3 p1, p2; if (bvhAabb.RayTest(ray, &p1) && bvhAabb.RayTest(DKLine(ray.end, ray.begin), &p2)) { DKVector3 offset = this->aabbOffset; DKVector3 scale = this->aabbScale; DKASSERT_DEBUG(scale.x > 0.0f && scale.y > 0.0f && scale.z > 0.0f); unsigned short rayAabbMin[3]; unsigned short rayAabbMax[3]; DKAabb rayOverlapAabb; rayOverlapAabb.Expand(p1); rayOverlapAabb.Expand(p2); for (int i = 0; i < 3; ++i) { rayAabbMin[i] = (rayOverlapAabb.positionMin.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); rayAabbMax[i] = (rayOverlapAabb.positionMax.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); } int currentNodeIndex = 0; int nodeCount = (int)this->nodes.Count(); bool isLeafNode = false; bool isOverlapped = false; DKAabb nodeAabb; const DKVector3 scaleFactor = scale / float(0xffff); while (currentNodeIndex < nodeCount) { const QuantizedAabbNode& node = nodes.Value(currentNodeIndex); isOverlapped = IsAabbOverlapped(rayAabbMin, rayAabbMax, node.aabbMin, node.aabbMax); isLeafNode = node.objectIndex >= 0; if (isLeafNode) { if (isOverlapped) { // un-quantize nodeAabb.positionMin.val[0] = (float(node.aabbMin[0]) * scaleFactor.val[0]) + offset.val[0]; nodeAabb.positionMin.val[1] = (float(node.aabbMin[1]) * scaleFactor.val[1]) + offset.val[1]; nodeAabb.positionMin.val[2] = (float(node.aabbMin[2]) * scaleFactor.val[2]) + offset.val[2]; nodeAabb.positionMax.val[0] = (float(node.aabbMax[0]) * scaleFactor.val[0]) + offset.val[0]; nodeAabb.positionMax.val[1] = (float(node.aabbMax[1]) * scaleFactor.val[1]) + offset.val[1]; nodeAabb.positionMax.val[2] = (float(node.aabbMax[2]) * scaleFactor.val[2]) + offset.val[2]; if (nodeAabb.RayTest(ray)) { if (cb == NULL || !cb->Invoke(node.objectIndex, ray)) return true; } } currentNodeIndex++; } else { if (isOverlapped) currentNodeIndex++; else currentNodeIndex -= node.negativeTreeSize; } } } } return false; } bool DKBvh::AabbOverlapTest(const DKAabb& aabb, AabbOverlapResultCallback* cb) const { if (this->volume && aabb.IsValid()) { // rescale given aabb to be quantized. DKAabb inAabb = DKAabb::Intersection(this->Aabb(), aabb); if (inAabb.IsValid()) // aabb overlapped. { DKVector3 offset = this->aabbOffset; DKVector3 scale = this->aabbScale; DKASSERT_DEBUG(scale.x > 0.0f && scale.y > 0.0f && scale.z > 0.0f); unsigned short aabbMin[3]; unsigned short aabbMax[3]; for (int i = 0; i < 3; ++i) { aabbMin[i] = (inAabb.positionMin.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); aabbMax[i] = (inAabb.positionMax.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); } int currentNodeIndex = 0; int nodeCount = (int)this->nodes.Count(); bool isLeafNode = false; bool isOverlapped = false; while (currentNodeIndex < nodeCount) { const QuantizedAabbNode& node = nodes.Value(currentNodeIndex); isOverlapped = IsAabbOverlapped(aabbMin, aabbMax, node.aabbMin, node.aabbMax); isLeafNode = node.objectIndex >= 0; if (isLeafNode) { if (isOverlapped) { if (cb == NULL || !cb->Invoke(node.objectIndex, aabb)) return true; } currentNodeIndex++; } else { if (isOverlapped) currentNodeIndex++; else currentNodeIndex -= node.negativeTreeSize; } } } } return false; } <commit_msg>DKBvh::RayTest() bug fixed.<commit_after>// // File: DKBvh.cpp // Author: Hongtae Kim (tiff2766@gmail.com) // // Copyright (c) 2004-2015 Hongtae Kim. All rights reserved. // #include <algorithm> #include <cstdlib> #include "DKMath.h" #include "DKBvh.h" #define MAX_NODE_COUNT (0x7fffffff >> 1) using namespace DKFoundation; using namespace DKFramework; DKBvh::DKBvh(void) : volume(NULL) { } DKBvh::~DKBvh(void) { } void DKBvh::Build(VolumeInterface* vi) { this->volume = vi; BuildInternal(); } void DKBvh::Rebuild(void) { BuildInternal(); } void DKBvh::BuildInternal(void) { if (this->volume) { this->volume->Lock(); nodes.Clear(); DKArray<QuantizedAabbNode> quantizedLeafNodes; // Query all leaf-nodes (all triangles) int numTriangles = this->volume->NumberOfObjects(); if (numTriangles > 0) { struct LeafNode { DKAabb aabb; int objectIndex; }; DKAabb aabb; aabb.positionMin = DKVector3(FLT_MAX, FLT_MAX, FLT_MAX); aabb.positionMax = DKVector3(-FLT_MAX, -FLT_MAX, -FLT_MAX); DKArray<LeafNode> leafNodes; leafNodes.Reserve(numTriangles); for (int i = 0; i < numTriangles; ++i) { DKAabb box = this->volume->AabbForObjectAtIndex(i); if (box.IsValid()) { LeafNode info = { box, i }; leafNodes.Add(info); // Update AABB for (int k = 0; k < 3; ++k) { if (aabb.positionMin.val[k] > info.aabb.positionMin.val[k]) aabb.positionMin.val[k] = info.aabb.positionMin.val[k]; if (aabb.positionMax.val[k] < info.aabb.positionMax.val[k]) aabb.positionMax.val[k] = info.aabb.positionMax.val[k]; } } } DKVector3 scale = aabb.positionMax - aabb.positionMin; this->aabbScale.x = Max(scale.x, 0.00001); this->aabbScale.y = Max(scale.y, 0.00001); this->aabbScale.z = Max(scale.z, 0.00001); this->aabbOffset = aabb.positionMin; quantizedLeafNodes.Reserve(leafNodes.Count()); for (LeafNode& n : leafNodes) { DKVector3 aabbMin = (n.aabb.positionMin - this->aabbOffset) / this->aabbScale * float(0xffff); DKVector3 aabbMax = (n.aabb.positionMax - this->aabbOffset) / this->aabbScale * float(0xffff); QuantizedAabbNode node; node.aabbMin[0] = aabbMin.val[0]; node.aabbMin[1] = aabbMin.val[1]; node.aabbMin[2] = aabbMin.val[2]; node.aabbMax[0] = aabbMax.val[0]; node.aabbMax[1] = aabbMax.val[1]; node.aabbMax[2] = aabbMax.val[2]; node.objectIndex = n.objectIndex; quantizedLeafNodes.Add(node); } } if (quantizedLeafNodes.Count() > 0 && quantizedLeafNodes.Count() < MAX_NODE_COUNT) { nodes.Reserve(quantizedLeafNodes.Count() * 2); BuildTree(quantizedLeafNodes, (int)quantizedLeafNodes.Count()); } this->volume->Unlock(); } else nodes.Clear(); } DKAabb DKBvh::Aabb(void) const { if (volume) { return DKAabb(aabbOffset, aabbOffset + aabbScale); } return DKAabb(); } #define BVH_PARTITION_FULL_SORT 1 void DKBvh::BuildTree(QuantizedAabbNode* leafNodes, int count) { DKASSERT_DEBUG(leafNodes); DKASSERT_DEBUG(count > 0); if (count == 1) // leaf-node { this->nodes.Add(leafNodes[0]); return; } using VectorI64 = int64_t[3]; using VectorI32 = int32_t[3]; using VectorI16 = int16_t[3]; // calculate means VectorI32 means; if (1) { VectorI64 tmp = { 0, 0, 0 }; for (int i = 0; i < count; ++i) { QuantizedAabbNode& node = leafNodes[i]; tmp[0] += node.aabbMin[0] + node.aabbMax[0]; tmp[1] += node.aabbMin[1] + node.aabbMax[1]; tmp[2] += node.aabbMin[2] + node.aabbMax[2]; } int c = count << 1; means[0] = (int32_t)(tmp[0] / c); means[1] = (int32_t)(tmp[1] / c); means[2] = (int32_t)(tmp[2] / c); } // calculate axis (0: x-axis, 1: y-axis, 2: z-axis, DKVector3::val order) int splitAxis = 0; if (1) { VectorI32 center, variance = { 0, 0, 0 }; for (int i = 0; i < count; ++i) { QuantizedAabbNode& node = leafNodes[i]; center[0] = (node.aabbMin[0] + node.aabbMax[0]) >> 1; center[1] = (node.aabbMin[1] + node.aabbMax[1]) >> 1; center[2] = (node.aabbMin[2] + node.aabbMax[2]) >> 1; variance[0] += std::abs(center[0] - means[0]); variance[1] += std::abs(center[1] - means[1]); variance[2] += std::abs(center[2] - means[2]); } splitAxis = (variance[0] < variance[1] ? (variance[1] < variance[2] ? 2 : 1) : (variance[0] < variance[2] ? 2 : 0)); } // partitioning int splitValue = means[splitAxis]; int splitIndex = 0; #if BVH_PARTITION_FULL_SORT // soft leaf-nodes, place larger value front. std::sort(leafNodes, leafNodes + count, [splitAxis](const QuantizedAabbNode& a, const QuantizedAabbNode& b)->bool { return (a.aabbMax[splitAxis] + a.aabbMin[splitAxis]) > (b.aabbMax[splitAxis] + b.aabbMin[splitAxis]); }); splitIndex = count / 2; #else // sort leaf-nodes, place larger than splitValue to left. for (int i = 0; i < count; ++i) { QuantizedAabbNode& node = leafNodes[i]; if (node.aabbMax[splitAxis] + node.aabbMin[splitAxis] > splitValue) { QuantizedAabbNode tmp = leafNodes[i]; leafNodes[i] = leafNodes[splitIndex]; leafNodes[splitIndex] = tmp; splitIndex++; } } int balancedRangeMin = count / 3; int balancedRangeMax = count - balancedRangeMin - 1; if (splitIndex <= balancedRangeMin || splitIndex >= balancedRangeMax) { splitIndex = count / 2; } DKASSERT_DEBUG(splitIndex < count); #endif // recursion int currentNodeIndex = (int)nodes.Add(QuantizedAabbNode()); // build left sub tree int leftChildNodeIndex = (int)nodes.Count(); BuildTree(leafNodes, splitIndex); // build right sub tree int rightChildNodeIndex = (int)nodes.Count(); BuildTree(&leafNodes[splitIndex], count - splitIndex); QuantizedAabbNode& node = nodes.Value(currentNodeIndex); QuantizedAabbNode& left = nodes.Value(leftChildNodeIndex); QuantizedAabbNode& right = nodes.Value(rightChildNodeIndex); for (int i = 0; i < 3; ++i) { node.aabbMin[i] = Min(left.aabbMin[i], right.aabbMin[i]); node.aabbMax[i] = Max(left.aabbMax[i], right.aabbMax[i]); } node.negativeTreeSize = currentNodeIndex - static_cast<int>(nodes.Count()); } template <typename T> //FORCEINLINE static bool IsAabbOverlapped(const T(& min1)[3], const T(&max1)[3], const T(&min2)[3], const T(&max2)[3]) FORCEINLINE static bool IsAabbOverlapped(const T* min1, const T* max1, const T* min2, const T* max2) { if (min1[0] > max2[0] || max1[0] < min2[0] || min1[1] > max2[1] || max1[1] < min2[1] || min1[2] > max2[2] || max1[2] < min2[2]) return false; return true; } bool DKBvh::RayTest(const DKLine& ray, RayCastResultCallback* cb) const { if (this->volume) { DKAabb bvhAabb = this->Aabb(); DKVector3 p1, p2; if (bvhAabb.RayTest(ray, &p1) && bvhAabb.RayTest(DKLine(ray.end, ray.begin), &p2)) { DKVector3 offset = this->aabbOffset; DKVector3 scale = this->aabbScale; DKASSERT_DEBUG(scale.x > 0.0f && scale.y > 0.0f && scale.z > 0.0f); unsigned short rayAabbMin[3]; unsigned short rayAabbMax[3]; DKAabb rayOverlapAabb; rayOverlapAabb.Expand(p1); rayOverlapAabb.Expand(p2); for (int i = 0; i < 3; ++i) { rayAabbMin[i] = (rayOverlapAabb.positionMin.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); rayAabbMax[i] = (rayOverlapAabb.positionMax.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); } int currentNodeIndex = 0; int nodeCount = (int)this->nodes.Count(); bool isLeafNode = false; bool isOverlapped = false; DKAabb nodeAabb; const DKVector3 scaleFactor = scale / float(0xffff); while (currentNodeIndex < nodeCount) { const QuantizedAabbNode& node = nodes.Value(currentNodeIndex); isOverlapped = IsAabbOverlapped(rayAabbMin, rayAabbMax, node.aabbMin, node.aabbMax); isLeafNode = node.objectIndex >= 0; if (isLeafNode) { if (isOverlapped) { // un-quantize nodeAabb.positionMin.val[0] = (float(node.aabbMin[0]) * scaleFactor.val[0]) + offset.val[0]; nodeAabb.positionMin.val[1] = (float(node.aabbMin[1]) * scaleFactor.val[1]) + offset.val[1]; nodeAabb.positionMin.val[2] = (float(node.aabbMin[2]) * scaleFactor.val[2]) + offset.val[2]; nodeAabb.positionMax.val[0] = (float(node.aabbMax[0]) * scaleFactor.val[0]) + offset.val[0]; nodeAabb.positionMax.val[1] = (float(node.aabbMax[1]) * scaleFactor.val[1]) + offset.val[1]; nodeAabb.positionMax.val[2] = (float(node.aabbMax[2]) * scaleFactor.val[2]) + offset.val[2]; if (nodeAabb.RayTest(ray)) { if (cb == NULL || !cb->Invoke(node.objectIndex, ray)) return true; } } currentNodeIndex++; } else { if (isOverlapped) currentNodeIndex++; else currentNodeIndex -= node.negativeTreeSize; } } } } return false; } bool DKBvh::AabbOverlapTest(const DKAabb& aabb, AabbOverlapResultCallback* cb) const { if (this->volume && aabb.IsValid()) { // rescale given aabb to be quantized. DKAabb inAabb = DKAabb::Intersection(this->Aabb(), aabb); if (inAabb.IsValid()) // aabb overlapped. { DKVector3 offset = this->aabbOffset; DKVector3 scale = this->aabbScale; DKASSERT_DEBUG(scale.x > 0.0f && scale.y > 0.0f && scale.z > 0.0f); unsigned short aabbMin[3]; unsigned short aabbMax[3]; for (int i = 0; i < 3; ++i) { aabbMin[i] = (inAabb.positionMin.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); aabbMax[i] = (inAabb.positionMax.val[i] - offset.val[i]) / scale.val[i] * float(0xffff); } int currentNodeIndex = 0; int nodeCount = (int)this->nodes.Count(); bool isLeafNode = false; bool isOverlapped = false; while (currentNodeIndex < nodeCount) { const QuantizedAabbNode& node = nodes.Value(currentNodeIndex); isOverlapped = IsAabbOverlapped(aabbMin, aabbMax, node.aabbMin, node.aabbMax); isLeafNode = node.objectIndex >= 0; if (isLeafNode) { if (isOverlapped) { if (cb == NULL || !cb->Invoke(node.objectIndex, aabb)) return true; } currentNodeIndex++; } else { if (isOverlapped) currentNodeIndex++; else currentNodeIndex -= node.negativeTreeSize; } } } } return false; } <|endoftext|>
<commit_before>/* * This file is part of SmoothThermistor. * * Copyright (c) 2016 Gianni Van Hoecke <gianni.vh@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. * * User: Gianni Van Hoecke <gianni.vh@gmail.com> * Date: 23/05/16 * Time: 19:28 * * SmoothThermistor (https://github.com/giannivh/SmoothThermistor) * A flexible thermistor reading library. */ #include "Arduino.h" #include "SmoothThermistor.h" #include <math.h> SmoothThermistor::SmoothThermistor(uint8_t analogPin, uint16_t adcSize, uint32_t nominalResistance, uint32_t seriesResistance, uint16_t betaCoefficient, uint8_t nominalTemperature, uint8_t samples) { _analogPin = analogPin; _adcSize = adcSize; _nominalResistance = nominalResistance; _seriesResistance = seriesResistance; _betaCoefficient = betaCoefficient; _nominalTemperature = nominalTemperature; _samples = samples; } void SmoothThermistor::useAREF(bool aref) { analogReference(aref? EXTERNAL: DEFAULT); } float SmoothThermistor::temperature(void) { // take samples float average = 0; for (uint8_t i = 0; i < _samples; i++) { average += analogRead(_analogPin); delay(10); } average /= _samples; // convert the value to resistance average = _seriesResistance * ((pow(2.0, _adcSize) - 1) / average - 1); // Steinhart–Hart equation, based on https://learn.adafruit.com/thermistor/using-a-thermistor float steinhart = (log(average / _nominalResistance)) / _betaCoefficient; steinhart += 1.0 / (_nominalTemperature + 273.15); steinhart = 1.0 / steinhart; // invert steinhart -= 273.15; // convert to celsius return steinhart; }<commit_msg>removed analogReference for ESP32<commit_after>/* * This file is part of SmoothThermistor. * * Copyright (c) 2016 Gianni Van Hoecke <gianni.vh@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. * * User: Gianni Van Hoecke <gianni.vh@gmail.com> * Date: 23/05/16 * Time: 19:28 * * SmoothThermistor (https://github.com/giannivh/SmoothThermistor) * A flexible thermistor reading library. */ #include "Arduino.h" #include "SmoothThermistor.h" #include <math.h> SmoothThermistor::SmoothThermistor(uint8_t analogPin, uint16_t adcSize, uint32_t nominalResistance, uint32_t seriesResistance, uint16_t betaCoefficient, uint8_t nominalTemperature, uint8_t samples) { _analogPin = analogPin; _adcSize = adcSize; _nominalResistance = nominalResistance; _seriesResistance = seriesResistance; _betaCoefficient = betaCoefficient; _nominalTemperature = nominalTemperature; _samples = samples; } void SmoothThermistor::useAREF(bool aref) { #IFNDEF ESP32 analogReference(aref? EXTERNAL: DEFAULT); #ENDIF } float SmoothThermistor::temperature(void) { // take samples float average = 0; for (uint8_t i = 0; i < _samples; i++) { average += analogRead(_analogPin); delay(10); } average /= _samples; // convert the value to resistance average = _seriesResistance * ((pow(2.0, _adcSize) - 1) / average - 1); // Steinhart–Hart equation, based on https://learn.adafruit.com/thermistor/using-a-thermistor float steinhart = (log(average / _nominalResistance)) / _betaCoefficient; steinhart += 1.0 / (_nominalTemperature + 273.15); steinhart = 1.0 / steinhart; // invert steinhart -= 273.15; // convert to celsius return steinhart; } <|endoftext|>
<commit_before>#include <algorithm> #include <cassert> #include <string> #include "TimeWarpEventSet.hpp" #include "utility/warnings.hpp" namespace warped { void TimeWarpEventSet::initialize (unsigned int num_of_objects, unsigned int num_of_schedulers, unsigned int num_of_worker_threads) { num_of_objects_ = num_of_objects; num_of_schedulers_ = num_of_schedulers; /* Create the input queues and their locks. Also create the input queue to schedule queue map. */ input_queue_lock_ = make_unique<std::mutex []>(num_of_objects); for (unsigned int obj_id = 0; obj_id < num_of_objects; obj_id++) { input_queue_.push_back( make_unique<std::multiset<std::shared_ptr<Event>, compareEvents>>()); track_processed_event_.push_back( make_unique<std::unordered_map<std::shared_ptr<Event>, bool>>()); lowest_unprocessed_event_pointer_.push_back(0); last_processed_event_pointer_.push_back(0); scheduled_event_pointer_.push_back(0); input_queue_scheduler_map_.push_back(obj_id % num_of_schedulers); } /* Create the schedule queues and their locks. */ for (unsigned int scheduler_id = 0; scheduler_id < num_of_schedulers; scheduler_id++) { schedule_queue_.push_back(make_unique< std::multiset<std::shared_ptr<Event>, compareEvents>>()); } schedule_queue_lock_ = make_unique<std::mutex []>(num_of_schedulers); /* Map worker threads to schedule queues. */ for (unsigned int thread_id = 0; thread_id < num_of_worker_threads; thread_id++) { worker_thread_scheduler_map_.push_back(thread_id % num_of_schedulers); } } void TimeWarpEventSet::acquireInputQueueLock (unsigned int obj_id) { input_queue_lock_[obj_id].lock(); } void TimeWarpEventSet::releaseInputQueueLock (unsigned int obj_id) { input_queue_lock_[obj_id].unlock(); } void TimeWarpEventSet::insertEvent (unsigned int obj_id, std::shared_ptr<Event> event) { bool causal_order_ok = true; auto event_iterator = input_queue_[obj_id]->insert(event); (*track_processed_event_[obj_id])[event] = false; // If event is negative // Assumption: Positive event arrives earlier than its negative counterpart if (event->event_type_ == EventType::NEGATIVE) { auto next_iterator = std::next(event_iterator); // If next event is the positive counterpart if ((next_iterator != input_queue_[obj_id]->end()) && (**next_iterator == *event) && ((*next_iterator)->event_type_ == EventType::POSITIVE)) { // If no event is currently scheduled (all current events processed) if (!scheduled_event_pointer_[obj_id]) { scheduled_event_pointer_[obj_id] = event; causal_order_ok = false; } else { // Scheduled event present // If positive counterpart is currently scheduled if (scheduled_event_pointer_[obj_id] == *next_iterator) { causal_order_ok = false; } else if (**next_iterator < *scheduled_event_pointer_[obj_id]) { // If negative event is supposed to cause a rollback causal_order_ok = false; } else { // It is ok to delete the negative event (*track_processed_event_[obj_id]).erase(*event_iterator); (*track_processed_event_[obj_id]).erase(*next_iterator); input_queue_[obj_id]->erase(event_iterator); input_queue_[obj_id]->erase(next_iterator); } } } else { // If no positive counterpart found assert(0); } } else { // Positive event // If no event is currently scheduled (all current events processed) if (!scheduled_event_pointer_[obj_id]) { scheduled_event_pointer_[obj_id] = event; // Initial event should not be classified as a potential straggler if ((input_queue_[obj_id]->size() > 1) && (event != *input_queue_[obj_id]->rbegin())) { causal_order_ok = false; } } else { // Scheduled event present // If event is smaller than the one scheduled if (*event < *scheduled_event_pointer_[obj_id]) { causal_order_ok = false; } } } // If inserted event is the one scheduled, insert into schedule queue if (scheduled_event_pointer_[obj_id] == event) { unsigned int scheduler_id = input_queue_scheduler_map_[obj_id]; schedule_queue_lock_[scheduler_id].lock(); schedule_queue_[scheduler_id]->insert(event); schedule_queue_lock_[scheduler_id].unlock(); } if (!causal_order_ok) { // If unprocessed event already exists if (lowest_unprocessed_event_pointer_[obj_id]) { // If event less than existing lowest unprocessed event if ((*event < *lowest_unprocessed_event_pointer_[obj_id]) || ((*event == *lowest_unprocessed_event_pointer_[obj_id]) && (event->event_type_ < lowest_unprocessed_event_pointer_[obj_id]->event_type_))) { lowest_unprocessed_event_pointer_[obj_id] = event; } } else { // Unprocessed event does not exist lowest_unprocessed_event_pointer_[obj_id] = event; } } } std::shared_ptr<Event> TimeWarpEventSet::getEvent (unsigned int thread_id) { unsigned int scheduler_id = worker_thread_scheduler_map_[thread_id]; schedule_queue_lock_[scheduler_id].lock(); auto event_iterator = schedule_queue_[scheduler_id]->begin(); auto event = (event_iterator != schedule_queue_[scheduler_id]->end()) ? *event_iterator : nullptr; if (event) { schedule_queue_[scheduler_id]->erase(event_iterator); } schedule_queue_lock_[scheduler_id].unlock(); return event; } bool TimeWarpEventSet::isRollbackRequired(unsigned int obj_id) { bool rollback_req = true; // If no events have been processed till that point if (!last_processed_event_pointer_[obj_id]) { rollback_req = false; } else { // When atleast one event has been processed auto last_processed_event_iterator = input_queue_[obj_id]->find(last_processed_event_pointer_[obj_id]); assert (last_processed_event_iterator != input_queue_[obj_id]->end()); auto event_iterator = std::next(last_processed_event_iterator); if (event_iterator != input_queue_[obj_id]->end()) { // If the lowest unprocessed event is immediately next to the last processed event if (lowest_unprocessed_event_pointer_[obj_id] == *event_iterator) { rollback_req = false; } } } return rollback_req; } void TimeWarpEventSet::lastProcessedEvent (unsigned int obj_id, std::shared_ptr<Event> event) { last_processed_event_pointer_[obj_id] = event; } void TimeWarpEventSet::processedEvent (unsigned int obj_id, std::shared_ptr<Event> event) { (*track_processed_event_[obj_id])[event] = true; lastProcessedEvent(obj_id, event); } std::shared_ptr<Event> TimeWarpEventSet::getLowestUnprocessedEvent (unsigned int obj_id) { return lowest_unprocessed_event_pointer_[obj_id]; } void TimeWarpEventSet::resetLowestUnprocessedEvent (unsigned int obj_id) { lowest_unprocessed_event_pointer_[obj_id] = 0; } std::unique_ptr<std::vector<std::shared_ptr<Event>>> TimeWarpEventSet::getEventsForCoastForward ( unsigned int obj_id, std::shared_ptr<Event> straggler_event, std::shared_ptr<Event> restored_state_event) { auto events = make_unique<std::vector<std::shared_ptr<Event>>>(); auto straggler_iterator = input_queue_[obj_id]->find(straggler_event); auto restored_event_iterator = input_queue_[obj_id]->find(restored_state_event); assert(straggler_iterator != input_queue_[obj_id]->end()); assert(restored_event_iterator != input_queue_[obj_id]->end()); do { straggler_iterator--; assert(*straggler_iterator); if (straggler_iterator == restored_event_iterator) { break; } if ((*track_processed_event_[obj_id])[*straggler_iterator]) { events->push_back(*straggler_iterator); } } while (straggler_iterator != input_queue_[obj_id]->begin()); return (std::move(events)); } void TimeWarpEventSet::startScheduling (unsigned int obj_id) { auto straggler_event = lowest_unprocessed_event_pointer_[obj_id]; if (scheduled_event_pointer_[obj_id]) { // If there is a chance of causal order violation if (straggler_event) { auto event_iterator = input_queue_[obj_id]->find(straggler_event); if (event_iterator == input_queue_[obj_id]->end()) { assert(0); } scheduled_event_pointer_[obj_id] = straggler_event; } else { // Causal order auto event_iterator = input_queue_[obj_id]->find(scheduled_event_pointer_[obj_id]); if (event_iterator == input_queue_[obj_id]->end()) { assert(0); } event_iterator++; scheduled_event_pointer_[obj_id] = (event_iterator != input_queue_[obj_id]->end()) ? *event_iterator : 0; } if (scheduled_event_pointer_[obj_id]) { unsigned int scheduler_id = input_queue_scheduler_map_[obj_id]; schedule_queue_lock_[scheduler_id].lock(); schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]); schedule_queue_lock_[scheduler_id].unlock(); } } else { assert(0); } } void TimeWarpEventSet::cancelEvent (unsigned int obj_id, std::shared_ptr<Event> cancel_event) { auto neg_iterator = input_queue_[obj_id]->find(cancel_event); assert(neg_iterator != input_queue_[obj_id]->end()); auto pos_iterator = std::next(neg_iterator); assert(**pos_iterator == **neg_iterator); assert((*pos_iterator)->event_type_ == EventType::POSITIVE); auto next_valid_iterator = std::next(neg_iterator, 2); scheduled_event_pointer_[obj_id] = (next_valid_iterator != input_queue_[obj_id]->end()) ? *next_valid_iterator : 0; if (scheduled_event_pointer_[obj_id]) { unsigned int scheduler_id = input_queue_scheduler_map_[obj_id]; schedule_queue_lock_[scheduler_id].lock(); schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]); schedule_queue_lock_[scheduler_id].unlock(); } (*track_processed_event_[obj_id]).erase(*neg_iterator); (*track_processed_event_[obj_id]).erase(*pos_iterator); input_queue_[obj_id]->erase(neg_iterator); input_queue_[obj_id]->erase(pos_iterator); } void TimeWarpEventSet::fossilCollectAll (unsigned int fossil_collect_time) { for (unsigned int obj_id = 0; obj_id < num_of_objects_; obj_id++) { acquireInputQueueLock(obj_id); auto event_iterator = input_queue_[obj_id]->begin(); for (; event_iterator != input_queue_[obj_id]->end(); event_iterator++) { if ((*event_iterator)->timestamp() >= fossil_collect_time) { break; } } if (event_iterator != input_queue_[obj_id]->begin()) { input_queue_[obj_id]->erase(input_queue_[obj_id]->begin(), std::prev(event_iterator)); } releaseInputQueueLock(obj_id); } } } // namespace warped <commit_msg>modified the fossilCollectAll() for changes in other aspects of event set.<commit_after>#include <algorithm> #include <cassert> #include <string> #include "TimeWarpEventSet.hpp" #include "utility/warnings.hpp" namespace warped { void TimeWarpEventSet::initialize (unsigned int num_of_objects, unsigned int num_of_schedulers, unsigned int num_of_worker_threads) { num_of_objects_ = num_of_objects; num_of_schedulers_ = num_of_schedulers; /* Create the input queues and their locks. Also create the input queue to schedule queue map. */ input_queue_lock_ = make_unique<std::mutex []>(num_of_objects); for (unsigned int obj_id = 0; obj_id < num_of_objects; obj_id++) { input_queue_.push_back( make_unique<std::multiset<std::shared_ptr<Event>, compareEvents>>()); track_processed_event_.push_back( make_unique<std::unordered_map<std::shared_ptr<Event>, bool>>()); lowest_unprocessed_event_pointer_.push_back(0); last_processed_event_pointer_.push_back(0); scheduled_event_pointer_.push_back(0); input_queue_scheduler_map_.push_back(obj_id % num_of_schedulers); } /* Create the schedule queues and their locks. */ for (unsigned int scheduler_id = 0; scheduler_id < num_of_schedulers; scheduler_id++) { schedule_queue_.push_back(make_unique< std::multiset<std::shared_ptr<Event>, compareEvents>>()); } schedule_queue_lock_ = make_unique<std::mutex []>(num_of_schedulers); /* Map worker threads to schedule queues. */ for (unsigned int thread_id = 0; thread_id < num_of_worker_threads; thread_id++) { worker_thread_scheduler_map_.push_back(thread_id % num_of_schedulers); } } void TimeWarpEventSet::acquireInputQueueLock (unsigned int obj_id) { input_queue_lock_[obj_id].lock(); } void TimeWarpEventSet::releaseInputQueueLock (unsigned int obj_id) { input_queue_lock_[obj_id].unlock(); } void TimeWarpEventSet::insertEvent (unsigned int obj_id, std::shared_ptr<Event> event) { bool causal_order_ok = true; auto event_iterator = input_queue_[obj_id]->insert(event); (*track_processed_event_[obj_id])[event] = false; // If event is negative // Assumption: Positive event arrives earlier than its negative counterpart if (event->event_type_ == EventType::NEGATIVE) { auto next_iterator = std::next(event_iterator); // If next event is the positive counterpart if ((next_iterator != input_queue_[obj_id]->end()) && (**next_iterator == *event) && ((*next_iterator)->event_type_ == EventType::POSITIVE)) { // If no event is currently scheduled (all current events processed) if (!scheduled_event_pointer_[obj_id]) { scheduled_event_pointer_[obj_id] = event; causal_order_ok = false; } else { // Scheduled event present // If positive counterpart is currently scheduled if (scheduled_event_pointer_[obj_id] == *next_iterator) { causal_order_ok = false; } else if (**next_iterator < *scheduled_event_pointer_[obj_id]) { // If negative event is supposed to cause a rollback causal_order_ok = false; } else { // It is ok to delete the negative event (*track_processed_event_[obj_id]).erase(*event_iterator); (*track_processed_event_[obj_id]).erase(*next_iterator); input_queue_[obj_id]->erase(event_iterator); input_queue_[obj_id]->erase(next_iterator); } } } else { // If no positive counterpart found assert(0); } } else { // Positive event // If no event is currently scheduled (all current events processed) if (!scheduled_event_pointer_[obj_id]) { scheduled_event_pointer_[obj_id] = event; // Initial event should not be classified as a potential straggler if ((input_queue_[obj_id]->size() > 1) && (event != *input_queue_[obj_id]->rbegin())) { causal_order_ok = false; } } else { // Scheduled event present // If event is smaller than the one scheduled if (*event < *scheduled_event_pointer_[obj_id]) { causal_order_ok = false; } } } // If inserted event is the one scheduled, insert into schedule queue if (scheduled_event_pointer_[obj_id] == event) { unsigned int scheduler_id = input_queue_scheduler_map_[obj_id]; schedule_queue_lock_[scheduler_id].lock(); schedule_queue_[scheduler_id]->insert(event); schedule_queue_lock_[scheduler_id].unlock(); } if (!causal_order_ok) { // If unprocessed event already exists if (lowest_unprocessed_event_pointer_[obj_id]) { // If event less than existing lowest unprocessed event if ((*event < *lowest_unprocessed_event_pointer_[obj_id]) || ((*event == *lowest_unprocessed_event_pointer_[obj_id]) && (event->event_type_ < lowest_unprocessed_event_pointer_[obj_id]->event_type_))) { lowest_unprocessed_event_pointer_[obj_id] = event; } } else { // Unprocessed event does not exist lowest_unprocessed_event_pointer_[obj_id] = event; } } } std::shared_ptr<Event> TimeWarpEventSet::getEvent (unsigned int thread_id) { unsigned int scheduler_id = worker_thread_scheduler_map_[thread_id]; schedule_queue_lock_[scheduler_id].lock(); auto event_iterator = schedule_queue_[scheduler_id]->begin(); auto event = (event_iterator != schedule_queue_[scheduler_id]->end()) ? *event_iterator : nullptr; if (event) { schedule_queue_[scheduler_id]->erase(event_iterator); } schedule_queue_lock_[scheduler_id].unlock(); return event; } bool TimeWarpEventSet::isRollbackRequired(unsigned int obj_id) { bool rollback_req = true; // If no events have been processed till that point if (!last_processed_event_pointer_[obj_id]) { rollback_req = false; } else { // When atleast one event has been processed auto last_processed_event_iterator = input_queue_[obj_id]->find(last_processed_event_pointer_[obj_id]); assert (last_processed_event_iterator != input_queue_[obj_id]->end()); auto event_iterator = std::next(last_processed_event_iterator); if (event_iterator != input_queue_[obj_id]->end()) { // If the lowest unprocessed event is immediately next to the last processed event if (lowest_unprocessed_event_pointer_[obj_id] == *event_iterator) { rollback_req = false; } } } return rollback_req; } void TimeWarpEventSet::lastProcessedEvent (unsigned int obj_id, std::shared_ptr<Event> event) { last_processed_event_pointer_[obj_id] = event; } void TimeWarpEventSet::processedEvent (unsigned int obj_id, std::shared_ptr<Event> event) { (*track_processed_event_[obj_id])[event] = true; lastProcessedEvent(obj_id, event); } std::shared_ptr<Event> TimeWarpEventSet::getLowestUnprocessedEvent (unsigned int obj_id) { return lowest_unprocessed_event_pointer_[obj_id]; } void TimeWarpEventSet::resetLowestUnprocessedEvent (unsigned int obj_id) { lowest_unprocessed_event_pointer_[obj_id] = 0; } std::unique_ptr<std::vector<std::shared_ptr<Event>>> TimeWarpEventSet::getEventsForCoastForward ( unsigned int obj_id, std::shared_ptr<Event> straggler_event, std::shared_ptr<Event> restored_state_event) { auto events = make_unique<std::vector<std::shared_ptr<Event>>>(); auto straggler_iterator = input_queue_[obj_id]->find(straggler_event); auto restored_event_iterator = input_queue_[obj_id]->find(restored_state_event); assert(straggler_iterator != input_queue_[obj_id]->end()); assert(restored_event_iterator != input_queue_[obj_id]->end()); do { straggler_iterator--; assert(*straggler_iterator); if (straggler_iterator == restored_event_iterator) { break; } if ((*track_processed_event_[obj_id])[*straggler_iterator]) { events->push_back(*straggler_iterator); } } while (straggler_iterator != input_queue_[obj_id]->begin()); return (std::move(events)); } void TimeWarpEventSet::startScheduling (unsigned int obj_id) { auto straggler_event = lowest_unprocessed_event_pointer_[obj_id]; if (scheduled_event_pointer_[obj_id]) { // If there is a chance of causal order violation if (straggler_event) { auto event_iterator = input_queue_[obj_id]->find(straggler_event); if (event_iterator == input_queue_[obj_id]->end()) { assert(0); } scheduled_event_pointer_[obj_id] = straggler_event; } else { // Causal order auto event_iterator = input_queue_[obj_id]->find(scheduled_event_pointer_[obj_id]); if (event_iterator == input_queue_[obj_id]->end()) { assert(0); } event_iterator++; scheduled_event_pointer_[obj_id] = (event_iterator != input_queue_[obj_id]->end()) ? *event_iterator : 0; } if (scheduled_event_pointer_[obj_id]) { unsigned int scheduler_id = input_queue_scheduler_map_[obj_id]; schedule_queue_lock_[scheduler_id].lock(); schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]); schedule_queue_lock_[scheduler_id].unlock(); } } else { assert(0); } } void TimeWarpEventSet::cancelEvent (unsigned int obj_id, std::shared_ptr<Event> cancel_event) { auto neg_iterator = input_queue_[obj_id]->find(cancel_event); assert(neg_iterator != input_queue_[obj_id]->end()); auto pos_iterator = std::next(neg_iterator); assert(**pos_iterator == **neg_iterator); assert((*pos_iterator)->event_type_ == EventType::POSITIVE); auto next_valid_iterator = std::next(neg_iterator, 2); scheduled_event_pointer_[obj_id] = (next_valid_iterator != input_queue_[obj_id]->end()) ? *next_valid_iterator : 0; if (scheduled_event_pointer_[obj_id]) { unsigned int scheduler_id = input_queue_scheduler_map_[obj_id]; schedule_queue_lock_[scheduler_id].lock(); schedule_queue_[scheduler_id]->insert(scheduled_event_pointer_[obj_id]); schedule_queue_lock_[scheduler_id].unlock(); } (*track_processed_event_[obj_id]).erase(*neg_iterator); (*track_processed_event_[obj_id]).erase(*pos_iterator); input_queue_[obj_id]->erase(neg_iterator); input_queue_[obj_id]->erase(pos_iterator); } void TimeWarpEventSet::fossilCollectAll (unsigned int fossil_collect_time) { for (unsigned int obj_id = 0; obj_id < num_of_objects_; obj_id++) { acquireInputQueueLock(obj_id); auto event_iterator = input_queue_[obj_id]->begin(); while (event_iterator != input_queue_[obj_id]->end()) { if ((*event_iterator)->timestamp() >= fossil_collect_time) { break; } (*track_processed_event_[obj_id]).erase(*event_iterator); input_queue_[obj_id]->erase(event_iterator); event_iterator = input_queue_[obj_id]->begin(); } releaseInputQueueLock(obj_id); } } } // namespace warped <|endoftext|>
<commit_before>#include "opencv2/highgui/highgui.hpp" #include "opencv2/photo/photo.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "image_process.hpp" #include <iostream> #include <cstdio> #include <cstdlib> #include <vector> #include <queue> #include <map> #include <set> #include <cmath> #include <cstdint> using namespace cv; using namespace std; typedef vector< pair<int, RotatedRect> > ellipse_list; inline double radians(double deg) { return deg / 180.0 * M_PI; } inline double eccentricity(const RotatedRect &box) { double a = box.size.height, b = box.size.width; return sqrt(1.0 - (b*b)/(a*a)); } Point quick_find_center(const Mat &gray) { Mat edges; Canny(gray, edges, 35, 45); GaussianBlur(edges, edges, Size(7, 7), 3); edges = gray; Mat mdx, mdy; Sobel(edges, mdx, CV_16S, 1, 0); Sobel(edges, mdy, CV_16S, 0, 1); long long a, b, d, p, q; long long &c = b; a = b = d = p = q = 0; for (int x=0; x<gray.cols; x++) for (int y=0; y<gray.rows; y++) { int32_t dx = mdx.at<int16_t>(y, x), dy = mdy.at<int16_t>(y, x); a += dy*dy; b -= dx*dy; d += dx*dx; p += x*dy*dy - y*dx*dy; q += y*dx*dx - x*dx*dy; } Mat left = (Mat_<double>(2,2) << a,b,c,d); Mat right = (Mat_<double>(2,1) << p,q); Mat ans; solve(left, right, ans); return Point(ans); } void filter_hue_val(const Mat &hsv, Mat &dst, int min_val=20) { vector<Mat> hsvChannels(3); split(hsv, hsvChannels); Mat mask1; threshold(hsvChannels[2], mask1, 0, 255, CV_THRESH_OTSU); MatND hist; int histSize[] = {180}; int channels[] = {0}; float h_range[] = {0, 180}; const float* ranges[] = {h_range}; calcHist(&(hsvChannels[0]), 1, channels, mask1, hist, 1, histSize, ranges); hist.at<float>(0) = 0; int maxLoc[1]; minMaxIdx(hist, 0, 0, 0, maxLoc); Mat mask2; inRange(hsvChannels[0], *maxLoc-10, *maxLoc+10, mask2); mask1 &= mask2; bitwise_and(hsvChannels[2], mask1, dst); dst -= min_val; } void auto_crop(Mat *imgs[], double inner_crop=0.08) { Mat gray = (*imgs[0]).clone(); vector< vector<Point> > contours; findContours(gray, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); vector<Point> points; for(size_t i= 0; i < contours.size(); i++) for(size_t j= 0; j < contours[i].size(); j++) points.push_back(contours[i][j]); RotatedRect rect = points.size() ? minAreaRect(points) \ : RotatedRect(Point(0, 0), Size(1, 1), 0); if (rect.angle < -45.0) { Size t = Size(rect.size.height, rect.size.width); rect = RotatedRect(rect.center, t, rect.angle + 90.0); } Mat m = getRotationMatrix2D(rect.center, rect.angle, 1); Size roi_size = Size(rect.size.width * (1-inner_crop), rect.size.height * (1-inner_crop)); if (roi_size.area() <= 0) roi_size.width = roi_size.height = 1; Point roi_center = Point(rect.center.x - roi_size.width/2, rect.center.y - roi_size.height/2); if (rect.center.x - roi_size.width/2 < 0) roi_size = Size(rect.center.x*2, roi_size.height); if (rect.center.y - roi_size.height/2 < 0) roi_size = Size(roi_size.width, rect.center.y*2); Rect roi = Rect(roi_center, roi_size); Size ws = Size(rect.center.x + roi_size.width/2 + 1, rect.center.y + roi_size.height/2 + 1); for (Mat **p = imgs; *p; p++) { warpAffine(**p, **p, m, ws); Mat cropped = cv::Mat(**p, roi); cropped.copyTo(**p); } } void auto_resize(Mat *imgs[], int max_dim_size = 1200) { Size si = (*imgs[0]).size(); if (si.width > si.height) si = Size(max_dim_size, si.height*(1.0*max_dim_size/si.width)); else si = Size(si.width*(1.0*max_dim_size/si.height), max_dim_size); for (Mat **p = imgs; *p; p++) resize(**p, **p, si); } void get_sobel(const Mat &gray, Mat &dst) { Mat dx, dy; Sobel(gray, dx, CV_32F, 1, 0); Sobel(gray, dy, CV_32F, 0, 1); multiply(dx, dx, dx); multiply(dy, dy, dy); add(dx, dy, dst); sqrt(dst, dst); convertScaleAbs(dst, dst); threshold(dst, dst, 0, 255, CV_THRESH_OTSU); } void detect_ellipses(const Mat &bin, ellipse_list &ellipses, int min_pts = 500, int merge_overlap = 8, double overlap_detect_dt = M_PI/100.0, double max_ecc = 0.32) { Mat labels, stats, centroids; int nLabels = connectedComponentsWithStats(bin, labels, stats, centroids); vector<Point> *all_points = new vector<Point>[nLabels]; for (int i=0; i<labels.cols; i++) for (int j = 0; j < labels.rows; j++) { int flag = labels.at<int32_t>(j, i); int area = stats.at<int32_t>(flag, CC_STAT_AREA); if (flag != 0 and area > min_pts) all_points[flag].push_back(Point(i, j)); } for (int flag=1; flag<nLabels; flag++) { int area = stats.at<int32_t>(flag, CC_STAT_AREA); if (area <= min_pts) continue; vector<Point> points = all_points[flag]; RotatedRect el = fitEllipse(points); set<int> merged_flags; merged_flags.insert(0); merged_flags.insert(flag); for (int i=0; i<merge_overlap and eccentricity(el) < max_ecc; i++) { map<int, int> counts; double a = el.size.height / 2.0, b = el.size.width / 2.0, theta = radians(el.angle); // test overlap at some sample points on ellipse for (double t=-M_PI*2; t<M_PI*2; t+=overlap_detect_dt) { double x = el.center.x + b*cos(t)*cos(theta) - a*sin(t)*sin(theta), y = el.center.y + b*cos(t)*sin(theta) + a*sin(t)*cos(theta); if (y<0 or y>=labels.rows or x<0 or x>=labels.cols) continue; int oflag = labels.at<int32_t>((int)y, (int)x); if (merged_flags.find(oflag) == merged_flags.end()) counts[oflag]++; } int oflag = 0; counts[0] = 0; for(auto it=counts.begin(); it!=counts.end(); it++) { int key = it->first, value = it->second; if (counts[oflag] < value) oflag = key; } if (oflag == 0) // no overlap found break; vector<Point> &opts = all_points[oflag]; if (opts.size() > points.size()) // don't merge larger area break; points.insert(points.end(), opts.begin(), opts.end()); el = cv::fitEllipse(points); merged_flags.insert(oflag); } if (eccentricity(el) < max_ecc) { ellipses.push_back(make_pair(points.size(), el)); } } delete[] all_points; } RotatedRect average_allipse(const ellipse_list ellipses, double center_within_ra=4, double dt=M_PI/20) { double &R = center_within_ra; map<pair<int, int>, int> cnt; int max_count = 0; for (auto pr: ellipses) { int count = pr.first; RotatedRect &el = pr.second; Point c = el.center; for (int x=c.x-R; x<=c.x+R; x++) { int dx = x - c.x; double max_dy = sqrt(fabs(R*R-dx*dx)); for (int y=c.y-max_dy; y<=c.y+max_dy; y++) { pair<int, int> p = make_pair(x, y); if ((cnt[p] += count) > max_count) max_count = cnt[p]; } } } set<int> selected; for(auto it=cnt.begin(); it!=cnt.end(); it++) { if (it->second == max_count) { int x = it->first.first, y = it->first.second; for (size_t i=0; i<ellipses.size(); i++) { const RotatedRect &el = ellipses[i].second; Point c = el.center; if (hypot(c.x-x, c.y-y) <= R) selected.insert(i); } } } double x_accu, y_accu, accu; x_accu = y_accu = accu = 0.0; for (int i: selected) { const RotatedRect &el = ellipses[i].second; int count = ellipses[i].first; x_accu += el.center.x * count; y_accu += el.center.y * count; accu += count; } if (accu == 0.0) return RotatedRect(Point(0, 0), Size(0, 0), 0); vector<Point> new_el; for (double t=-M_PI*2; t<M_PI*2; t+=dt) { double x_accu, y_accu; x_accu = y_accu = 0.0; for (int i: selected) { const RotatedRect &el = ellipses[i].second; int count = ellipses[i].first; double x0 = el.center.x, y0 = el.center.y; double dt = t-radians(el.angle); double b = el.size.width/2, a = el.size.height/2; double r = a*b / hypot(a*cos(dt), b*sin(dt)); double x = x0 - r*cos(t), y = y0 - r*sin(t); x_accu += x * count; y_accu += y * count; } new_el.push_back(Point(x_accu/accu, y_accu/accu)); } RotatedRect box = fitEllipse(new_el); return box; } void _dynamic_erode_dilate(Mat &bin, Point center, double dt, uchar first, uchar second) { Mat new_gray(bin.size(), CV_8U); for (int x=0; x<bin.cols; x++) for (int y=0; y<bin.rows; y++) { int v = bin.at<uchar>(y, x); bool todo = (v == first); double rx = x - center.x, ry = y - center.y; double r = hypot(rx, ry), t = atan2(ry, rx); Point p1(center.x+r*cos(t+dt), center.y+r*sin(t+dt)); LineIterator it(bin, p1, Point(x, y)); for (int i=0; not todo and i<it.count; i++, ++it) if (*(uchar*)*it == first) todo = true; Point p2(center.x+r*cos(t-dt), center.y+r*sin(t-dt)); LineIterator it2(bin, p2, Point(x, y)); for (int i=0; not todo and i<it2.count; i++, ++it2) if (*(uchar*)*it2 == first) todo = true; new_gray.at<uchar>(y, x) = todo ? first : second; } new_gray.copyTo(bin); } void dynamic_erode(Mat &bin, Point center, double dt) { _dynamic_erode_dilate(bin, center, dt, 0, 255); } void dynamic_dilate(Mat &bin, Point center, double dt) { _dynamic_erode_dilate(bin, center, dt, 255, 0); } void elliptical_integrate(const Mat &gray, RotatedRect &el, vector<double> &avg) { double theta = radians(el.angle); double ratio = 1.0 * el.size.width / el.size.height; double cos_ = cos(theta), sin_ = sin(theta); double cx = el.center.x, cy = el.center.y; vector< array<uint32_t, 2> > mk; if (std::isnan(ratio)) ratio = 1.0; for (int x=0; x<gray.cols; x++) for (int y=0; y<gray.rows; y++) { double dx = x - cx, dy = y - cy; int r = (int)hypot(dx*cos_+dy*sin_, (-dx*sin_+dy*cos_)*ratio); if (r >= (int)mk.size()) mk.resize(r+1); mk[r][0]++; mk[r][1] += gray.at<uchar>(y, x); } avg.clear(); avg.reserve(mk.size()); for (auto a: mk) avg.push_back(a[0]>0 ? (double)a[1]/a[0] : 0.0); } void preprocess(Mat &bgr, Mat &gray) { Mat hsv; cvtColor(bgr, hsv, CV_BGR2HSV); filter_hue_val(hsv, gray); Mat *gray_bgr[] = { &gray, &bgr, NULL }; equalizeHist(gray, gray); auto_crop(gray_bgr); auto_resize(gray_bgr); } RotatedRect get_rbox(Mat &im) { ellipse_list ellipses; detect_ellipses(im, ellipses); return average_allipse(ellipses); } <commit_msg>Seems the code is of no use<commit_after>#include "opencv2/highgui/highgui.hpp" #include "opencv2/photo/photo.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "image_process.hpp" #include <iostream> #include <cstdio> #include <cstdlib> #include <vector> #include <queue> #include <map> #include <set> #include <cmath> #include <cstdint> using namespace cv; using namespace std; typedef vector< pair<int, RotatedRect> > ellipse_list; inline double radians(double deg) { return deg / 180.0 * M_PI; } inline double eccentricity(const RotatedRect &box) { double a = box.size.height, b = box.size.width; return sqrt(1.0 - (b*b)/(a*a)); } Point quick_find_center(const Mat &gray) { Mat edges; Canny(gray, edges, 35, 45); GaussianBlur(edges, edges, Size(7, 7), 3); edges = gray; Mat mdx, mdy; Sobel(edges, mdx, CV_16S, 1, 0); Sobel(edges, mdy, CV_16S, 0, 1); long long a, b, d, p, q; long long &c = b; a = b = d = p = q = 0; for (int x=0; x<gray.cols; x++) for (int y=0; y<gray.rows; y++) { int32_t dx = mdx.at<int16_t>(y, x), dy = mdy.at<int16_t>(y, x); a += dy*dy; b -= dx*dy; d += dx*dx; p += x*dy*dy - y*dx*dy; q += y*dx*dx - x*dx*dy; } Mat left = (Mat_<double>(2,2) << a,b,c,d); Mat right = (Mat_<double>(2,1) << p,q); Mat ans; solve(left, right, ans); return Point(ans); } void filter_hue_val(const Mat &hsv, Mat &dst) { vector<Mat> hsvChannels(3); split(hsv, hsvChannels); Mat mask1; threshold(hsvChannels[2], mask1, 0, 255, CV_THRESH_OTSU); MatND hist; int histSize[] = {180}; int channels[] = {0}; float h_range[] = {0, 180}; const float* ranges[] = {h_range}; calcHist(&(hsvChannels[0]), 1, channels, mask1, hist, 1, histSize, ranges); hist.at<float>(0) = 0; int maxLoc[1]; minMaxIdx(hist, 0, 0, 0, maxLoc); Mat mask2; inRange(hsvChannels[0], *maxLoc-10, *maxLoc+10, mask2); mask1 &= mask2; bitwise_and(hsvChannels[2], mask1, dst); } void auto_crop(Mat *imgs[], double inner_crop=0.08) { Mat gray = (*imgs[0]).clone(); vector< vector<Point> > contours; findContours(gray, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); vector<Point> points; for(size_t i= 0; i < contours.size(); i++) for(size_t j= 0; j < contours[i].size(); j++) points.push_back(contours[i][j]); RotatedRect rect = points.size() ? minAreaRect(points) \ : RotatedRect(Point(0, 0), Size(1, 1), 0); if (rect.angle < -45.0) { Size t = Size(rect.size.height, rect.size.width); rect = RotatedRect(rect.center, t, rect.angle + 90.0); } Mat m = getRotationMatrix2D(rect.center, rect.angle, 1); Size roi_size = Size(rect.size.width * (1-inner_crop), rect.size.height * (1-inner_crop)); if (roi_size.area() <= 0) roi_size.width = roi_size.height = 1; Point roi_center = Point(rect.center.x - roi_size.width/2, rect.center.y - roi_size.height/2); if (rect.center.x - roi_size.width/2 < 0) roi_size = Size(rect.center.x*2, roi_size.height); if (rect.center.y - roi_size.height/2 < 0) roi_size = Size(roi_size.width, rect.center.y*2); Rect roi = Rect(roi_center, roi_size); Size ws = Size(rect.center.x + roi_size.width/2 + 1, rect.center.y + roi_size.height/2 + 1); for (Mat **p = imgs; *p; p++) { warpAffine(**p, **p, m, ws); Mat cropped = cv::Mat(**p, roi); cropped.copyTo(**p); } } void auto_resize(Mat *imgs[], int max_dim_size = 1200) { Size si = (*imgs[0]).size(); if (si.width > si.height) si = Size(max_dim_size, si.height*(1.0*max_dim_size/si.width)); else si = Size(si.width*(1.0*max_dim_size/si.height), max_dim_size); for (Mat **p = imgs; *p; p++) resize(**p, **p, si); } void get_sobel(const Mat &gray, Mat &dst) { Mat dx, dy; Sobel(gray, dx, CV_32F, 1, 0); Sobel(gray, dy, CV_32F, 0, 1); multiply(dx, dx, dx); multiply(dy, dy, dy); add(dx, dy, dst); sqrt(dst, dst); convertScaleAbs(dst, dst); threshold(dst, dst, 0, 255, CV_THRESH_OTSU); } void detect_ellipses(const Mat &bin, ellipse_list &ellipses, int min_pts = 500, int merge_overlap = 8, double overlap_detect_dt = M_PI/100.0, double max_ecc = 0.32) { Mat labels, stats, centroids; int nLabels = connectedComponentsWithStats(bin, labels, stats, centroids); vector<Point> *all_points = new vector<Point>[nLabels]; for (int i=0; i<labels.cols; i++) for (int j = 0; j < labels.rows; j++) { int flag = labels.at<int32_t>(j, i); int area = stats.at<int32_t>(flag, CC_STAT_AREA); if (flag != 0 and area > min_pts) all_points[flag].push_back(Point(i, j)); } for (int flag=1; flag<nLabels; flag++) { int area = stats.at<int32_t>(flag, CC_STAT_AREA); if (area <= min_pts) continue; vector<Point> points = all_points[flag]; RotatedRect el = fitEllipse(points); set<int> merged_flags; merged_flags.insert(0); merged_flags.insert(flag); for (int i=0; i<merge_overlap and eccentricity(el) < max_ecc; i++) { map<int, int> counts; double a = el.size.height / 2.0, b = el.size.width / 2.0, theta = radians(el.angle); // test overlap at some sample points on ellipse for (double t=-M_PI*2; t<M_PI*2; t+=overlap_detect_dt) { double x = el.center.x + b*cos(t)*cos(theta) - a*sin(t)*sin(theta), y = el.center.y + b*cos(t)*sin(theta) + a*sin(t)*cos(theta); if (y<0 or y>=labels.rows or x<0 or x>=labels.cols) continue; int oflag = labels.at<int32_t>((int)y, (int)x); if (merged_flags.find(oflag) == merged_flags.end()) counts[oflag]++; } int oflag = 0; counts[0] = 0; for(auto it=counts.begin(); it!=counts.end(); it++) { int key = it->first, value = it->second; if (counts[oflag] < value) oflag = key; } if (oflag == 0) // no overlap found break; vector<Point> &opts = all_points[oflag]; if (opts.size() > points.size()) // don't merge larger area break; points.insert(points.end(), opts.begin(), opts.end()); el = cv::fitEllipse(points); merged_flags.insert(oflag); } if (eccentricity(el) < max_ecc) { ellipses.push_back(make_pair(points.size(), el)); } } delete[] all_points; } RotatedRect average_allipse(const ellipse_list ellipses, double center_within_ra=4, double dt=M_PI/20) { double &R = center_within_ra; map<pair<int, int>, int> cnt; int max_count = 0; for (auto pr: ellipses) { int count = pr.first; RotatedRect &el = pr.second; Point c = el.center; for (int x=c.x-R; x<=c.x+R; x++) { int dx = x - c.x; double max_dy = sqrt(fabs(R*R-dx*dx)); for (int y=c.y-max_dy; y<=c.y+max_dy; y++) { pair<int, int> p = make_pair(x, y); if ((cnt[p] += count) > max_count) max_count = cnt[p]; } } } set<int> selected; for(auto it=cnt.begin(); it!=cnt.end(); it++) { if (it->second == max_count) { int x = it->first.first, y = it->first.second; for (size_t i=0; i<ellipses.size(); i++) { const RotatedRect &el = ellipses[i].second; Point c = el.center; if (hypot(c.x-x, c.y-y) <= R) selected.insert(i); } } } double x_accu, y_accu, accu; x_accu = y_accu = accu = 0.0; for (int i: selected) { const RotatedRect &el = ellipses[i].second; int count = ellipses[i].first; x_accu += el.center.x * count; y_accu += el.center.y * count; accu += count; } if (accu == 0.0) return RotatedRect(Point(0, 0), Size(0, 0), 0); vector<Point> new_el; for (double t=-M_PI*2; t<M_PI*2; t+=dt) { double x_accu, y_accu; x_accu = y_accu = 0.0; for (int i: selected) { const RotatedRect &el = ellipses[i].second; int count = ellipses[i].first; double x0 = el.center.x, y0 = el.center.y; double dt = t-radians(el.angle); double b = el.size.width/2, a = el.size.height/2; double r = a*b / hypot(a*cos(dt), b*sin(dt)); double x = x0 - r*cos(t), y = y0 - r*sin(t); x_accu += x * count; y_accu += y * count; } new_el.push_back(Point(x_accu/accu, y_accu/accu)); } RotatedRect box = fitEllipse(new_el); return box; } void _dynamic_erode_dilate(Mat &bin, Point center, double dt, uchar first, uchar second) { Mat new_gray(bin.size(), CV_8U); for (int x=0; x<bin.cols; x++) for (int y=0; y<bin.rows; y++) { int v = bin.at<uchar>(y, x); bool todo = (v == first); double rx = x - center.x, ry = y - center.y; double r = hypot(rx, ry), t = atan2(ry, rx); Point p1(center.x+r*cos(t+dt), center.y+r*sin(t+dt)); LineIterator it(bin, p1, Point(x, y)); for (int i=0; not todo and i<it.count; i++, ++it) if (*(uchar*)*it == first) todo = true; Point p2(center.x+r*cos(t-dt), center.y+r*sin(t-dt)); LineIterator it2(bin, p2, Point(x, y)); for (int i=0; not todo and i<it2.count; i++, ++it2) if (*(uchar*)*it2 == first) todo = true; new_gray.at<uchar>(y, x) = todo ? first : second; } new_gray.copyTo(bin); } void dynamic_erode(Mat &bin, Point center, double dt) { _dynamic_erode_dilate(bin, center, dt, 0, 255); } void dynamic_dilate(Mat &bin, Point center, double dt) { _dynamic_erode_dilate(bin, center, dt, 255, 0); } void elliptical_integrate(const Mat &gray, RotatedRect &el, vector<double> &avg) { double theta = radians(el.angle); double ratio = 1.0 * el.size.width / el.size.height; double cos_ = cos(theta), sin_ = sin(theta); double cx = el.center.x, cy = el.center.y; vector< array<uint32_t, 2> > mk; if (std::isnan(ratio)) ratio = 1.0; for (int x=0; x<gray.cols; x++) for (int y=0; y<gray.rows; y++) { double dx = x - cx, dy = y - cy; int r = (int)hypot(dx*cos_+dy*sin_, (-dx*sin_+dy*cos_)*ratio); if (r >= (int)mk.size()) mk.resize(r+1); mk[r][0]++; mk[r][1] += gray.at<uchar>(y, x); } avg.clear(); avg.reserve(mk.size()); for (auto a: mk) avg.push_back(a[0]>0 ? (double)a[1]/a[0] : 0.0); } void preprocess(Mat &bgr, Mat &gray) { Mat hsv; cvtColor(bgr, hsv, CV_BGR2HSV); filter_hue_val(hsv, gray); Mat *gray_bgr[] = { &gray, &bgr, NULL }; equalizeHist(gray, gray); auto_crop(gray_bgr); auto_resize(gray_bgr); } RotatedRect get_rbox(Mat &im) { ellipse_list ellipses; detect_ellipses(im, ellipses); return average_allipse(ellipses); } <|endoftext|>
<commit_before>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "WallsComputation.h" #include "settings/types/Ratio.h" // libArachne #include "WallToolPaths.h" namespace cura { WallsComputation::WallsComputation(const Settings& settings, const LayerIndex layer_nr) : settings(settings) , layer_nr(layer_nr) { } /* * This function is executed in a parallel region based on layer_nr. * When modifying make sure any changes does not introduce data races. * * generateWalls only reads and writes data for the current layer */ void WallsComputation::generateWalls(SliceLayerPart* part) { size_t wall_count = settings.get<size_t>("wall_line_count"); if (wall_count == 0) // Early out if no walls are to be generated { part->print_outline = part->outline; part->inner_area = part->outline; return; } const bool spiralize = settings.get<bool>("magic_spiralize"); const size_t alternate = ((layer_nr % 2) + 2) % 2; if (spiralize && layer_nr < LayerIndex(settings.get<size_t>("initial_bottom_layers")) && alternate == 1) //Add extra insets every 2 layers when spiralizing. This makes bottoms of cups watertight. { wall_count += 5; } if (settings.get<bool>("alternate_extra_perimeter")) { wall_count += alternate; } const bool first_layer = layer_nr == 0; const Ratio line_width_0_factor = first_layer ? 1.0_r : settings.get<ExtruderTrain&>("wall_0_extruder_nr").settings.get<Ratio>("initial_layer_line_width_factor"); const coord_t line_width_0 = settings.get<coord_t>("wall_line_width_0") * line_width_0_factor; const Ratio line_width_x_factor = first_layer ? 1.0_r : settings.get<ExtruderTrain&>("wall_line_width_x").settings.get<Ratio>("initial_layer_line_width_factor"); const coord_t line_width_x = settings.get<coord_t>("wall_line_width_x") * line_width_x_factor; // TODO: Apply the Outer Wall Inset in libArachne toolpaths (CURA-7830) const coord_t wall_0_inset = settings.get<coord_t>("wall_0_inset"); // When spiralizing, generate the spiral insets using simple offsets instead of generating toolpaths if (spiralize) { const bool recompute_outline_based_on_outer_wall = settings.get<bool>("support_enable") && !settings.get<bool>("fill_outline_gaps"); generateSpiralInsets(part, line_width_0, wall_0_inset, recompute_outline_based_on_outer_wall); if (layer_nr <= settings.get<size_t>("bottom_layers")) { WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, settings); part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } } else { WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, settings); part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } part->print_outline = part->outline; } /* * This function is executed in a parallel region based on layer_nr. * When modifying make sure any changes does not introduce data races. * * generateWalls only reads and writes data for the current layer */ void WallsComputation::generateWalls(SliceLayer* layer) { for(SliceLayerPart& part : layer->parts) { generateWalls(&part); } const bool remove_parts_without_walls = !settings.get<bool>("fill_outline_gaps"); //Remove the parts which did not generate a wall. As these parts are too small to print, // and later code can now assume that there is always minimal 1 wall line. for (unsigned int part_idx = 0; part_idx < layer->parts.size(); part_idx++) { if (layer->parts[part_idx].wall_toolpaths.empty() && layer->parts[part_idx].spiral_insets.empty() && remove_parts_without_walls) { if (part_idx != layer->parts.size() - 1) { // move existing part into part to be deleted layer->parts[part_idx] = std::move(layer->parts.back()); } layer->parts.pop_back(); // always remove last element from array (is more efficient) part_idx -= 1; // check the part we just moved here } } } void WallsComputation::generateSpiralInsets(SliceLayerPart *part, coord_t line_width_0, coord_t wall_0_inset, bool recompute_outline_based_on_outer_wall) { part->spiral_insets.push_back(part->outline.offset(-line_width_0 / 2 - wall_0_inset)); //Finally optimize all the polygons. Every point removed saves time in the long run. const ExtruderTrain& train_wall = settings.get<ExtruderTrain&>("wall_0_extruder_nr"); const coord_t maximum_resolution = train_wall.settings.get<coord_t>("meshfix_maximum_resolution"); const coord_t maximum_deviation = train_wall.settings.get<coord_t>("meshfix_maximum_deviation"); part->spiral_insets[0].simplify(maximum_resolution, maximum_deviation); part->spiral_insets[0].removeDegenerateVerts(); if (recompute_outline_based_on_outer_wall) { part->print_outline = part->spiral_insets[0].offset(line_width_0 / 2, ClipperLib::jtSquare); } else { part->print_outline = part->outline; } if (part->spiral_insets[0].empty()) { part->spiral_insets.pop_back(); } } }//namespace cura <commit_msg>Fix compilation warning about comparing signed and unsigned integers<commit_after>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "WallsComputation.h" #include "settings/types/Ratio.h" // libArachne #include "WallToolPaths.h" namespace cura { WallsComputation::WallsComputation(const Settings& settings, const LayerIndex layer_nr) : settings(settings) , layer_nr(layer_nr) { } /* * This function is executed in a parallel region based on layer_nr. * When modifying make sure any changes does not introduce data races. * * generateWalls only reads and writes data for the current layer */ void WallsComputation::generateWalls(SliceLayerPart* part) { size_t wall_count = settings.get<size_t>("wall_line_count"); if (wall_count == 0) // Early out if no walls are to be generated { part->print_outline = part->outline; part->inner_area = part->outline; return; } const bool spiralize = settings.get<bool>("magic_spiralize"); const size_t alternate = ((layer_nr % 2) + 2) % 2; if (spiralize && layer_nr < LayerIndex(settings.get<size_t>("initial_bottom_layers")) && alternate == 1) //Add extra insets every 2 layers when spiralizing. This makes bottoms of cups watertight. { wall_count += 5; } if (settings.get<bool>("alternate_extra_perimeter")) { wall_count += alternate; } const bool first_layer = layer_nr == 0; const Ratio line_width_0_factor = first_layer ? 1.0_r : settings.get<ExtruderTrain&>("wall_0_extruder_nr").settings.get<Ratio>("initial_layer_line_width_factor"); const coord_t line_width_0 = settings.get<coord_t>("wall_line_width_0") * line_width_0_factor; const Ratio line_width_x_factor = first_layer ? 1.0_r : settings.get<ExtruderTrain&>("wall_line_width_x").settings.get<Ratio>("initial_layer_line_width_factor"); const coord_t line_width_x = settings.get<coord_t>("wall_line_width_x") * line_width_x_factor; // TODO: Apply the Outer Wall Inset in libArachne toolpaths (CURA-7830) const coord_t wall_0_inset = settings.get<coord_t>("wall_0_inset"); // When spiralizing, generate the spiral insets using simple offsets instead of generating toolpaths if (spiralize) { const bool recompute_outline_based_on_outer_wall = settings.get<bool>("support_enable") && !settings.get<bool>("fill_outline_gaps"); generateSpiralInsets(part, line_width_0, wall_0_inset, recompute_outline_based_on_outer_wall); if (layer_nr <= static_cast<LayerIndex>(settings.get<size_t>("bottom_layers"))) { WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, settings); part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } } else { WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, settings); part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } part->print_outline = part->outline; } /* * This function is executed in a parallel region based on layer_nr. * When modifying make sure any changes does not introduce data races. * * generateWalls only reads and writes data for the current layer */ void WallsComputation::generateWalls(SliceLayer* layer) { for(SliceLayerPart& part : layer->parts) { generateWalls(&part); } const bool remove_parts_without_walls = !settings.get<bool>("fill_outline_gaps"); //Remove the parts which did not generate a wall. As these parts are too small to print, // and later code can now assume that there is always minimal 1 wall line. for (unsigned int part_idx = 0; part_idx < layer->parts.size(); part_idx++) { if (layer->parts[part_idx].wall_toolpaths.empty() && layer->parts[part_idx].spiral_insets.empty() && remove_parts_without_walls) { if (part_idx != layer->parts.size() - 1) { // move existing part into part to be deleted layer->parts[part_idx] = std::move(layer->parts.back()); } layer->parts.pop_back(); // always remove last element from array (is more efficient) part_idx -= 1; // check the part we just moved here } } } void WallsComputation::generateSpiralInsets(SliceLayerPart *part, coord_t line_width_0, coord_t wall_0_inset, bool recompute_outline_based_on_outer_wall) { part->spiral_insets.push_back(part->outline.offset(-line_width_0 / 2 - wall_0_inset)); //Finally optimize all the polygons. Every point removed saves time in the long run. const ExtruderTrain& train_wall = settings.get<ExtruderTrain&>("wall_0_extruder_nr"); const coord_t maximum_resolution = train_wall.settings.get<coord_t>("meshfix_maximum_resolution"); const coord_t maximum_deviation = train_wall.settings.get<coord_t>("meshfix_maximum_deviation"); part->spiral_insets[0].simplify(maximum_resolution, maximum_deviation); part->spiral_insets[0].removeDegenerateVerts(); if (recompute_outline_based_on_outer_wall) { part->print_outline = part->spiral_insets[0].offset(line_width_0 / 2, ClipperLib::jtSquare); } else { part->print_outline = part->outline; } if (part->spiral_insets[0].empty()) { part->spiral_insets.pop_back(); } } }//namespace cura <|endoftext|>
<commit_before>// Copyright 2011 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. // // Author: jmarantz@google.com (Joshua Marantz) #include "net/instaweb/rewriter/public/process_context.h" #include "base/logging.h" #include "pagespeed/kernel/http/google_url.h" #include "pagespeed/kernel/html/html_keywords.h" #include "pagespeed/kernel/http/domain_registry.h" #include "pagespeed/kernel/js/js_tokenizer.h" #include "pagespeed/kernel/util/gflags.h" #include "google/protobuf/stubs/common.h" using namespace google; // NOLINT namespace { int construction_count = 0; } // Clean up valgrind-based memory-leak checks by deleting statically allocated // data from various libraries. This must be called both from unit-tests // and from the Apache module, so that valgrind can be run on both of them. namespace net_instaweb { ProcessContext::ProcessContext() : js_tokenizer_patterns_(new pagespeed::js::JsTokenizerPatterns) { ++construction_count; CHECK_EQ(1, construction_count) << "ProcessContext must only be constructed once."; domain_registry::Init(); HtmlKeywords::Init(); // url/url_util.cc lazily initializes its "standard_schemes" table in a // thread-unsafe way and so it must be explicitly initialized prior to thread // creation, and explicitly terminated after thread quiescence. url::Initialize(); } ProcessContext::~ProcessContext() { // Clean up statics from third_party code first. // The command-line flags structures are lazily initialized, but // they are done so in static constructors resulting from DEFINE_int32 // and other similar macros. So they must happen prior to threads // starting up. ShutDownCommandLineFlags(); // The protobuf shutdown infrastructure is lazily initialized in a threadsafe // manner. See third_party/protobuf/src/google/protobuf/stubs/common.cc, // function InitShutdownFunctionsOnce. google::protobuf::ShutdownProtobufLibrary(); url::Shutdown(); HtmlKeywords::ShutDown(); } } // namespace net_instaweb <commit_msg>Give up on cleaning up gflags on exit, it races with some stuff in google-land.<commit_after>// Copyright 2011 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. // // Author: jmarantz@google.com (Joshua Marantz) #include "net/instaweb/rewriter/public/process_context.h" #include "base/logging.h" #include "pagespeed/kernel/http/google_url.h" #include "pagespeed/kernel/html/html_keywords.h" #include "pagespeed/kernel/http/domain_registry.h" #include "pagespeed/kernel/js/js_tokenizer.h" #include "google/protobuf/stubs/common.h" using namespace google; // NOLINT namespace { int construction_count = 0; } // Clean up valgrind-based memory-leak checks by deleting statically allocated // data from various libraries. This must be called both from unit-tests // and from the Apache module, so that valgrind can be run on both of them. namespace net_instaweb { ProcessContext::ProcessContext() : js_tokenizer_patterns_(new pagespeed::js::JsTokenizerPatterns) { ++construction_count; CHECK_EQ(1, construction_count) << "ProcessContext must only be constructed once."; domain_registry::Init(); HtmlKeywords::Init(); // url/url_util.cc lazily initializes its "standard_schemes" table in a // thread-unsafe way and so it must be explicitly initialized prior to thread // creation, and explicitly terminated after thread quiescence. url::Initialize(); } ProcessContext::~ProcessContext() { // Clean up statics from third_party code first. // The protobuf shutdown infrastructure is lazily initialized in a threadsafe // manner. See third_party/protobuf/src/google/protobuf/stubs/common.cc, // function InitShutdownFunctionsOnce. google::protobuf::ShutdownProtobufLibrary(); url::Shutdown(); HtmlKeywords::ShutDown(); } } // namespace net_instaweb <|endoftext|>
<commit_before>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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 <gst/gst.h> #include "ServerMethods.hpp" #include <MediaSet.hpp> #include <string> #include <EventHandler.hpp> #include <KurentoException.hpp> #include <jsonrpc/JsonRpcUtils.hpp> #include <jsonrpc/JsonRpcConstants.hpp> #include <sstream> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #define GST_CAT_DEFAULT kurento_server_methods GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoServerMethods" #define SESSION_ID "sessionId" #define OBJECT "object" #define SUBSCRIPTION "subscription" #define REQUEST_TIMEOUT 20000 /* 20 seconds */ namespace kurento { ServerMethods::ServerMethods (const boost::property_tree::ptree &config) : config (config) { // TODO: Use config to load more factories moduleManager.loadModulesFromDirectories (""); cache = std::shared_ptr<RequestCache> (new RequestCache (REQUEST_TIMEOUT) ); handler.setPreProcess (std::bind (&ServerMethods::preProcess, this, std::placeholders::_1, std::placeholders::_2) ); handler.setPostProcess (std::bind (&ServerMethods::postProcess, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("create", std::bind (&ServerMethods::create, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("release", std::bind (&ServerMethods::release, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("ref", std::bind (&ServerMethods::ref, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unref", std::bind (&ServerMethods::unref, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("describe", std::bind (&ServerMethods::describe, this, std::placeholders::_1, std::placeholders::_2) ); } ServerMethods::~ServerMethods() { } static void requireParams (const Json::Value &params) { if (params == Json::Value::null) { throw JsonRpc::CallException (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "'params' is requiered"); } } static std::string generateUUID () { std::stringstream ss; boost::uuids::uuid uuid = boost::uuids::random_generator() (); ss << uuid; return ss.str(); } void ServerMethods::process (const std::string &request, std::string &response) { handler.process (request, response); } void ServerMethods::keepAliveSession (const std::string &sessionId) { MediaSet::getMediaSet()->keepAliveSession (sessionId); } bool ServerMethods::preProcess (const Json::Value &request, Json::Value &response) { std::string sessionId; std::string resp; int requestId; try { Json::Reader reader; Json::Value params; JsonRpc::getValue (request, JSON_RPC_ID, requestId); JsonRpc::getValue (request, JSON_RPC_PARAMS, params); JsonRpc::getValue (params, SESSION_ID, sessionId); resp = cache->getCachedResponse (sessionId, requestId); GST_DEBUG ("Cached response: %s", resp.c_str() ); /* update response with the one we got from cache */ reader.parse (resp, response); return false; } catch (...) { /* continue processing */ return true; } } void ServerMethods::postProcess (const Json::Value &request, Json::Value &response) { Json::FastWriter writer; std::string sessionId; std::string resp; int requestId; try { Json::Reader reader; JsonRpc::getValue (request, JSON_RPC_ID, requestId); try { Json::Value result; JsonRpc::getValue (response, JSON_RPC_RESULT, result); JsonRpc::getValue (result, SESSION_ID, sessionId); } catch (JsonRpc::CallException &ex) { Json::Value params; JsonRpc::getValue (request, JSON_RPC_PARAMS, params); JsonRpc::getValue (params, SESSION_ID, sessionId); } /* CacheException will be triggered if this response is not cached */ cache->getCachedResponse (sessionId, requestId); } catch (JsonRpc::CallException &e) { /* We could not get some of the required parameters. Ignore */ } catch (CacheException &e) { /* Cache response */ resp = writer.write (response); GST_DEBUG ("Caching: %s", resp.c_str() ); cache->addResponse (sessionId, requestId, resp); } } void ServerMethods::describe (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObjectImpl> obj; std::string subscription; std::string sessionId; std::string objectId; requireParams (params); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } JsonRpc::getValue (params, OBJECT, objectId); try { obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } response["sessionId"] = sessionId; response["type"] = obj->getType (); } void ServerMethods::keepAlive (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string sessionId; requireParams (params); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet()->keepAliveSession (sessionId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::release (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); try { MediaSet::getMediaSet()->release (objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::ref (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string objectId; std::string sessionId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet()->ref (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unref (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; std::string sessionId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet()->unref (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unsubscribe (const Json::Value &params, Json::Value &response) { std::string subscription; std::string sessionId; std::string objectId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, SUBSCRIPTION, subscription); JsonRpc::getValue (params, SESSION_ID, sessionId); MediaSet::getMediaSet()->removeEventHandler (sessionId, objectId, subscription); } void ServerMethods::registerEventHandler (std::shared_ptr<MediaObjectImpl> obj, const std::string &sessionId, const std::string &subscriptionId, std::shared_ptr<EventHandler> handler) { MediaSet::getMediaSet()->addEventHandler (sessionId, obj->getId(), subscriptionId, handler); } std::string ServerMethods::connectEventHandler (std::shared_ptr<MediaObjectImpl> obj, const std::string &sessionId, const std::string &eventType, std::shared_ptr<EventHandler> handler) { std::string subscriptionId; if (!obj->connect (eventType, handler) ) { throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found"); } subscriptionId = generateUUID(); registerEventHandler (obj, sessionId, subscriptionId, handler); return subscriptionId; } void ServerMethods::subscribe (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObjectImpl> obj; std::string eventType; std::string handlerId; std::string sessionId; std::string objectId; requireParams (params); JsonRpc::getValue (params, "type", eventType); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } try { obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId); try { handlerId = eventSubscriptionHandler (obj, sessionId, eventType, params); } catch (std::bad_function_call &e) { throw KurentoException (NOT_IMPLEMENTED, "Current transport does not support events"); } if (handlerId == "") { throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found"); } } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } response["sessionId"] = sessionId; response["value"] = handlerId; } void ServerMethods::invoke (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObjectImpl> obj; std::string sessionId; std::string operation; Json::Value operationParams; std::string objectId; requireParams (params); JsonRpc::getValue (params, "operation", operation); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, "operationParams", operationParams); } catch (JsonRpc::CallException e) { /* operationParams is optional at this point */ } try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } try { Json::Value value; obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId); if (!obj) { throw KurentoException (MEDIA_OBJECT_NOT_FOUND, "Object not found"); } obj->invoke (obj, operation, operationParams, value); response["value"] = value; response["sessionId"] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::create (const Json::Value &params, Json::Value &response) { std::string type; std::shared_ptr<Factory> factory; std::string sessionId; requireParams (params); JsonRpc::getValue (params, "type", type); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } factory = moduleManager.getFactory (type); if (factory) { try { std::shared_ptr <MediaObjectImpl> object; object = std::dynamic_pointer_cast<MediaObjectImpl> ( factory->createObject (config, sessionId, params["constructorParams"]) ); response["value"] = object->getId(); response["sessionId"] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } else { JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "Class '" + type + "' does not exist"); // TODO: Define error data and code throw e; } } ServerMethods::StaticConstructor ServerMethods::staticConstructor; ServerMethods::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <commit_msg>ServerMethods: Use constant for sessionId key<commit_after>/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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 <gst/gst.h> #include "ServerMethods.hpp" #include <MediaSet.hpp> #include <string> #include <EventHandler.hpp> #include <KurentoException.hpp> #include <jsonrpc/JsonRpcUtils.hpp> #include <jsonrpc/JsonRpcConstants.hpp> #include <sstream> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #define GST_CAT_DEFAULT kurento_server_methods GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoServerMethods" #define SESSION_ID "sessionId" #define OBJECT "object" #define SUBSCRIPTION "subscription" #define REQUEST_TIMEOUT 20000 /* 20 seconds */ namespace kurento { ServerMethods::ServerMethods (const boost::property_tree::ptree &config) : config (config) { // TODO: Use config to load more factories moduleManager.loadModulesFromDirectories (""); cache = std::shared_ptr<RequestCache> (new RequestCache (REQUEST_TIMEOUT) ); handler.setPreProcess (std::bind (&ServerMethods::preProcess, this, std::placeholders::_1, std::placeholders::_2) ); handler.setPostProcess (std::bind (&ServerMethods::postProcess, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("create", std::bind (&ServerMethods::create, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("release", std::bind (&ServerMethods::release, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("ref", std::bind (&ServerMethods::ref, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("unref", std::bind (&ServerMethods::unref, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive, this, std::placeholders::_1, std::placeholders::_2) ); handler.addMethod ("describe", std::bind (&ServerMethods::describe, this, std::placeholders::_1, std::placeholders::_2) ); } ServerMethods::~ServerMethods() { } static void requireParams (const Json::Value &params) { if (params == Json::Value::null) { throw JsonRpc::CallException (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "'params' is requiered"); } } static std::string generateUUID () { std::stringstream ss; boost::uuids::uuid uuid = boost::uuids::random_generator() (); ss << uuid; return ss.str(); } void ServerMethods::process (const std::string &request, std::string &response) { handler.process (request, response); } void ServerMethods::keepAliveSession (const std::string &sessionId) { MediaSet::getMediaSet()->keepAliveSession (sessionId); } bool ServerMethods::preProcess (const Json::Value &request, Json::Value &response) { std::string sessionId; std::string resp; int requestId; try { Json::Reader reader; Json::Value params; JsonRpc::getValue (request, JSON_RPC_ID, requestId); JsonRpc::getValue (request, JSON_RPC_PARAMS, params); JsonRpc::getValue (params, SESSION_ID, sessionId); resp = cache->getCachedResponse (sessionId, requestId); GST_DEBUG ("Cached response: %s", resp.c_str() ); /* update response with the one we got from cache */ reader.parse (resp, response); return false; } catch (...) { /* continue processing */ return true; } } void ServerMethods::postProcess (const Json::Value &request, Json::Value &response) { Json::FastWriter writer; std::string sessionId; std::string resp; int requestId; try { Json::Reader reader; JsonRpc::getValue (request, JSON_RPC_ID, requestId); try { Json::Value result; JsonRpc::getValue (response, JSON_RPC_RESULT, result); JsonRpc::getValue (result, SESSION_ID, sessionId); } catch (JsonRpc::CallException &ex) { Json::Value params; JsonRpc::getValue (request, JSON_RPC_PARAMS, params); JsonRpc::getValue (params, SESSION_ID, sessionId); } /* CacheException will be triggered if this response is not cached */ cache->getCachedResponse (sessionId, requestId); } catch (JsonRpc::CallException &e) { /* We could not get some of the required parameters. Ignore */ } catch (CacheException &e) { /* Cache response */ resp = writer.write (response); GST_DEBUG ("Caching: %s", resp.c_str() ); cache->addResponse (sessionId, requestId, resp); } } void ServerMethods::describe (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObjectImpl> obj; std::string subscription; std::string sessionId; std::string objectId; requireParams (params); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } JsonRpc::getValue (params, OBJECT, objectId); try { obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } response[SESSION_ID] = sessionId; response["type"] = obj->getType (); } void ServerMethods::keepAlive (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string sessionId; requireParams (params); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet()->keepAliveSession (sessionId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::release (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); try { MediaSet::getMediaSet()->release (objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::ref (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string objectId; std::string sessionId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet()->ref (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unref (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObject> obj; std::string subscription; std::string objectId; std::string sessionId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, SESSION_ID, sessionId); try { MediaSet::getMediaSet()->unref (sessionId, objectId); } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::unsubscribe (const Json::Value &params, Json::Value &response) { std::string subscription; std::string sessionId; std::string objectId; requireParams (params); JsonRpc::getValue (params, OBJECT, objectId); JsonRpc::getValue (params, SUBSCRIPTION, subscription); JsonRpc::getValue (params, SESSION_ID, sessionId); MediaSet::getMediaSet()->removeEventHandler (sessionId, objectId, subscription); } void ServerMethods::registerEventHandler (std::shared_ptr<MediaObjectImpl> obj, const std::string &sessionId, const std::string &subscriptionId, std::shared_ptr<EventHandler> handler) { MediaSet::getMediaSet()->addEventHandler (sessionId, obj->getId(), subscriptionId, handler); } std::string ServerMethods::connectEventHandler (std::shared_ptr<MediaObjectImpl> obj, const std::string &sessionId, const std::string &eventType, std::shared_ptr<EventHandler> handler) { std::string subscriptionId; if (!obj->connect (eventType, handler) ) { throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found"); } subscriptionId = generateUUID(); registerEventHandler (obj, sessionId, subscriptionId, handler); return subscriptionId; } void ServerMethods::subscribe (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObjectImpl> obj; std::string eventType; std::string handlerId; std::string sessionId; std::string objectId; requireParams (params); JsonRpc::getValue (params, "type", eventType); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } try { obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId); try { handlerId = eventSubscriptionHandler (obj, sessionId, eventType, params); } catch (std::bad_function_call &e) { throw KurentoException (NOT_IMPLEMENTED, "Current transport does not support events"); } if (handlerId == "") { throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found"); } } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } response[SESSION_ID] = sessionId; response["value"] = handlerId; } void ServerMethods::invoke (const Json::Value &params, Json::Value &response) { std::shared_ptr<MediaObjectImpl> obj; std::string sessionId; std::string operation; Json::Value operationParams; std::string objectId; requireParams (params); JsonRpc::getValue (params, "operation", operation); JsonRpc::getValue (params, OBJECT, objectId); try { JsonRpc::getValue (params, "operationParams", operationParams); } catch (JsonRpc::CallException e) { /* operationParams is optional at this point */ } try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } try { Json::Value value; obj = MediaSet::getMediaSet()->getMediaObject (sessionId, objectId); if (!obj) { throw KurentoException (MEDIA_OBJECT_NOT_FOUND, "Object not found"); } obj->invoke (obj, operation, operationParams, value); response["value"] = value; response[SESSION_ID] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } void ServerMethods::create (const Json::Value &params, Json::Value &response) { std::string type; std::shared_ptr<Factory> factory; std::string sessionId; requireParams (params); JsonRpc::getValue (params, "type", type); try { JsonRpc::getValue (params, SESSION_ID, sessionId); } catch (JsonRpc::CallException e) { sessionId = generateUUID (); } factory = moduleManager.getFactory (type); if (factory) { try { std::shared_ptr <MediaObjectImpl> object; object = std::dynamic_pointer_cast<MediaObjectImpl> ( factory->createObject (config, sessionId, params["constructorParams"]) ); response["value"] = object->getId(); response[SESSION_ID] = sessionId; } catch (KurentoException &ex) { Json::Value data; data["code"] = ex.getCode(); data["message"] = ex.getMessage(); JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, ex.what(), data); throw e; } } else { JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT, "Class '" + type + "' does not exist"); // TODO: Define error data and code throw e; } } ServerMethods::StaticConstructor ServerMethods::staticConstructor; ServerMethods::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <|endoftext|>
<commit_before>// Copyright (c) 2014-2016 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "masternode.h" #include "masternode-sync.h" #include "masternodeman.h" #include "protocol.h" extern CWallet* pwalletMain; // Keep track of the active Masternode CActiveMasternode activeMasternode; // Bootup the Masternode, look for a 1000DASH input and register on the network void CActiveMasternode::ManageState() { std::string strError; if(!fMasterNode) return; if (fDebug) LogPrintf("CActiveMasternode::ManageState -- Begin\n"); //need correct blocks to send ping if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageState -- %s\n", GetStatus()); return; } if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) nState = ACTIVE_MASTERNODE_INITIAL; if(nState == ACTIVE_MASTERNODE_INITIAL) { CMasternode *pmn; pmn = mnodeman.Find(pubKeyMasternode); if(pmn != NULL) { pmn->Check(); if((pmn->IsEnabled() || pmn->IsPreEnabled()) && pmn->nProtocolVersion == PROTOCOL_VERSION) EnableRemoteMasterNode(pmn->vin, pmn->addr); } } if(nState != ACTIVE_MASTERNODE_STARTED) { // Set defaults nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = ""; if(pwalletMain->IsLocked()) { strNotCapableReason = "Wallet is locked."; LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } if(pwalletMain->GetBalance() == 0) { nState = ACTIVE_MASTERNODE_INITIAL; LogPrintf("CActiveMasternode::ManageState() -- %s\n", GetStatus()); return; } if(!GetLocal(service)) { strNotCapableReason = "Can't detect external address. Please consider using the externalip configuration option if problem persists."; LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(service.GetPort() != mainnetDefaultPort) { strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } } else if(service.GetPort() == mainnetDefaultPort) { strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } LogPrintf("CActiveMasternode::ManageState -- Checking inbound connection to '%s'\n", service.ToString()); if(!ConnectNode((CAddress)service, NULL, true)) { strNotCapableReason = "Could not connect to " + service.ToString(); LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } // Choose coins to use CPubKey pubKeyCollateral; CKey keyCollateral; if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) { int nInputAge = GetInputAge(vin); if(nInputAge < Params().GetConsensus().nMasternodeMinimumConfirmations){ nState = ACTIVE_MASTERNODE_INPUT_TOO_NEW; strNotCapableReason = strprintf("%s - %d confirmations", GetStatus(), nInputAge); LogPrintf("CActiveMasternode::ManageState -- %s\n", strNotCapableReason); return; } LOCK(pwalletMain->cs_wallet); pwalletMain->LockCoin(vin.prevout); CMasternodeBroadcast mnb; if(!CMasternodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyMasternode, pubKeyMasternode, strError, mnb)) { strNotCapableReason = "Error on CMasternodeBroadcast::Create -- " + strError; LogPrintf("CActiveMasternode::ManageState -- %s\n", strNotCapableReason); return; } //update to masternode list LogPrintf("CActiveMasternode::ManageState -- Update Masternode List\n"); mnodeman.UpdateMasternodeList(mnb); //send to all peers LogPrintf("CActiveMasternode::ManageState -- Relay broadcast, vin=%s\n", vin.ToString()); mnb.Relay(); LogPrintf("CActiveMasternode::ManageState -- Is capable master node!\n"); nState = ACTIVE_MASTERNODE_STARTED; return; } else { strNotCapableReason = "Could not find suitable coins!"; LogPrintf("CActiveMasternode::ManageState -- %s\n", strNotCapableReason); return; } } //send to all peers if(!SendMasternodePing(strError)) { LogPrintf("CActiveMasternode::ManageState -- Error on SendMasternodePing(): %s\n", strError); } } std::string CActiveMasternode::GetStatus() { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode start request sent"; default: return "unknown"; } } bool CActiveMasternode::SendMasternodePing(std::string& strErrorRet) { if(nState != ACTIVE_MASTERNODE_STARTED) { strErrorRet = "Masternode is not in a running status"; return false; } CMasternodePing mnp(vin); if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { strErrorRet = "Couldn't sign Masternode Ping"; return false; } // Update lastPing for our masternode in Masternode list CMasternode* pmn = mnodeman.Find(vin); if(pmn != NULL) { if(pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { strErrorRet = "Too early to send Masternode Ping"; return false; } pmn->lastPing = mnp; mnodeman.mapSeenMasternodePing.insert(std::make_pair(mnp.GetHash(), mnp)); //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if(mnodeman.mapSeenMasternodeBroadcast.count(hash)) mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = mnp; LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", vin.ToString()); mnp.Relay(); return true; } else { // Seems like we are trying to send a ping while the Masternode is not registered in the network strErrorRet = "PrivateSend Masternode List doesn't include our Masternode, shutting down Masternode pinging service! " + vin.ToString(); nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strErrorRet; return false; } } // when starting a Masternode, this can enable to run as a hot wallet with no funds bool CActiveMasternode::EnableRemoteMasterNode(CTxIn& vinNew, CService& serviceNew) { if(!fMasterNode) return false; nState = ACTIVE_MASTERNODE_STARTED; //The values below are needed for signing mnping messages going forward vin = vinNew; service = serviceNew; LogPrintf("CActiveMasternode::EnableHotColdMasterNode -- Enabled! You may shut down the cold daemon.\n"); return true; } <commit_msg>Revert "[UI] Message change when Masternodes is started" (#1053)<commit_after>// Copyright (c) 2014-2016 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "masternode.h" #include "masternode-sync.h" #include "masternodeman.h" #include "protocol.h" extern CWallet* pwalletMain; // Keep track of the active Masternode CActiveMasternode activeMasternode; // Bootup the Masternode, look for a 1000DASH input and register on the network void CActiveMasternode::ManageState() { std::string strError; if(!fMasterNode) return; if (fDebug) LogPrintf("CActiveMasternode::ManageState -- Begin\n"); //need correct blocks to send ping if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveMasternode::ManageState -- %s\n", GetStatus()); return; } if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) nState = ACTIVE_MASTERNODE_INITIAL; if(nState == ACTIVE_MASTERNODE_INITIAL) { CMasternode *pmn; pmn = mnodeman.Find(pubKeyMasternode); if(pmn != NULL) { pmn->Check(); if((pmn->IsEnabled() || pmn->IsPreEnabled()) && pmn->nProtocolVersion == PROTOCOL_VERSION) EnableRemoteMasterNode(pmn->vin, pmn->addr); } } if(nState != ACTIVE_MASTERNODE_STARTED) { // Set defaults nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = ""; if(pwalletMain->IsLocked()) { strNotCapableReason = "Wallet is locked."; LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } if(pwalletMain->GetBalance() == 0) { nState = ACTIVE_MASTERNODE_INITIAL; LogPrintf("CActiveMasternode::ManageState() -- %s\n", GetStatus()); return; } if(!GetLocal(service)) { strNotCapableReason = "Can't detect external address. Please consider using the externalip configuration option if problem persists."; LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(service.GetPort() != mainnetDefaultPort) { strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } } else if(service.GetPort() == mainnetDefaultPort) { strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } LogPrintf("CActiveMasternode::ManageState -- Checking inbound connection to '%s'\n", service.ToString()); if(!ConnectNode((CAddress)service, NULL, true)) { strNotCapableReason = "Could not connect to " + service.ToString(); LogPrintf("CActiveMasternode::ManageState -- not capable: %s\n", strNotCapableReason); return; } // Choose coins to use CPubKey pubKeyCollateral; CKey keyCollateral; if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) { int nInputAge = GetInputAge(vin); if(nInputAge < Params().GetConsensus().nMasternodeMinimumConfirmations){ nState = ACTIVE_MASTERNODE_INPUT_TOO_NEW; strNotCapableReason = strprintf("%s - %d confirmations", GetStatus(), nInputAge); LogPrintf("CActiveMasternode::ManageState -- %s\n", strNotCapableReason); return; } LOCK(pwalletMain->cs_wallet); pwalletMain->LockCoin(vin.prevout); CMasternodeBroadcast mnb; if(!CMasternodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyMasternode, pubKeyMasternode, strError, mnb)) { strNotCapableReason = "Error on CMasternodeBroadcast::Create -- " + strError; LogPrintf("CActiveMasternode::ManageState -- %s\n", strNotCapableReason); return; } //update to masternode list LogPrintf("CActiveMasternode::ManageState -- Update Masternode List\n"); mnodeman.UpdateMasternodeList(mnb); //send to all peers LogPrintf("CActiveMasternode::ManageState -- Relay broadcast, vin=%s\n", vin.ToString()); mnb.Relay(); LogPrintf("CActiveMasternode::ManageState -- Is capable master node!\n"); nState = ACTIVE_MASTERNODE_STARTED; return; } else { strNotCapableReason = "Could not find suitable coins!"; LogPrintf("CActiveMasternode::ManageState -- %s\n", strNotCapableReason); return; } } //send to all peers if(!SendMasternodePing(strError)) { LogPrintf("CActiveMasternode::ManageState -- Error on SendMasternodePing(): %s\n", strError); } } std::string CActiveMasternode::GetStatus() { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; default: return "unknown"; } } bool CActiveMasternode::SendMasternodePing(std::string& strErrorRet) { if(nState != ACTIVE_MASTERNODE_STARTED) { strErrorRet = "Masternode is not in a running status"; return false; } CMasternodePing mnp(vin); if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { strErrorRet = "Couldn't sign Masternode Ping"; return false; } // Update lastPing for our masternode in Masternode list CMasternode* pmn = mnodeman.Find(vin); if(pmn != NULL) { if(pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { strErrorRet = "Too early to send Masternode Ping"; return false; } pmn->lastPing = mnp; mnodeman.mapSeenMasternodePing.insert(std::make_pair(mnp.GetHash(), mnp)); //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if(mnodeman.mapSeenMasternodeBroadcast.count(hash)) mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = mnp; LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", vin.ToString()); mnp.Relay(); return true; } else { // Seems like we are trying to send a ping while the Masternode is not registered in the network strErrorRet = "PrivateSend Masternode List doesn't include our Masternode, shutting down Masternode pinging service! " + vin.ToString(); nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strErrorRet; return false; } } // when starting a Masternode, this can enable to run as a hot wallet with no funds bool CActiveMasternode::EnableRemoteMasterNode(CTxIn& vinNew, CService& serviceNew) { if(!fMasterNode) return false; nState = ACTIVE_MASTERNODE_STARTED; //The values below are needed for signing mnping messages going forward vin = vinNew; service = serviceNew; LogPrintf("CActiveMasternode::EnableHotColdMasterNode -- Enabled! You may shut down the cold daemon.\n"); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2017-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "masternode.h" #include "masternode-sync.h" #include "masternodeman.h" #include "netbase.h" #include "protocol.h" // Keep track of the active Masternode CActiveMasternode activeMasternode; void CActiveMasternode::ManageState(CConnman& connman) { LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- Start\n"); if(!fMasternodeMode) { LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- Not a masternode, returning\n"); return; } if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus()); return; } if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) { nState = ACTIVE_MASTERNODE_INITIAL; } LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(eType == MASTERNODE_UNKNOWN) { ManageStateInitial(connman); } if(eType == MASTERNODE_REMOTE) { ManageStateRemote(); } SendMasternodePing(connman); } std::string CActiveMasternode::GetStateString() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "INITIAL"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW"; case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE"; case ACTIVE_MASTERNODE_STARTED: return "STARTED"; default: return "UNKNOWN"; } } std::string CActiveMasternode::GetStatus() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; default: return "Unknown"; } } std::string CActiveMasternode::GetTypeString() const { std::string strType; switch(eType) { case MASTERNODE_REMOTE: strType = "REMOTE"; break; default: strType = "UNKNOWN"; break; } return strType; } bool CActiveMasternode::SendMasternodePing(CConnman& connman) { if(!fPingerEnabled) { LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); return false; } if(!mnodeman.Has(outpoint)) { strNotCapableReason = "Masternode not in masternode list"; nState = ACTIVE_MASTERNODE_NOT_CAPABLE; LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); return false; } CMasternodePing mnp(outpoint); const CMasternode* pmn = mnodeman.Find(outpoint); mnp.nSentinelVersion = nSentinelVersion; mnp.fSentinelIsCurrent = (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_SENTINEL_PING_MAX_SECONDS); if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); return false; } // Update lastPing for our masternode in Masternode list if(mnodeman.IsMasternodePingedWithin(pmn, outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n"); return false; } mnodeman.SetMasternodeLastPing(outpoint, mnp); LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", outpoint.ToStringShort()); mnp.Relay(connman); return true; } bool CActiveMasternode::UpdateSentinelPing(int version) { nSentinelVersion = version; nSentinelPingTime = GetAdjustedTime(); return true; } void CActiveMasternode::ManageStateInitial(CConnman& connman) { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); // Check that our local network configuration is correct if (!fListen) { // listen option is probably overwritten by smth else, no good nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // First try to find whatever local address is specified by externalip option bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service); if(!fFoundLocal) { bool empty = true; // If we have some peers, let's try to find our local address from one of them connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) { empty = false; if (pnode->addr.IsIPv4()) fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service); return !fFoundLocal; }); // nothing and no live connections, can't do anything for now if (empty) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } if(!fFoundLocal) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int mainnetDefaultPort = chainParams->GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(service.GetPort() != mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } else if(service.GetPort() == mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // Check socket connectivity LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString()); SOCKET hSocket = INVALID_SOCKET; hSocket = CreateSocket(service); if (hSocket == INVALID_SOCKET) { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- Could not create socket '%s'\n", service.ToString()); return; } bool fConnected = ConnectSocketDirectly(service, hSocket, nConnectTimeout, true) && IsSelectableSocket(hSocket); CloseSocket(hSocket); if (!fConnected) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Could not connect to " + service.ToString(); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // Default to REMOTE eType = MASTERNODE_REMOTE; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); } void CActiveMasternode::ManageStateRemote() { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n", GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString()); mnodeman.CheckMasternode(pubKeyMasternode, true); masternode_info_t infoMn; if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) { if(infoMn.nProtocolVersion != MIN_PEER_PROTO_VERSION) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Invalid protocol version"; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(service != infoMn.addr) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState)); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(nState != ACTIVE_MASTERNODE_STARTED) { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- STARTED!\n"); outpoint = infoMn.outpoint; service = infoMn.addr; fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; } } else { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode not in masternode list"; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); } } <commit_msg>dont send ping unless in winners list with 6 sigs<commit_after>// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2017-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "masternode.h" #include "masternode-sync.h" #include "masternodeman.h" #include "masternode-payments.h" #include "netbase.h" #include "protocol.h" #include "script/standard.h" // Keep track of the active Masternode CActiveMasternode activeMasternode; void CActiveMasternode::ManageState(CConnman& connman) { LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- Start\n"); if(!fMasternodeMode) { LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- Not a masternode, returning\n"); return; } if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus()); return; } if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) { nState = ACTIVE_MASTERNODE_INITIAL; } LogPrint(BCLog::MN, "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); if(eType == MASTERNODE_UNKNOWN) { ManageStateInitial(connman); } if(eType == MASTERNODE_REMOTE) { ManageStateRemote(); } SendMasternodePing(connman); } std::string CActiveMasternode::GetStateString() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "INITIAL"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW"; case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE"; case ACTIVE_MASTERNODE_STARTED: return "STARTED"; default: return "UNKNOWN"; } } std::string CActiveMasternode::GetStatus() const { switch (nState) { case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; default: return "Unknown"; } } std::string CActiveMasternode::GetTypeString() const { std::string strType; switch(eType) { case MASTERNODE_REMOTE: strType = "REMOTE"; break; default: strType = "UNKNOWN"; break; } return strType; } bool CActiveMasternode::SendMasternodePing(CConnman& connman) { if(!fPingerEnabled) { LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); return false; } if(!mnodeman.Has(outpoint)) { strNotCapableReason = "Masternode not in masternode list"; nState = ACTIVE_MASTERNODE_NOT_CAPABLE; LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); return false; } CMasternodePing mnp(outpoint); const CMasternode* pmn = mnodeman.Find(outpoint); mnp.nSentinelVersion = nSentinelVersion; mnp.fSentinelIsCurrent = (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_SENTINEL_PING_MAX_SECONDS); if(!mnp.Sign(keyMasternode, pubKeyMasternode)) { LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); return false; } // Update lastPing for our masternode in Masternode list if(mnodeman.IsMasternodePingedWithin(pmn, outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n"); return false; } // ensure that we should only create ping if in the winners list const CScript &mnpayee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID()); bool foundPayee = false; { LOCK(cs_mapMasternodeBlocks); CMasternodePayee payee; // only allow ping if MNPAYMENTS_SIGNATURES_REQUIRED votes are on this masternode in last 10 blocks of winners list and 20 blocks into future (match default of masternode winners) for (int i = -10; i < 20; i++) { if(mnpayments.mapMasternodeBlocks.count(chainActive.Height()+i) && mnpayments.mapMasternodeBlocks[chainActive.Height()+i].HasPayeeWithVotes(mnpayee, MNPAYMENTS_SIGNATURES_REQUIRED, payee)) { foundPayee = true; break; } } } if(!foundPayee){ LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- Not in winners list, skipping ping...\n"); return false; } mnodeman.SetMasternodeLastPing(outpoint, mnp); LogPrint(BCLog::MN, "CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", outpoint.ToStringShort()); mnp.Relay(connman); return true; } bool CActiveMasternode::UpdateSentinelPing(int version) { nSentinelVersion = version; nSentinelPingTime = GetAdjustedTime(); return true; } void CActiveMasternode::ManageStateInitial(CConnman& connman) { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); // Check that our local network configuration is correct if (!fListen) { // listen option is probably overwritten by smth else, no good nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // First try to find whatever local address is specified by externalip option bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service); if(!fFoundLocal) { bool empty = true; // If we have some peers, let's try to find our local address from one of them connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty, this](CNode* pnode) { empty = false; if (pnode->addr.IsIPv4()) fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service); return !fFoundLocal; }); // nothing and no live connections, can't do anything for now if (empty) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } if(!fFoundLocal) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int mainnetDefaultPort = chainParams->GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(service.GetPort() != mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } } else if(service.GetPort() == mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // Check socket connectivity LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString()); SOCKET hSocket = INVALID_SOCKET; hSocket = CreateSocket(service); if (hSocket == INVALID_SOCKET) { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- Could not create socket '%s'\n", service.ToString()); return; } bool fConnected = ConnectSocketDirectly(service, hSocket, nConnectTimeout, true) && IsSelectableSocket(hSocket); CloseSocket(hSocket); if (!fConnected) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Could not connect to " + service.ToString(); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } // Default to REMOTE eType = MASTERNODE_REMOTE; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); } void CActiveMasternode::ManageStateRemote() { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n", GetStatus(), GetTypeString(), fPingerEnabled, pubKeyMasternode.GetID().ToString()); mnodeman.CheckMasternode(pubKeyMasternode, true); masternode_info_t infoMn; if(mnodeman.GetMasternodeInfo(pubKeyMasternode, infoMn)) { if(infoMn.nProtocolVersion != MIN_PEER_PROTO_VERSION) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Invalid protocol version"; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(service != infoMn.addr) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently."; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState)); LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } if(nState != ACTIVE_MASTERNODE_STARTED) { LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- STARTED!\n"); outpoint = infoMn.outpoint; service = infoMn.addr; fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; } } else { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode not in masternode list"; LogPrint(BCLog::MN, "CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); } } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE test_mat3 #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include "mat3.h" #include "vec3.h" #include <cstdio> void print_matrix3(const kmMat3* mat) { const int max = 3; printf("\n\n"); for(int i = 0; i < max; i++) { printf("|"); for(int j = 0; j < max; j++) { if(j > 0) { printf("\t"); } printf("%f",mat->mat[i + max*j]); } printf("|\n"); } printf("\n"); } BOOST_AUTO_TEST_CASE(test_mat3_inverse) { kmMat3 mat; BOOST_CHECK(NULL != kmMat3Identity(&mat)); kmMat3 adj; BOOST_CHECK(NULL != kmMat3Adjugate(&adj, &mat)); BOOST_CHECK(NULL != kmMat3Inverse(&mat, kmMat3Determinant(&mat), &mat)); BOOST_CHECK(kmMat3IsIdentity(&mat)); } BOOST_AUTO_TEST_CASE(test_mat3_transpose) { kmMat3 mat; float temp[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f }; memcpy(mat.mat, temp, sizeof(float) * 9); kmMat3 transpose; float temp2[] = {0.0f, 3.0f, 6.0f, 1.0f, 4.0f, 7.0f, 2.0f, 5.0f, 8.0f }; memcpy(transpose.mat, temp2, sizeof(float) * 9); kmMat3 result; BOOST_CHECK(NULL != kmMat3Transpose(&result, &mat)); BOOST_CHECK(kmMat3AreEqual(&transpose, &result)); // print_matrix3(&transpose); // print_matrix3(&result); } BOOST_AUTO_TEST_CASE(test_mat3_fill) { float temp[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f }; kmMat3 orig, filled; orig.mat[0] = 0.0f; orig.mat[1] = 1.0f; orig.mat[2] = 2.0f; orig.mat[3] = 3.0f; orig.mat[4] = 4.0f; orig.mat[5] = 5.0f; orig.mat[6] = 6.0f; orig.mat[7] = 7.0f; orig.mat[8] = 8.0f; kmMat3Fill(&filled, temp); BOOST_CHECK(kmMat3AreEqual(&filled, &orig)); } BOOST_AUTO_TEST_CASE(test_mat3_are_equal) { kmMat3 test, different; kmMat3Identity(&test); kmMat3Identity(&different); BOOST_CHECK(kmMat3AreEqual(&test, &test)); BOOST_CHECK(kmMat3AreEqual(&test, &different)); different.mat[3] = 3.0f; //Arbitrary to make it different BOOST_CHECK(!kmMat3AreEqual(&test, &different)); } BOOST_AUTO_TEST_CASE(test_mat3_axis_angle) { float radians = 1.0; kmMat3 a; kmVec3 axisIn; kmVec3Fill(&axisIn, 1.0f, 0.0f, 0.0f); kmMat3RotationAxisAngle(&a, &axisIn, radians); //TODO: Finish this } BOOST_AUTO_TEST_CASE(test_mat3_identity) { float identity[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; kmMat3 expected, actual; kmMat3Fill(&expected, identity); kmMat3Identity(&actual); BOOST_CHECK(kmMat3AreEqual(&expected, &actual)); } BOOST_AUTO_TEST_CASE(test_mat3_is_identity) { kmMat3 identity; kmMat3Identity(&identity); BOOST_CHECK(kmMat3IsIdentity(&identity)); identity.mat[0] = 5.0f; //Arbitrary number BOOST_CHECK(!kmMat3IsIdentity(&identity)); } BOOST_AUTO_TEST_CASE(test_mat3_scaling) { kmMat3 expected, actual; kmMat3Identity(&expected); expected.mat[0] = 1.0f; expected.mat[4] = 2.0f; kmMat3Scaling(&actual, 1.0f, 2.0f); BOOST_CHECK(kmMat3AreEqual(&expected, &actual)); } <commit_msg>Added a test for kmMat3Translation<commit_after>#define BOOST_TEST_MODULE test_mat3 #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include "mat3.h" #include "vec3.h" #include <cstdio> void print_matrix3(const kmMat3* mat) { const int max = 3; printf("\n\n"); for(int i = 0; i < max; i++) { printf("|"); for(int j = 0; j < max; j++) { if(j > 0) { printf("\t"); } printf("%f",mat->mat[i + max*j]); } printf("|\n"); } printf("\n"); } BOOST_AUTO_TEST_CASE(test_mat3_inverse) { kmMat3 mat; BOOST_CHECK(NULL != kmMat3Identity(&mat)); kmMat3 adj; BOOST_CHECK(NULL != kmMat3Adjugate(&adj, &mat)); BOOST_CHECK(NULL != kmMat3Inverse(&mat, kmMat3Determinant(&mat), &mat)); BOOST_CHECK(kmMat3IsIdentity(&mat)); } BOOST_AUTO_TEST_CASE(test_mat3_transpose) { kmMat3 mat; float temp[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f }; memcpy(mat.mat, temp, sizeof(float) * 9); kmMat3 transpose; float temp2[] = {0.0f, 3.0f, 6.0f, 1.0f, 4.0f, 7.0f, 2.0f, 5.0f, 8.0f }; memcpy(transpose.mat, temp2, sizeof(float) * 9); kmMat3 result; BOOST_CHECK(NULL != kmMat3Transpose(&result, &mat)); BOOST_CHECK(kmMat3AreEqual(&transpose, &result)); // print_matrix3(&transpose); // print_matrix3(&result); } BOOST_AUTO_TEST_CASE(test_mat3_fill) { float temp[] = { 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f }; kmMat3 orig, filled; orig.mat[0] = 0.0f; orig.mat[1] = 1.0f; orig.mat[2] = 2.0f; orig.mat[3] = 3.0f; orig.mat[4] = 4.0f; orig.mat[5] = 5.0f; orig.mat[6] = 6.0f; orig.mat[7] = 7.0f; orig.mat[8] = 8.0f; kmMat3Fill(&filled, temp); BOOST_CHECK(kmMat3AreEqual(&filled, &orig)); } BOOST_AUTO_TEST_CASE(test_mat3_are_equal) { kmMat3 test, different; kmMat3Identity(&test); kmMat3Identity(&different); BOOST_CHECK(kmMat3AreEqual(&test, &test)); BOOST_CHECK(kmMat3AreEqual(&test, &different)); different.mat[3] = 3.0f; //Arbitrary to make it different BOOST_CHECK(!kmMat3AreEqual(&test, &different)); } BOOST_AUTO_TEST_CASE(test_mat3_axis_angle) { float radians = 1.0; kmMat3 a; kmVec3 axisIn; kmVec3Fill(&axisIn, 1.0f, 0.0f, 0.0f); kmMat3RotationAxisAngle(&a, &axisIn, radians); //TODO: Finish this } BOOST_AUTO_TEST_CASE(test_mat3_identity) { float identity[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; kmMat3 expected, actual; kmMat3Fill(&expected, identity); kmMat3Identity(&actual); BOOST_CHECK(kmMat3AreEqual(&expected, &actual)); } BOOST_AUTO_TEST_CASE(test_mat3_is_identity) { kmMat3 identity; kmMat3Identity(&identity); BOOST_CHECK(kmMat3IsIdentity(&identity)); identity.mat[0] = 5.0f; //Arbitrary number BOOST_CHECK(!kmMat3IsIdentity(&identity)); } BOOST_AUTO_TEST_CASE(test_mat3_scaling) { kmMat3 expected, actual; kmMat3Identity(&expected); expected.mat[0] = 1.0f; expected.mat[4] = 2.0f; kmMat3Scaling(&actual, 1.0f, 2.0f); BOOST_CHECK(kmMat3AreEqual(&expected, &actual)); } BOOST_AUTO_TEST_CASE(test_mat3_translation) { kmMat3 expected, actual; kmMat3Identity(&expected); expected.mat[6] = 1.0f; expected.mat[7] = 2.0f; kmMat3Translation(&actual, 1.0f, 2.0f); BOOST_CHECK(kmMat3AreEqual(&expected, &actual)); } <|endoftext|>
<commit_before>#include <fstream> #include <vector> #include <string> #include <iostream> #include <stdexcept> #include "glsupport.h" using namespace std; void checkGlErrors() { const GLenum errCode = glGetError(); if (errCode != GL_NO_ERROR) { string error("GL Error: "); error += reinterpret_cast<const char*>(gluErrorString(errCode)); cerr << error << endl; throw runtime_error(error); } } // Dump text file into a character vector, throws exception on error static void readTextFile(const char *fn, vector<char>& data) { // Sets ios::binary bit to prevent end of line translation, so that the // number of bytes we read equals file size ifstream ifs(fn, ios::binary); if (!ifs) throw runtime_error(string("Cannot open file ") + fn); // Sets bits to report IO error using exception ifs.exceptions(ios::eofbit | ios::failbit | ios::badbit); ifs.seekg(0, ios::end); size_t len = ifs.tellg(); data.resize(len); ifs.seekg(0, ios::beg); ifs.read(&data[0], len); } // Print info regarding an GL object static void printInfoLog(GLuint obj, const string& filename) { GLint infologLength = 0; GLint charsWritten = 0; glGetObjectParameterivARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &infologLength); if (infologLength > 0) { string infoLog(infologLength, ' '); glGetInfoLogARB(obj, infologLength, &charsWritten, &infoLog[0]); std::cerr << "##### Log [" << filename << "]:\n" << infoLog << endl; } } static void compileShader(GLuint shaderHandle, int sourceLength, const char *source, const char *filenameHint) { const char *ptrs[] = {source}; const GLint lens[] = {sourceLength}; glShaderSource(shaderHandle, 1, ptrs, lens); // load the shader sources glCompileShader(shaderHandle); printInfoLog(shaderHandle, filenameHint); GLint compiled = 0; glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &compiled); if (!compiled) throw runtime_error("fails to compile GL shader"); } void readAndCompileSingleShaderFromMemory(GLuint shaderHandle, int sourceLength, const char *source) { compileShader(shaderHandle, sourceLength, source, "<in-memory source>"); } void readAndCompileSingleShader(GLuint shaderHandle, const char *fn) { vector<char> source; readTextFile(fn, source); compileShader(shaderHandle, source.size(), &source[0], fn); } void linkShader(GLuint programHandle, GLuint vs, GLuint fs) { glAttachShader(programHandle, vs); glAttachShader(programHandle, fs); glLinkProgram(programHandle); glDetachShader(programHandle, vs); glDetachShader(programHandle, fs); GLint linked = 0; glGetProgramiv(programHandle, GL_LINK_STATUS, &linked); printInfoLog(programHandle, "linking"); if (!linked) throw runtime_error("fails to link shaders"); } void readAndCompileShader(GLuint programHandle, const char * vertexShaderFileName, const char * fragmentShaderFileName) { GlShader vs(GL_VERTEX_SHADER); GlShader fs(GL_FRAGMENT_SHADER); readAndCompileSingleShader(vs, vertexShaderFileName); readAndCompileSingleShader(fs, fragmentShaderFileName); linkShader(programHandle, vs, fs); } void readAndCompileShaderFromMemory(GLuint programHandle, int vsSourceLength, const char *vsSource, int fsSourceLength, const char *fsSource) { GlShader vs(GL_VERTEX_SHADER); GlShader fs(GL_FRAGMENT_SHADER); readAndCompileSingleShaderFromMemory(vs, vsSourceLength, vsSource); readAndCompileSingleShaderFromMemory(fs, fsSourceLength, fsSource); linkShader(programHandle, vs, fs); } <commit_msg>update glsupport os x fix<commit_after>#include <fstream> #include <vector> #include <string> #include <iostream> #include <stdexcept> #include "glsupport.h" using namespace std; void checkGlErrors() { const GLenum errCode = glGetError(); if (errCode != GL_NO_ERROR) { string error("GL Error: "); error += reinterpret_cast<const char*>(gluErrorString(errCode)); cerr << error << endl; throw runtime_error(error); } } // Dump text file into a character vector, throws exception on error static void readTextFile(const char *fn, vector<char>& data) { // Sets ios::binary bit to prevent end of line translation, so that the // number of bytes we read equals file size ifstream ifs(fn, ios::binary); if (!ifs) throw runtime_error(string("Cannot open file ") + fn); // Sets bits to report IO error using exception ifs.exceptions(ios::eofbit | ios::failbit | ios::badbit); ifs.seekg(0, ios::end); size_t len = ifs.tellg(); data.resize(len); ifs.seekg(0, ios::beg); ifs.read(&data[0], len); } // GL 3 core needs separate functions for shader and program info logs // Print info regarding a GL program static void printProgramInfoLog(GLuint obj, const string& filename) { GLsizei infoLogLength, charsWritten; glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { string infoLog(infoLogLength, ' '); glGetProgramInfoLog(obj, infoLogLength, &charsWritten, &infoLog[0]); std::cerr << "##### Log [" << filename << "]:\n" << infoLog << endl; } } // Print info regarding a GL shader static void printShaderInfoLog(GLuint obj, const string& filename) { GLsizei infoLogLength, charsWritten; glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { string infoLog(infoLogLength, ' '); glGetShaderInfoLog(obj, infoLogLength, &charsWritten, &infoLog[0]); std::cerr << "##### Log [" << filename << "]:\n" << infoLog << endl; } } static void compileShader(GLuint shaderHandle, int sourceLength, const char *source, const char *filenameHint) { const char *ptrs[] = { source }; const GLint lens[] = { sourceLength }; glShaderSource(shaderHandle, 1, ptrs, lens); // load the shader sources glCompileShader(shaderHandle); printShaderInfoLog(shaderHandle, filenameHint); GLint compiled = 0; glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &compiled); if (!compiled) throw runtime_error("fails to compile GL shader"); } void readAndCompileSingleShaderFromMemory(GLuint shaderHandle, int sourceLength, const char *source) { compileShader(shaderHandle, sourceLength, source, "<in-memory source>"); } void readAndCompileSingleShader(GLuint shaderHandle, const char *fn) { vector<char> source; readTextFile(fn, source); compileShader(shaderHandle, source.size(), &source[0], fn); } void linkShader(GLuint programHandle, GLuint vs, GLuint fs) { glAttachShader(programHandle, vs); glAttachShader(programHandle, fs); glLinkProgram(programHandle); glDetachShader(programHandle, vs); glDetachShader(programHandle, fs); GLint linked = 0; glGetProgramiv(programHandle, GL_LINK_STATUS, &linked); printProgramInfoLog(programHandle, "linking"); if (!linked) throw runtime_error("fails to link shaders"); } void readAndCompileShader(GLuint programHandle, const char * vertexShaderFileName, const char * fragmentShaderFileName) { GlShader vs(GL_VERTEX_SHADER); GlShader fs(GL_FRAGMENT_SHADER); readAndCompileSingleShader(vs, vertexShaderFileName); readAndCompileSingleShader(fs, fragmentShaderFileName); linkShader(programHandle, vs, fs); } void readAndCompileShaderFromMemory(GLuint programHandle, int vsSourceLength, const char *vsSource, int fsSourceLength, const char *fsSource) { GlShader vs(GL_VERTEX_SHADER); GlShader fs(GL_FRAGMENT_SHADER); readAndCompileSingleShaderFromMemory(vs, vsSourceLength, vsSource); readAndCompileSingleShaderFromMemory(fs, fsSourceLength, fsSource); linkShader(programHandle, vs, fs); } <|endoftext|>
<commit_before>/* * Copyright 2015 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "EM_object.h" #include "mem_worker_thread.h" namespace fm { namespace detail { EM_object::file_holder::ptr EM_object::file_holder::create_temp( const std::string &name, size_t num_bytes) { char *tmp = tempnam(".", name.c_str()); std::string tmp_name = basename(tmp); safs::safs_file f(safs::get_sys_RAID_conf(), tmp_name); assert(!f.exist()); bool ret = f.create_file(num_bytes); assert(ret); file_holder::ptr holder(new file_holder(tmp_name, false)); free(tmp); return holder; } EM_object::file_holder::~file_holder() { if (!persistent) { safs::safs_file f(safs::get_sys_RAID_conf(), file_name); assert(f.exist()); f.delete_file(); } } bool EM_object::file_holder::set_persistent(const std::string &new_name) { safs::safs_file f(safs::get_sys_RAID_conf(), file_name); if (!f.rename(new_name)) return false; persistent = true; this->file_name = new_name; return true; } safs::io_interface::ptr EM_object::io_set::create_io() { thread *t = thread::get_curr_thread(); assert(t); pthread_spin_lock(&io_lock); auto it = thread_ios.find(t); if (it == thread_ios.end()) { safs::io_interface::ptr io = safs::create_io(factory, t); io->set_callback(portion_callback::ptr(new portion_callback())); thread_ios.insert(std::pair<thread *, safs::io_interface::ptr>(t, io)); pthread_setspecific(io_key, io.get()); pthread_spin_unlock(&io_lock); return io; } else { safs::io_interface::ptr io = it->second; pthread_spin_unlock(&io_lock); return io; } } EM_object::io_set::io_set(safs::file_io_factory::shared_ptr factory) { this->factory = factory; int ret = pthread_key_create(&io_key, NULL); assert(ret == 0); pthread_spin_init(&io_lock, PTHREAD_PROCESS_PRIVATE); } EM_object::io_set::~io_set() { pthread_spin_destroy(&io_lock); pthread_key_delete(io_key); thread_ios.clear(); } bool EM_object::io_set::has_io() const { return pthread_getspecific(io_key) != NULL; } safs::io_interface &EM_object::io_set::get_curr_io() const { void *io_addr = pthread_getspecific(io_key); if (io_addr) return *(safs::io_interface *) io_addr; else { safs::io_interface::ptr io = const_cast<io_set *>(this)->create_io(); return *io; } } void portion_callback::add(long key, portion_compute::ptr compute) { auto it = computes.find(key); if (it == computes.end()) { std::vector<portion_compute::ptr> tmp(1); tmp[0] = compute; auto ret = computes.insert( std::pair<long, std::vector<portion_compute::ptr> >(key, tmp)); assert(ret.second); } else it->second.push_back(compute); } int portion_callback::invoke(safs::io_request *reqs[], int num) { for (int i = 0; i < num; i++) { auto it = computes.find(get_portion_key(*reqs[i])); // Sometimes we want to use the I/O instance synchronously, and // we don't need to keep a compute here. if (it == computes.end()) continue; std::vector<portion_compute::ptr> tmp = it->second; // We have to remove the vector of computes from the hashtable first. // Otherwise, the user-defined `run' function may try to add new // computes to the vector. computes.erase(it); for (auto comp_it = tmp.begin(); comp_it != tmp.end(); comp_it++) { portion_compute::ptr compute = *comp_it; compute->run(reqs[i]->get_buf(), reqs[i]->get_size()); } } return 0; } } } <commit_msg>[Matrix]: avoid using tempnam.<commit_after>/* * Copyright 2015 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "EM_object.h" #include "mem_worker_thread.h" namespace fm { namespace detail { EM_object::file_holder::ptr EM_object::file_holder::create_temp( const std::string &name, size_t num_bytes) { const size_t MAX_TRIES = 10; size_t i; std::string tmp_name; for (i = 0; i < MAX_TRIES; i++) { tmp_name = name + gen_rand_name(8); safs::safs_file f(safs::get_sys_RAID_conf(), tmp_name); if (!f.exist()) break; } if (i == MAX_TRIES) { BOOST_LOG_TRIVIAL(error) << "Can't create a temp matrix name because max tries are reached"; return EM_object::file_holder::ptr(); } safs::safs_file f(safs::get_sys_RAID_conf(), tmp_name); bool ret = f.create_file(num_bytes); assert(ret); file_holder::ptr holder(new file_holder(tmp_name, false)); return holder; } EM_object::file_holder::~file_holder() { if (!persistent) { safs::safs_file f(safs::get_sys_RAID_conf(), file_name); assert(f.exist()); f.delete_file(); } } bool EM_object::file_holder::set_persistent(const std::string &new_name) { safs::safs_file f(safs::get_sys_RAID_conf(), file_name); if (!f.rename(new_name)) return false; persistent = true; this->file_name = new_name; return true; } safs::io_interface::ptr EM_object::io_set::create_io() { thread *t = thread::get_curr_thread(); assert(t); pthread_spin_lock(&io_lock); auto it = thread_ios.find(t); if (it == thread_ios.end()) { safs::io_interface::ptr io = safs::create_io(factory, t); io->set_callback(portion_callback::ptr(new portion_callback())); thread_ios.insert(std::pair<thread *, safs::io_interface::ptr>(t, io)); pthread_setspecific(io_key, io.get()); pthread_spin_unlock(&io_lock); return io; } else { safs::io_interface::ptr io = it->second; pthread_spin_unlock(&io_lock); return io; } } EM_object::io_set::io_set(safs::file_io_factory::shared_ptr factory) { this->factory = factory; int ret = pthread_key_create(&io_key, NULL); assert(ret == 0); pthread_spin_init(&io_lock, PTHREAD_PROCESS_PRIVATE); } EM_object::io_set::~io_set() { pthread_spin_destroy(&io_lock); pthread_key_delete(io_key); thread_ios.clear(); } bool EM_object::io_set::has_io() const { return pthread_getspecific(io_key) != NULL; } safs::io_interface &EM_object::io_set::get_curr_io() const { void *io_addr = pthread_getspecific(io_key); if (io_addr) return *(safs::io_interface *) io_addr; else { safs::io_interface::ptr io = const_cast<io_set *>(this)->create_io(); return *io; } } void portion_callback::add(long key, portion_compute::ptr compute) { auto it = computes.find(key); if (it == computes.end()) { std::vector<portion_compute::ptr> tmp(1); tmp[0] = compute; auto ret = computes.insert( std::pair<long, std::vector<portion_compute::ptr> >(key, tmp)); assert(ret.second); } else it->second.push_back(compute); } int portion_callback::invoke(safs::io_request *reqs[], int num) { for (int i = 0; i < num; i++) { auto it = computes.find(get_portion_key(*reqs[i])); // Sometimes we want to use the I/O instance synchronously, and // we don't need to keep a compute here. if (it == computes.end()) continue; std::vector<portion_compute::ptr> tmp = it->second; // We have to remove the vector of computes from the hashtable first. // Otherwise, the user-defined `run' function may try to add new // computes to the vector. computes.erase(it); for (auto comp_it = tmp.begin(); comp_it != tmp.end(); comp_it++) { portion_compute::ptr compute = *comp_it; compute->run(reqs[i]->get_buf(), reqs[i]->get_size()); } } return 0; } } } <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include <string> #include <utils.hpp> #ifndef TRANSPOSE_HPP #define TRANSPOSE_HPP namespace isa { namespace OpenCL { class transposeConf { public: transposeConf(); ~transposeConf(); // Get unsigned int getNrItemsPerBlock() const; // Set void setNrItemsPerBlock(unsigned int items); // utils std::string print() const; private: unsigned int nrItemsPerBlock; } // Sequential transpose template< typename T > void transpose(const unsigned int M, const unsigned int N, const unsigned int padding, std::vector< T > & input, std::vector< T > & output); // OpenCL transpose std::string * getTransposeOpenCL(const transposeConf & conf, const unsigned int M, const unsigned int N, const unsigned int padding, const unsigned int vector, std::string typeName); // Implementations inline unsigned int transposeConf::getNrItemsPerBlock() const { return nrItemsPerBlock; } inline void transposeConf::setNrItemsPerBlock(unsigned int items) { nrItemsPerBlock = items; } template< typename T > void transpose(const unsigned int M, const unsigned int N, const unsigned int padding, std::vector< T > & input, std::vector< T > & output) { for ( unsigned int i = 0; i < M; i++ ) { for ( unsigned int j = 0; j < N; j++ ) { output[(j * isa::utils::pad(M, padding)) + i] = input[(i * isa::utils::pad(N, padding)) + j]; } } } } // OpenCl } // isa #endif // TRANSPOSE_HPP <commit_msg>Typo.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include <string> #include <utils.hpp> #ifndef TRANSPOSE_HPP #define TRANSPOSE_HPP namespace isa { namespace OpenCL { class transposeConf { public: transposeConf(); ~transposeConf(); // Get unsigned int getNrItemsPerBlock() const; // Set void setNrItemsPerBlock(unsigned int items); // utils std::string print() const; private: unsigned int nrItemsPerBlock; }; // Sequential transpose template< typename T > void transpose(const unsigned int M, const unsigned int N, const unsigned int padding, std::vector< T > & input, std::vector< T > & output); // OpenCL transpose std::string * getTransposeOpenCL(const transposeConf & conf, const unsigned int M, const unsigned int N, const unsigned int padding, const unsigned int vector, std::string typeName); // Implementations inline unsigned int transposeConf::getNrItemsPerBlock() const { return nrItemsPerBlock; } inline void transposeConf::setNrItemsPerBlock(unsigned int items) { nrItemsPerBlock = items; } template< typename T > void transpose(const unsigned int M, const unsigned int N, const unsigned int padding, std::vector< T > & input, std::vector< T > & output) { for ( unsigned int i = 0; i < M; i++ ) { for ( unsigned int j = 0; j < N; j++ ) { output[(j * isa::utils::pad(M, padding)) + i] = input[(i * isa::utils::pad(N, padding)) + j]; } } } } // OpenCl } // isa #endif // TRANSPOSE_HPP <|endoftext|>
<commit_before>#pragma once #include <string> #include <cstddef> #include <cstring> #include <any.hpp> #include <reflection_info.hpp> namespace shadow { template <class InfoType, template <class> class... Policies> class info_type_aggregate : public Policies<info_type_aggregate<InfoType, Policies...>>... { template <class Derived> friend class name_policy; template <class Derived> friend class size_policy; template <class Derived> friend class comparison_policy; friend class reflection_manager; public: info_type_aggregate() = default; info_type_aggregate(const InfoType& info) : info_ptr_(&info) { } info_type_aggregate* operator->() { return this; } const info_type_aggregate* operator->() const { return this; } private: const InfoType* info_ptr_; }; template <class Derived> class name_policy { public: std::string name() const { return std::string(static_cast<const Derived*>(this)->info_ptr_->name); } }; template <class Derived> class size_policy { public: std::size_t size() const { return static_cast<const Derived*>(this)->info_ptr_->size; } }; template <class Derived> class comparison_policy { public: bool operator==(const Derived& other) const { if(std::strcmp(static_cast<const Derived*>(this)->info_ptr_->name, other.info_ptr_->name) == 0) { return true; } return false; } bool operator!=(const Derived& other) const { return !operator==(other); } }; typedef info_type_aggregate<type_info, name_policy, size_policy, comparison_policy> type_tag; typedef info_type_aggregate<constructor_info> constructor_tag; class reflection_manager; class object { friend class reflection_manager; private: // used by reflection_manager object(any value, const type_info* ti, const reflection_manager* man); public: object(); type_tag type() const; private: any value_; const type_info* type_info_; const reflection_manager* manager_; }; } namespace shadow { inline object::object(any value, const type_info* ti, const reflection_manager* man) : value_(std::move(value)), type_info_(ti), manager_(man) { } inline type_tag object::type() const { return type_tag(*type_info_); } } <commit_msg>Make constructor of object public. modified: include/api_types.hpp<commit_after>#pragma once #include <string> #include <cstddef> #include <cstring> #include <any.hpp> #include <reflection_info.hpp> namespace shadow { template <class InfoType, template <class> class... Policies> class info_type_aggregate : public Policies<info_type_aggregate<InfoType, Policies...>>... { template <class Derived> friend class name_policy; template <class Derived> friend class size_policy; template <class Derived> friend class comparison_policy; friend class reflection_manager; public: info_type_aggregate() = default; info_type_aggregate(const InfoType& info) : info_ptr_(&info) { } info_type_aggregate* operator->() { return this; } const info_type_aggregate* operator->() const { return this; } private: const InfoType* info_ptr_; }; template <class Derived> class name_policy { public: std::string name() const { return std::string(static_cast<const Derived*>(this)->info_ptr_->name); } }; template <class Derived> class size_policy { public: std::size_t size() const { return static_cast<const Derived*>(this)->info_ptr_->size; } }; template <class Derived> class comparison_policy { public: bool operator==(const Derived& other) const { if(std::strcmp(static_cast<const Derived*>(this)->info_ptr_->name, other.info_ptr_->name) == 0) { return true; } return false; } bool operator!=(const Derived& other) const { return !operator==(other); } }; typedef info_type_aggregate<type_info, name_policy, size_policy, comparison_policy> type_tag; typedef info_type_aggregate<constructor_info> constructor_tag; class reflection_manager; class object { friend class reflection_manager; public: object(); object(any value, const type_info* ti, const reflection_manager* man); type_tag type() const; private: any value_; const type_info* type_info_; const reflection_manager* manager_; }; } namespace shadow { inline object::object(any value, const type_info* ti, const reflection_manager* man) : value_(std::move(value)), type_info_(ti), manager_(man) { } inline type_tag object::type() const { return type_tag(*type_info_); } } <|endoftext|>
<commit_before>/** * @file interface.hpp * @brief interface headers * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 8. 7 * @details COSSB interface headers */ #ifndef _COSSB_INTERFACE_HPP_ #define _COSSB_INTERFACE_HPP_ #if defined(__unix__) || defined(__gnu_linux__) || defined(linux) || defined(__linux__) #include "interface/icomponent.hpp" #include "interface/iauth.hpp" #include "interface/imessage.hpp" #include "interface/iprofile.hpp" #include "interface/isql.hpp" #include "interface/ilog.hpp" #include "interface/icomm.hpp" #endif #endif /* _COSSB_INTERFACE_HPP_ */ <commit_msg>add simple interface header<commit_after>/** * @file interface.hpp * @brief interface headers * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 8. 7 * @details COSSB interface headers */ #ifndef _COSSB_INTERFACE_HPP_ #define _COSSB_INTERFACE_HPP_ #if defined(__unix__) || defined(__gnu_linux__) || defined(linux) || defined(__linux__) #include "interface/icomponent.hpp" #include "interface/iauth.hpp" #include "interface/imessage.hpp" #include "interface/iprofile.hpp" #include "interface/isql.hpp" #include "interface/ilog.hpp" #include "interface/icomm.hpp" #include "interface/isimpleservice.hpp" #endif #endif /* _COSSB_INTERFACE_HPP_ */ <|endoftext|>
<commit_before>#ifndef OCCA_TOOLS_HEADER #define OCCA_TOOLS_HEADER #include <iostream> #include <stdlib.h> #include <sys/stat.h> #include <string.h> #include <errno.h> #if OCCA_OS == LINUX_OS # include <sys/time.h> #elif OCCA_OS == OSX_OS # include <CoreServices/CoreServices.h> # include <mach/mach_time.h> #else # include <windows.h> #endif namespace occa { class kernelInfo; inline double currentTime(){ #if OCCA_OS == LINUX_OS timespec ct; clock_gettime(CLOCK_MONOTONIC, &ct); return (double) (ct.tv_sec + (1.0e-9 * ct.tv_nsec)); #elif OCCA_OS == OSX_OS uint64_t ct; ct = mach_absolute_time(); const Nanoseconds ct2 = AbsoluteToNanoseconds(*(AbsoluteTime *) &ct); return ((double) 1.0e-9) * ((double) ( *((uint64_t*) &ct2) )); #elif OCCA_OS == WINDOWS_OS # warning "currentTime is not supported in Windows" #endif } inline void getFilePrefixAndName(const std::string &fullFilename, std::string &prefix, std::string &filename){ int lastSlash = 0; const int chars = fullFilename.size(); for(int i = 0; i < chars; ++i) if(fullFilename[i] == '/') lastSlash = i; ++lastSlash; prefix = fullFilename.substr(0, lastSlash); filename = fullFilename.substr(lastSlash, chars - lastSlash); } inline std::string getFileLock(const std::string &filename){ std::string prefix, name; getFilePrefixAndName(filename, prefix, name); return (prefix + "._occa_dir_" + name); } inline bool haveFile(const std::string &filename){ std::string lockDir = getFileLock(filename); int mkdirStatus = mkdir(lockDir.c_str(), 0755); // Someone else is making it if(mkdirStatus && (errno == EEXIST)) return false; return true; } inline void waitForFile(const std::string &filename){ struct stat buffer; std::string lockDir = getFileLock(filename); const char *c_lockDir = lockDir.c_str(); while(stat(c_lockDir, &buffer) == 0) /* Do Nothing */; } inline void releaseFile(const std::string &filename){ std::string lockDir = getFileLock(filename); rmdir(lockDir.c_str()); } std::string fnv(const std::string &filename); std::string readFile(const std::string &filename); std::string getCachedName(const std::string &filename, const std::string &salt); std::string createIntermediateSource(const std::string &filename, const std::string &cachedBinary, const kernelInfo &info); }; #endif <commit_msg>Include required header for rmdir<commit_after>#ifndef OCCA_TOOLS_HEADER #define OCCA_TOOLS_HEADER #include <iostream> #include <stdlib.h> #include <sys/stat.h> #include <string.h> #include <errno.h> #if OCCA_OS == LINUX_OS # include <sys/time.h> # include <unistd.h> #elif OCCA_OS == OSX_OS # include <CoreServices/CoreServices.h> # include <mach/mach_time.h> #else # include <windows.h> #endif namespace occa { class kernelInfo; inline double currentTime(){ #if OCCA_OS == LINUX_OS timespec ct; clock_gettime(CLOCK_MONOTONIC, &ct); return (double) (ct.tv_sec + (1.0e-9 * ct.tv_nsec)); #elif OCCA_OS == OSX_OS uint64_t ct; ct = mach_absolute_time(); const Nanoseconds ct2 = AbsoluteToNanoseconds(*(AbsoluteTime *) &ct); return ((double) 1.0e-9) * ((double) ( *((uint64_t*) &ct2) )); #elif OCCA_OS == WINDOWS_OS # warning "currentTime is not supported in Windows" #endif } inline void getFilePrefixAndName(const std::string &fullFilename, std::string &prefix, std::string &filename){ int lastSlash = 0; const int chars = fullFilename.size(); for(int i = 0; i < chars; ++i) if(fullFilename[i] == '/') lastSlash = i; ++lastSlash; prefix = fullFilename.substr(0, lastSlash); filename = fullFilename.substr(lastSlash, chars - lastSlash); } inline std::string getFileLock(const std::string &filename){ std::string prefix, name; getFilePrefixAndName(filename, prefix, name); return (prefix + "._occa_dir_" + name); } inline bool haveFile(const std::string &filename){ std::string lockDir = getFileLock(filename); int mkdirStatus = mkdir(lockDir.c_str(), 0755); // Someone else is making it if(mkdirStatus && (errno == EEXIST)) return false; return true; } inline void waitForFile(const std::string &filename){ struct stat buffer; std::string lockDir = getFileLock(filename); const char *c_lockDir = lockDir.c_str(); while(stat(c_lockDir, &buffer) == 0) /* Do Nothing */; } inline void releaseFile(const std::string &filename){ std::string lockDir = getFileLock(filename); rmdir(lockDir.c_str()); } std::string fnv(const std::string &filename); std::string readFile(const std::string &filename); std::string getCachedName(const std::string &filename, const std::string &salt); std::string createIntermediateSource(const std::string &filename, const std::string &cachedBinary, const kernelInfo &info); }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2009 Chris Pickel <sfiera@gmail.com> // // This file is part of libsfz, a free software project. You can redistribute // it and/or modify it under the terms of the MIT License. #ifndef SFZ_BYTES_HPP_ #define SFZ_BYTES_HPP_ #include <stdint.h> #include <stdlib.h> #include <iterator> #include "sfz/SmartPtr.hpp" #include "sfz/WriteItem.hpp" #include "sfz/WriteTarget.hpp" namespace sfz { class BytesPiece; class Bytes { public: // STL container types and constants. typedef uint8_t value_type; typedef uint8_t* pointer; typedef uint8_t& reference; typedef const uint8_t& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; static const size_type npos; typedef uint8_t* iterator; typedef const uint8_t* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; Bytes(); explicit Bytes(const Bytes& bytes); explicit Bytes(const BytesPiece& bytes); Bytes(const uint8_t* data, size_t size); Bytes(WriteItem item); Bytes(size_t num, uint8_t byte); ~Bytes(); const uint8_t* data() const; uint8_t* mutable_data() const; size_t size() const; void append(const BytesPiece& bytes); void append(const uint8_t* data, size_t size); void append(WriteItem item); void append(size_t num, uint8_t byte); void assign(const BytesPiece& bytes); void assign(const uint8_t* data, size_t size); void assign(WriteItem item); void assign(size_t num, uint8_t byte); uint8_t at(size_t loc) const; void clear(); bool empty() const; void reserve(size_t capacity); void resize(size_t size, uint8_t byte = '\0'); void swap(Bytes* bytes); // Iterator support. iterator begin() { return iterator(_data.get()); } iterator end() { return iterator(_data.get() + _size); } const_iterator begin() const { return const_iterator(_data.get()); } const_iterator end() const { return const_iterator(_data.get() + _size); } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } private: scoped_array<uint8_t> _data; size_t _size; size_t _capacity; // Disallow assignment. Bytes& operator=(const Bytes&); }; class BytesPiece { public: // STL container types and constants. typedef uint8_t value_type; typedef const uint8_t* pointer; typedef const uint8_t& reference; typedef const uint8_t& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; static const size_type npos; typedef const uint8_t* iterator; typedef const uint8_t* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; // Constructors. BytesPiece(); BytesPiece(const Bytes& bytes); BytesPiece(const char* data); BytesPiece(const uint8_t* data, size_t size); const uint8_t* data() const; size_t size() const; uint8_t at(size_t loc) const; bool empty() const; BytesPiece substr(size_t index) const; BytesPiece substr(size_t index, size_t size) const; void shift(size_t size); void shift(uint8_t* data, size_t size); const_iterator begin() const { return const_iterator(_data); } const_iterator end() const { return const_iterator(_data + _size); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } private: const uint8_t* _data; size_t _size; // ALLOW_COPY_AND_ASSIGN }; inline void write_to(WriteTarget out, const Bytes& bytes) { out.append(bytes); } inline void write_to(WriteTarget out, const BytesPiece& bytes) { out.append(bytes); } bool operator==(const Bytes& lhs, const Bytes& rhs); bool operator!=(const Bytes& lhs, const Bytes& rhs); bool operator==(const BytesPiece& lhs, const BytesPiece& rhs); bool operator!=(const BytesPiece& lhs, const BytesPiece& rhs); } // namespace sfz #endif // SFZ_BYTES_HPP_ <commit_msg>Make Bytes constructor explicit.<commit_after>// Copyright (c) 2009 Chris Pickel <sfiera@gmail.com> // // This file is part of libsfz, a free software project. You can redistribute // it and/or modify it under the terms of the MIT License. #ifndef SFZ_BYTES_HPP_ #define SFZ_BYTES_HPP_ #include <stdint.h> #include <stdlib.h> #include <iterator> #include "sfz/SmartPtr.hpp" #include "sfz/WriteItem.hpp" #include "sfz/WriteTarget.hpp" namespace sfz { class BytesPiece; class Bytes { public: // STL container types and constants. typedef uint8_t value_type; typedef uint8_t* pointer; typedef uint8_t& reference; typedef const uint8_t& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; static const size_type npos; typedef uint8_t* iterator; typedef const uint8_t* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; Bytes(); explicit Bytes(const Bytes& bytes); explicit Bytes(const BytesPiece& bytes); Bytes(const uint8_t* data, size_t size); explicit Bytes(WriteItem item); Bytes(size_t num, uint8_t byte); ~Bytes(); const uint8_t* data() const; uint8_t* mutable_data() const; size_t size() const; void append(const BytesPiece& bytes); void append(const uint8_t* data, size_t size); void append(WriteItem item); void append(size_t num, uint8_t byte); void assign(const BytesPiece& bytes); void assign(const uint8_t* data, size_t size); void assign(WriteItem item); void assign(size_t num, uint8_t byte); uint8_t at(size_t loc) const; void clear(); bool empty() const; void reserve(size_t capacity); void resize(size_t size, uint8_t byte = '\0'); void swap(Bytes* bytes); // Iterator support. iterator begin() { return iterator(_data.get()); } iterator end() { return iterator(_data.get() + _size); } const_iterator begin() const { return const_iterator(_data.get()); } const_iterator end() const { return const_iterator(_data.get() + _size); } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } private: scoped_array<uint8_t> _data; size_t _size; size_t _capacity; // Disallow assignment. Bytes& operator=(const Bytes&); }; class BytesPiece { public: // STL container types and constants. typedef uint8_t value_type; typedef const uint8_t* pointer; typedef const uint8_t& reference; typedef const uint8_t& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; static const size_type npos; typedef const uint8_t* iterator; typedef const uint8_t* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; // Constructors. BytesPiece(); BytesPiece(const Bytes& bytes); BytesPiece(const char* data); BytesPiece(const uint8_t* data, size_t size); const uint8_t* data() const; size_t size() const; uint8_t at(size_t loc) const; bool empty() const; BytesPiece substr(size_t index) const; BytesPiece substr(size_t index, size_t size) const; void shift(size_t size); void shift(uint8_t* data, size_t size); const_iterator begin() const { return const_iterator(_data); } const_iterator end() const { return const_iterator(_data + _size); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } private: const uint8_t* _data; size_t _size; // ALLOW_COPY_AND_ASSIGN }; inline void write_to(WriteTarget out, const Bytes& bytes) { out.append(bytes); } inline void write_to(WriteTarget out, const BytesPiece& bytes) { out.append(bytes); } bool operator==(const Bytes& lhs, const Bytes& rhs); bool operator!=(const Bytes& lhs, const Bytes& rhs); bool operator==(const BytesPiece& lhs, const BytesPiece& rhs); bool operator!=(const BytesPiece& lhs, const BytesPiece& rhs); } // namespace sfz #endif // SFZ_BYTES_HPP_ <|endoftext|>
<commit_before>#include "vecscontroller.h" #include <QObjectList> VecsController::VecsController(QObject *parent) : QObject(parent), m_discovering(false), m_agent(new QBluetoothDeviceDiscoveryAgent(this)) { connect(m_agent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)), this, SLOT(addDevice(QBluetoothDeviceInfo))); connect(m_agent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error)), this, SLOT(deviceScanError(QBluetoothDeviceDiscoveryAgent::Error))); connect(m_agent, SIGNAL(finished()), this, SLOT(scanFinished())); } VecsController::~VecsController() { qDeleteAll(m_devices); m_devices.clear(); } void VecsController::startScan() { qDeleteAll(m_devices); m_devices.clear(); emit devicesUpdated(); m_agent->start(); m_discovering = true; emit stateChanged(); setMessage("Scanning for devices..."); } void VecsController::setMessage(const QString &message) { m_message = message; emit messageChanged(); } void VecsController::startSession() { for (const auto& dev : m_devices) { switch (dev->role()) { case VecsDevice::RoleUndefined: dev->disconnectFromDevice(); break; case VecsDevice::RoleDoctor: if (dev->connectionState() == VecsDevice::StateDisconnected) dev->connectToDevice(); break; case VecsDevice::RolePatientHand: case VecsDevice::RolePatientBack: if (dev->connectionState() == VecsDevice::StateConnected) { dev->mpuStart(); } else if (dev->connectionState() == VecsDevice::StateDisconnected) { dev->connectToDevice(); // MPU запуститься автоматически, т.к. выставлена роль } break; } } } QString VecsController::message() const { return m_message; } QVariant VecsController::model() const { QObjectList objects; for (const auto& i : m_devices) objects.append(i); return QVariant::fromValue(objects); } QList<VecsDevice *> VecsController::devices() const { return m_devices; } bool VecsController::discovering() const { return m_discovering; } void VecsController::addDevice(const QBluetoothDeviceInfo &device) { if (device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration && device.name().contains("VE Control Sensor")) { VecsDevice *vecs = new VecsDevice(device.address(), device.rssi(), this); m_devices.append(vecs); emit devicesUpdated(); setMessage(QString("Device found [%1]").arg(device.address().toString())); } } void VecsController::scanFinished() { emit devicesUpdated(); m_discovering = false; emit stateChanged(); if (m_devices.isEmpty()) { setMessage("Scan finished: no devices found"); } else { setMessage(QString("Scan finished: found %1 devices").arg(m_devices.size())); } } void VecsController::deviceScanError(QBluetoothDeviceDiscoveryAgent::Error error) { if (error == QBluetoothDeviceDiscoveryAgent::PoweredOffError) setMessage("The Bluetooth adaptor is powered off, power it on before doing discovery."); else if (error == QBluetoothDeviceDiscoveryAgent::InputOutputError) setMessage("Writing or reading from the device resulted in an error."); else setMessage("An unknown error has occurred."); } <commit_msg>fix bug with MPU data receiving when Doctor role selected<commit_after>#include "vecscontroller.h" #include <QObjectList> VecsController::VecsController(QObject *parent) : QObject(parent), m_discovering(false), m_agent(new QBluetoothDeviceDiscoveryAgent(this)) { connect(m_agent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)), this, SLOT(addDevice(QBluetoothDeviceInfo))); connect(m_agent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error)), this, SLOT(deviceScanError(QBluetoothDeviceDiscoveryAgent::Error))); connect(m_agent, SIGNAL(finished()), this, SLOT(scanFinished())); } VecsController::~VecsController() { qDeleteAll(m_devices); m_devices.clear(); } void VecsController::startScan() { qDeleteAll(m_devices); m_devices.clear(); emit devicesUpdated(); m_agent->start(); m_discovering = true; emit stateChanged(); setMessage("Scanning for devices..."); } void VecsController::setMessage(const QString &message) { m_message = message; emit messageChanged(); } void VecsController::startSession() { for (const auto& dev : m_devices) { switch (dev->role()) { case VecsDevice::RoleUndefined: dev->disconnectFromDevice(); break; case VecsDevice::RoleDoctor: if (dev->connectionState() == VecsDevice::StateDisconnected) dev->connectToDevice(); else if (dev->connectionState() == VecsDevice::StateConnected) if (dev->mpuState()) dev->mpuStop(); break; case VecsDevice::RolePatientHand: case VecsDevice::RolePatientBack: if (dev->connectionState() == VecsDevice::StateConnected) { dev->mpuStart(); } else if (dev->connectionState() == VecsDevice::StateDisconnected) { dev->connectToDevice(); // MPU запуститься автоматически, т.к. выставлена роль } break; } } } QString VecsController::message() const { return m_message; } QVariant VecsController::model() const { QObjectList objects; for (const auto& i : m_devices) objects.append(i); return QVariant::fromValue(objects); } QList<VecsDevice *> VecsController::devices() const { return m_devices; } bool VecsController::discovering() const { return m_discovering; } void VecsController::addDevice(const QBluetoothDeviceInfo &device) { if (device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration && device.name().contains("VE Control Sensor")) { VecsDevice *vecs = new VecsDevice(device.address(), device.rssi(), this); m_devices.append(vecs); emit devicesUpdated(); setMessage(QString("Device found [%1]").arg(device.address().toString())); } } void VecsController::scanFinished() { emit devicesUpdated(); m_discovering = false; emit stateChanged(); if (m_devices.isEmpty()) { setMessage("Scan finished: no devices found"); } else { setMessage(QString("Scan finished: found %1 devices").arg(m_devices.size())); } } void VecsController::deviceScanError(QBluetoothDeviceDiscoveryAgent::Error error) { if (error == QBluetoothDeviceDiscoveryAgent::PoweredOffError) setMessage("The Bluetooth adaptor is powered off, power it on before doing discovery."); else if (error == QBluetoothDeviceDiscoveryAgent::InputOutputError) setMessage("Writing or reading from the device resulted in an error."); else setMessage("An unknown error has occurred."); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkGIFVolumetricStatistics.h> // MITK #include <mitkITKImageImport.h> #include <mitkImageCast.h> #include <mitkImageAccessByItk.h> // ITK #include <itkLabelStatisticsImageFilter.h> // VTK #include <vtkSmartPointer.h> #include <vtkImageMarchingCubes.h> #include <vtkMassProperties.h> // STL #include <sstream> #include <vnl/vnl_math.h> template<typename TPixel, unsigned int VImageDimension> void CalculateVolumeStatistic(itk::Image<TPixel, VImageDimension>* itkImage, mitk::Image::Pointer mask, mitk::GIFVolumetricStatistics::FeatureListType & featureList) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<int, VImageDimension> MaskType; typedef itk::LabelStatisticsImageFilter<ImageType, MaskType> FilterType; typedef typename FilterType::HistogramType HistogramType; typedef typename HistogramType::IndexType HIndexType; typename MaskType::Pointer maskImage = MaskType::New(); mitk::CastToItkImage(mask, maskImage); typename FilterType::Pointer labelStatisticsImageFilter = FilterType::New(); labelStatisticsImageFilter->SetInput( itkImage ); labelStatisticsImageFilter->SetLabelInput(maskImage); labelStatisticsImageFilter->Update(); double volume = labelStatisticsImageFilter->GetCount(1); for (int i = 0; i < VImageDimension; ++i) { volume *= itkImage->GetSpacing()[i]; } featureList.push_back(std::make_pair("Volumetric Features Volume (pixel based)",volume)); } mitk::GIFVolumetricStatistics::GIFVolumetricStatistics() { } mitk::GIFVolumetricStatistics::FeatureListType mitk::GIFVolumetricStatistics::CalculateFeatures(const Image::Pointer & image, const Image::Pointer &mask) { FeatureListType featureList; AccessByItk_2(image, CalculateVolumeStatistic, mask, featureList); vtkSmartPointer<vtkImageMarchingCubes> mesher = vtkSmartPointer<vtkImageMarchingCubes>::New(); vtkSmartPointer<vtkMassProperties> stats = vtkSmartPointer<vtkMassProperties>::New(); mesher->SetInputData(mask->GetVtkImageData()); stats->SetInputConnection(mesher->GetOutputPort()); stats->Update(); double pi = vnl_math::pi; double meshVolume = stats->GetVolume(); double meshSurf = stats->GetSurfaceArea(); double pixelVolume = featureList[0].second; double compactness1 = pixelVolume / ( std::sqrt(pi) * std::pow(meshSurf, 2.0/3.0)); double compactness2 = 36*pi*pixelVolume*pixelVolume/meshSurf/meshSurf/meshSurf; double sphericity=std::pow(pi,1/3.0) *std::pow(6*pixelVolume, 2.0/3.0) / meshSurf; double surfaceToVolume = meshSurf / pixelVolume; featureList.push_back(std::make_pair("Volumetric Features Volume (mesh based)",meshVolume)); featureList.push_back(std::make_pair("Volumetric Features Surface area",meshSurf)); featureList.push_back(std::make_pair("Volumetric Features Surface to volume ratio",surfaceToVolume)); featureList.push_back(std::make_pair("Volumetric Features Sphericity",sphericity)); featureList.push_back(std::make_pair("Volumetric Features Compactness 1",compactness1)); featureList.push_back(std::make_pair("Volumetric Features Compactness 2",compactness2)); return featureList; } mitk::GIFVolumetricStatistics::FeatureNameListType mitk::GIFVolumetricStatistics::GetFeatureNames() { FeatureNameListType featureList; featureList.push_back("FirstOrder Minimum"); featureList.push_back("FirstOrder Maximum"); featureList.push_back("FirstOrder Mean"); featureList.push_back("FirstOrder Variance"); featureList.push_back("FirstOrder Sum"); featureList.push_back("FirstOrder Median"); featureList.push_back("FirstOrder Standard deviation"); featureList.push_back("FirstOrder No. of Voxel"); return featureList; }<commit_msg>Added longest diameter<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkGIFVolumetricStatistics.h> // MITK #include <mitkITKImageImport.h> #include <mitkImageCast.h> #include <mitkImageAccessByItk.h> // ITK #include <itkLabelStatisticsImageFilter.h> #include <itkNeighborhoodIterator.h> // VTK #include <vtkSmartPointer.h> #include <vtkImageMarchingCubes.h> #include <vtkMassProperties.h> // STL #include <sstream> #include <vnl/vnl_math.h> template<typename TPixel, unsigned int VImageDimension> void CalculateVolumeStatistic(itk::Image<TPixel, VImageDimension>* itkImage, mitk::Image::Pointer mask, mitk::GIFVolumetricStatistics::FeatureListType & featureList) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<int, VImageDimension> MaskType; typedef itk::LabelStatisticsImageFilter<ImageType, MaskType> FilterType; typedef typename FilterType::HistogramType HistogramType; typedef typename HistogramType::IndexType HIndexType; typename MaskType::Pointer maskImage = MaskType::New(); mitk::CastToItkImage(mask, maskImage); typename FilterType::Pointer labelStatisticsImageFilter = FilterType::New(); labelStatisticsImageFilter->SetInput( itkImage ); labelStatisticsImageFilter->SetLabelInput(maskImage); labelStatisticsImageFilter->Update(); double volume = labelStatisticsImageFilter->GetCount(1); for (int i = 0; i < VImageDimension; ++i) { volume *= itkImage->GetSpacing()[i]; } featureList.push_back(std::make_pair("Volumetric Features Volume (pixel based)",volume)); } template<typename TPixel, unsigned int VImageDimension> void CalculateLargestDiameter(itk::Image<TPixel, VImageDimension>* mask, mitk::GIFVolumetricStatistics::FeatureListType & featureList) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef typename ImageType::PointType PointType; typename ImageType::SizeType radius; for (int i=0; i < VImageDimension; ++i) radius[i] = 1; itk::NeighborhoodIterator<ImageType> iterator(radius,mask, mask->GetRequestedRegion()); std::vector<PointType> borderPoints; while(!iterator.IsAtEnd()) { if (iterator.GetCenterPixel() == 0) { ++iterator; continue; } bool border = false; for (int i = 0; i < iterator.Size(); ++i) { if (iterator.GetPixel(i) == 0) { border = true; break; } } if (border) { auto centerIndex = iterator.GetIndex(); PointType centerPoint; mask->TransformIndexToPhysicalPoint(centerIndex, centerPoint ); borderPoints.push_back(centerPoint); } ++iterator; } double longestDiameter = 0; unsigned long numberOfBorderPoints = borderPoints.size(); for (int i = 0; i < numberOfBorderPoints; ++i) { auto point = borderPoints[i]; for (int j = i; j < numberOfBorderPoints; ++j) { double newDiameter=point.EuclideanDistanceTo(borderPoints[j]); if (newDiameter > longestDiameter) longestDiameter = newDiameter; } } featureList.push_back(std::make_pair("Volumetric Features Maximum 3D diameter",longestDiameter)); } mitk::GIFVolumetricStatistics::GIFVolumetricStatistics() { } mitk::GIFVolumetricStatistics::FeatureListType mitk::GIFVolumetricStatistics::CalculateFeatures(const Image::Pointer & image, const Image::Pointer &mask) { FeatureListType featureList; AccessByItk_2(image, CalculateVolumeStatistic, mask, featureList); AccessByItk_1(mask, CalculateLargestDiameter, featureList); vtkSmartPointer<vtkImageMarchingCubes> mesher = vtkSmartPointer<vtkImageMarchingCubes>::New(); vtkSmartPointer<vtkMassProperties> stats = vtkSmartPointer<vtkMassProperties>::New(); mesher->SetInputData(mask->GetVtkImageData()); stats->SetInputConnection(mesher->GetOutputPort()); stats->Update(); double pi = vnl_math::pi; double meshVolume = stats->GetVolume(); double meshSurf = stats->GetSurfaceArea(); double pixelVolume = featureList[0].second; double compactness1 = pixelVolume / ( std::sqrt(pi) * std::pow(meshSurf, 2.0/3.0)); double compactness2 = 36*pi*pixelVolume*pixelVolume/meshSurf/meshSurf/meshSurf; double sphericity=std::pow(pi,1/3.0) *std::pow(6*pixelVolume, 2.0/3.0) / meshSurf; double surfaceToVolume = meshSurf / pixelVolume; double sphericalDisproportion = meshSurf / 4 / pi / std::pow(3.0 / 4.0 / pi * pixelVolume, 2.0 / 3.0); featureList.push_back(std::make_pair("Volumetric Features Volume (mesh based)",meshVolume)); featureList.push_back(std::make_pair("Volumetric Features Surface area",meshSurf)); featureList.push_back(std::make_pair("Volumetric Features Surface to volume ratio",surfaceToVolume)); featureList.push_back(std::make_pair("Volumetric Features Sphericity",sphericity)); featureList.push_back(std::make_pair("Volumetric Features Compactness 1",compactness1)); featureList.push_back(std::make_pair("Volumetric Features Compactness 2",compactness2)); featureList.push_back(std::make_pair("Volumetric Features Spherical disproportion",sphericalDisproportion)); return featureList; } mitk::GIFVolumetricStatistics::FeatureNameListType mitk::GIFVolumetricStatistics::GetFeatureNames() { FeatureNameListType featureList; featureList.push_back("Volumetric Features Compactness 1"); featureList.push_back("Volumetric Features Compactness 2"); featureList.push_back("Volumetric Features Sphericity"); featureList.push_back("Volumetric Features Surface to volume ratio"); featureList.push_back("Volumetric Features Surface area"); featureList.push_back("Volumetric Features Volume (mesh based)"); featureList.push_back("Volumetric Features Volume (pixel based)"); featureList.push_back("Volumetric Features Spherical disproportion"); featureList.push_back("Volumetric Features Maximum 3D diameter"); return featureList; }<|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <string> #include <random> #include <unordered_map> #include <vector> #include <stdexcept> struct FileNotFound : public std::runtime_error { explicit FileNotFound(const char* message) : std::runtime_error{message} { }; explicit FileNotFound(const std::string& message) : std::runtime_error{message.c_str()} { }; }; void read_dict(const std::string& filename, std::unordered_map<int, std::string>& map) { int key; std::string word; std::fstream fs{filename, std::fstream::in}; if (fs.fail()) throw FileNotFound{filename + " is not in the current directory"}; while (!fs.eof()) { fs >> key; std::getline(fs, word); word.erase(0, word.find_first_not_of("\t ")); map[key] = word; } } // Fills the rows with digits std::vector<int> get_word_codes(int no_of_words, int digits_per_word) { std::vector<int> temp(no_of_words, 0); std::random_device rd; std::mt19937 mt{rd()}; std::uniform_int_distribution<int> dist(1, 5); for (int i = 0; i < no_of_words; ++i) { for (int j = digits_per_word-1; j >= 0; --j) temp[i] += dist(mt) * pow(10, j); } return std::move(temp); } int main(int argc, char* argv[]) try { std::unordered_map<int, std::string> dice_map; read_dict("diceware_dict.txt", dice_map); // Creates a matrix of // words in pass x digits_per_word const int no_of_words = argc > 2 ? std::stoi(argv[1]) : 5; constexpr int digits_per_word = 5; const std::vector<int> word_codes = get_word_codes(no_of_words, digits_per_word); std::cout << "Here is your diceware word list\n"; std::cout << "-------------------------------\n"; for (int code : word_codes) std::cout << dice_map[code] << " "; std::cout << "\n"; } catch (const FileNotFound& e) { std::cout << e.what() << std::endl; return -4; } catch (...) { std::cout << "Something strange happened..." << std::endl; return -77; } <commit_msg>Added easy copying and modularized word code generation<commit_after>#include <fstream> #include <iostream> #include <string> #include <random> #include <unordered_map> #include <vector> #include <stdexcept> struct FileNotFound : public std::runtime_error { explicit FileNotFound(const char* message) : std::runtime_error{message} { }; explicit FileNotFound(const std::string& message) : std::runtime_error{message.c_str()} { }; }; void read_dict(const std::string& filename, std::unordered_map<int, std::string>& map) { int key; std::string word; std::fstream fs{filename, std::fstream::in}; if (fs.fail()) throw FileNotFound{filename + " is not in the current directory"}; while (!fs.eof()) { fs >> key; std::getline(fs, word); word.erase(0, word.find_first_not_of("\t ")); map[key] = word; } } // Functor used to cache random number generator rather than // instantiating it over again in a function call class GetWordCode { int digits_per_word; std::random_device rd; std::mt19937 mt{}; std::uniform_int_distribution<int> dist; public: explicit GetWordCode(int dpw) : digits_per_word{dpw}, rd{}, mt{rd()}, dist{1, 5} { }; int operator()() { int word_code = 0; for (int i = digits_per_word-1; i >= 0; --i) word_code += dist(mt) * pow(10, i); return word_code; } }; int main(int argc, char* argv[]) try { std::unordered_map<int, std::string> dice_map; read_dict("diceware_dict.txt", dice_map); const int no_of_words = argc > 2 ? std::stoi(argv[1]) : 5; constexpr int digits_per_word = 5; GetWordCode get_word_code{digits_per_word}; std::vector<int> word_codes(no_of_words, 0); for (int& word_code : word_codes) word_code = get_word_code(); std::cout << " ---------------------------------\n"; std::cout << "| Here is your diceware word list |\n"; std::cout << " ---------------------------------\n"; std::cout << "With spaces: "; for (int code : word_codes) std::cout << dice_map[code] << " "; std::cout << "\n"; std::cout << "Without spaces: "; for (int code : word_codes) std::cout << dice_map[code]; std::cout << "\n"; } catch (const FileNotFound& e) { std::cout << e.what() << std::endl; return -4; } catch (...) { std::cout << "Something strange happened..." << std::endl; return -77; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LegendEntryProvider.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 19:18:58 $ * * 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 CHART2_VIEW_LEGENDENTRYPROVIDER_HXX #define CHART2_VIEW_LEGENDENTRYPROVIDER_HXX #ifndef _COM_SUN_STAR_CHART2_LEGENDEXPANSION_HPP_ #include <com/sun/star/chart2/LegendExpansion.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_VIEWLEGENDENTRYP_HPP_ #include <com/sun/star/chart2/ViewLegendEntry.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif namespace chart { class LegendEntryProvider { public: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::ViewLegendEntry > SAL_CALL createLegendEntries( ::com::sun::star::chart2::LegendExpansion eLegendExpansion, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xTextProperties, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xShapeFactory, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext ) throw (::com::sun::star::uno::RuntimeException) = 0; private: }; } // namespace chart // CHART2_VIEW_LEGENDENTRYPROVIDER_HXX #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.126); FILE MERGED 2008/04/01 10:50:41 thb 1.2.126.2: #i85898# Stripping all external header guards 2008/03/28 16:44:43 rt 1.2.126.1: #i87441# Change license header to LPGL v3.<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: LegendEntryProvider.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 CHART2_VIEW_LEGENDENTRYPROVIDER_HXX #define CHART2_VIEW_LEGENDENTRYPROVIDER_HXX #include <com/sun/star/chart2/LegendExpansion.hpp> #ifndef _COM_SUN_STAR_CHART2_VIEWLEGENDENTRYP_HPP_ #include <com/sun/star/chart2/ViewLegendEntry.hpp> #endif #include <com/sun/star/uno/XComponentContext.hpp> namespace chart { class LegendEntryProvider { public: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::chart2::ViewLegendEntry > SAL_CALL createLegendEntries( ::com::sun::star::chart2::LegendExpansion eLegendExpansion, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xTextProperties, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xTarget, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xShapeFactory, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext ) throw (::com::sun::star::uno::RuntimeException) = 0; private: }; } // namespace chart // CHART2_VIEW_LEGENDENTRYPROVIDER_HXX #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/update_screen.h" #include "base/file_util.h" #include "base/logging.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_screen_actor.h" #include "chrome/browser/chromeos/login/views_update_screen_actor.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "content/browser/browser_thread.h" namespace chromeos { namespace { // Progress bar stages. Each represents progress bar value // at the beginning of each stage. // TODO(nkostylev): Base stage progress values on approximate time. // TODO(nkostylev): Animate progress during each state. const int kBeforeUpdateCheckProgress = 7; const int kBeforeDownloadProgress = 14; const int kBeforeVerifyingProgress = 74; const int kBeforeFinalizingProgress = 81; const int kProgressComplete = 100; // Defines what part of update progress does download part takes. const int kDownloadProgressIncrement = 60; // Considering 10px shadow from each side. const int kUpdateScreenWidth = 580; const int kUpdateScreenHeight = 305; const char kUpdateDeadlineFile[] = "/tmp/update-check-response-deadline"; // Invoked from call to RequestUpdateCheck upon completion of the DBus call. void StartUpdateCallback(void* user_data, UpdateResult result, const char* msg) { if (result != chromeos::UPDATE_RESULT_SUCCESS) { DCHECK(user_data); UpdateScreen* screen = static_cast<UpdateScreen*>(user_data); if (UpdateScreen::HasInstance(screen)) screen->ExitUpdate(UpdateScreen::REASON_UPDATE_INIT_FAILED); } } } // anonymous namespace // static UpdateScreen::InstanceSet& UpdateScreen::GetInstanceSet() { static std::set<UpdateScreen*> instance_set; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // not threadsafe. return instance_set; } // static bool UpdateScreen::HasInstance(UpdateScreen* inst) { InstanceSet& instance_set = GetInstanceSet(); InstanceSet::iterator found = instance_set.find(inst); return (found != instance_set.end()); } UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : WizardScreen(delegate), reboot_check_delay_(0), is_checking_for_update_(true), is_downloading_update_(false), is_ignore_update_deadlines_(true), // See http://crosbug.com/10068 is_shown_(false), actor_(new ViewsUpdateScreenActor(delegate, kUpdateScreenWidth, kUpdateScreenHeight)) { GetInstanceSet().insert(this); } UpdateScreen::~UpdateScreen() { CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); GetInstanceSet().erase(this); } void UpdateScreen::UpdateStatusChanged(UpdateLibrary* library) { UpdateStatusOperation status = library->status().status; if (is_checking_for_update_ && status > UPDATE_STATUS_CHECKING_FOR_UPDATE) { is_checking_for_update_ = false; } switch (status) { case UPDATE_STATUS_CHECKING_FOR_UPDATE: // Do nothing in these cases, we don't want to notify the user of the // check unless there is an update. break; case UPDATE_STATUS_UPDATE_AVAILABLE: MakeSureScreenIsShown(); actor_->SetProgress(kBeforeDownloadProgress); if (!HasCriticalUpdate()) { LOG(INFO) << "Noncritical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } break; case UPDATE_STATUS_DOWNLOADING: { MakeSureScreenIsShown(); if (!is_downloading_update_) { // Because update engine doesn't send UPDATE_STATUS_UPDATE_AVAILABLE // we need to is update critical on first downloading notification. is_downloading_update_ = true; if (!HasCriticalUpdate()) { LOG(INFO) << "Non-critical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } } actor_->ShowCurtain(false); int download_progress = static_cast<int>( library->status().download_progress * kDownloadProgressIncrement); actor_->SetProgress(kBeforeDownloadProgress + download_progress); } break; case UPDATE_STATUS_VERIFYING: MakeSureScreenIsShown(); actor_->SetProgress(kBeforeVerifyingProgress); break; case UPDATE_STATUS_FINALIZING: MakeSureScreenIsShown(); actor_->SetProgress(kBeforeFinalizingProgress); break; case UPDATE_STATUS_UPDATED_NEED_REBOOT: MakeSureScreenIsShown(); // Make sure that first OOBE stage won't be shown after reboot. WizardController::MarkOobeCompleted(); actor_->SetProgress(kProgressComplete); if (HasCriticalUpdate()) { actor_->ShowCurtain(false); VLOG(1) << "Initiate reboot after update"; CrosLibrary::Get()->GetUpdateLibrary()->RebootAfterUpdate(); reboot_timer_.Start(base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); } else { ExitUpdate(REASON_UPDATE_NON_CRITICAL); } break; case UPDATE_STATUS_IDLE: case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: ExitUpdate(REASON_UPDATE_ENDED); break; default: NOTREACHED(); break; } } void UpdateScreen::StartUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) { LOG(ERROR) << "Error loading CrosLibrary"; ExitUpdate(REASON_UPDATE_INIT_FAILED); } else { CrosLibrary::Get()->GetUpdateLibrary()->AddObserver(this); VLOG(1) << "Initiate update check"; CrosLibrary::Get()->GetUpdateLibrary()->RequestUpdateCheck( StartUpdateCallback, this); } } void UpdateScreen::CancelUpdate() { ExitUpdate(REASON_UPDATE_CANCELED); } void UpdateScreen::Show() { is_shown_ = true; actor_->Show(); actor_->SetProgress(kBeforeUpdateCheckProgress); } void UpdateScreen::Hide() { actor_->Hide(); is_shown_ = false; } gfx::Size UpdateScreen::GetScreenSize() const { return gfx::Size(kUpdateScreenWidth, kUpdateScreenHeight); } void UpdateScreen::ExitUpdate(UpdateScreen::ExitReason reason) { ScreenObserver* observer = delegate()->GetObserver(this); if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); switch (reason) { case REASON_UPDATE_CANCELED: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case REASON_UPDATE_INIT_FAILED: observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); break; case REASON_UPDATE_NON_CRITICAL: case REASON_UPDATE_ENDED: { UpdateLibrary* update_library = CrosLibrary::Get()->GetUpdateLibrary(); switch (update_library->status().status) { case UPDATE_STATUS_UPDATE_AVAILABLE: case UPDATE_STATUS_UPDATED_NEED_REBOOT: case UPDATE_STATUS_DOWNLOADING: case UPDATE_STATUS_FINALIZING: case UPDATE_STATUS_VERIFYING: DCHECK(!HasCriticalUpdate()); // Noncritical update, just exit screen as if there is no update. // no break case UPDATE_STATUS_IDLE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: observer->OnExit(is_checking_for_update_ ? ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE : ScreenObserver::UPDATE_ERROR_UPDATING); break; default: NOTREACHED(); } } break; default: NOTREACHED(); } } void UpdateScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking user for a manual reboot."; MakeSureScreenIsShown(); actor_->ShowManualRebootInfo(); } void UpdateScreen::MakeSureScreenIsShown() { if (!is_shown_) delegate()->ShowCurrentScreen(); } void UpdateScreen::SetRebootCheckDelay(int seconds) { if (seconds <= 0) reboot_timer_.Stop(); DCHECK(!reboot_timer_.IsRunning()); reboot_check_delay_ = seconds; } bool UpdateScreen::HasCriticalUpdate() { if (is_ignore_update_deadlines_) return true; std::string deadline; // Checking for update flag file causes us to do blocking IO on UI thread. // Temporarily allow it until we fix http://crosbug.com/11106 base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath update_deadline_file_path(kUpdateDeadlineFile); if (!file_util::ReadFileToString(update_deadline_file_path, &deadline) || deadline.empty()) { return false; } // TODO(dpolukhin): Analyze file content. Now we can just assume that // if the file exists and not empty, there is critical update. return true; } } // namespace chromeos <commit_msg>Revert 81536 that made all updates during OOBE required<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/update_screen.h" #include "base/file_util.h" #include "base/logging.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/update_screen_actor.h" #include "chrome/browser/chromeos/login/views_update_screen_actor.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "content/browser/browser_thread.h" namespace chromeos { namespace { // Progress bar stages. Each represents progress bar value // at the beginning of each stage. // TODO(nkostylev): Base stage progress values on approximate time. // TODO(nkostylev): Animate progress during each state. const int kBeforeUpdateCheckProgress = 7; const int kBeforeDownloadProgress = 14; const int kBeforeVerifyingProgress = 74; const int kBeforeFinalizingProgress = 81; const int kProgressComplete = 100; // Defines what part of update progress does download part takes. const int kDownloadProgressIncrement = 60; // Considering 10px shadow from each side. const int kUpdateScreenWidth = 580; const int kUpdateScreenHeight = 305; const char kUpdateDeadlineFile[] = "/tmp/update-check-response-deadline"; // Invoked from call to RequestUpdateCheck upon completion of the DBus call. void StartUpdateCallback(void* user_data, UpdateResult result, const char* msg) { if (result != chromeos::UPDATE_RESULT_SUCCESS) { DCHECK(user_data); UpdateScreen* screen = static_cast<UpdateScreen*>(user_data); if (UpdateScreen::HasInstance(screen)) screen->ExitUpdate(UpdateScreen::REASON_UPDATE_INIT_FAILED); } } } // anonymous namespace // static UpdateScreen::InstanceSet& UpdateScreen::GetInstanceSet() { static std::set<UpdateScreen*> instance_set; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // not threadsafe. return instance_set; } // static bool UpdateScreen::HasInstance(UpdateScreen* inst) { InstanceSet& instance_set = GetInstanceSet(); InstanceSet::iterator found = instance_set.find(inst); return (found != instance_set.end()); } UpdateScreen::UpdateScreen(WizardScreenDelegate* delegate) : WizardScreen(delegate), reboot_check_delay_(0), is_checking_for_update_(true), is_downloading_update_(false), is_ignore_update_deadlines_(false), is_shown_(false), actor_(new ViewsUpdateScreenActor(delegate, kUpdateScreenWidth, kUpdateScreenHeight)) { GetInstanceSet().insert(this); } UpdateScreen::~UpdateScreen() { CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); GetInstanceSet().erase(this); } void UpdateScreen::UpdateStatusChanged(UpdateLibrary* library) { UpdateStatusOperation status = library->status().status; if (is_checking_for_update_ && status > UPDATE_STATUS_CHECKING_FOR_UPDATE) { is_checking_for_update_ = false; } switch (status) { case UPDATE_STATUS_CHECKING_FOR_UPDATE: // Do nothing in these cases, we don't want to notify the user of the // check unless there is an update. break; case UPDATE_STATUS_UPDATE_AVAILABLE: MakeSureScreenIsShown(); actor_->SetProgress(kBeforeDownloadProgress); if (!HasCriticalUpdate()) { LOG(INFO) << "Noncritical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } break; case UPDATE_STATUS_DOWNLOADING: { MakeSureScreenIsShown(); if (!is_downloading_update_) { // Because update engine doesn't send UPDATE_STATUS_UPDATE_AVAILABLE // we need to is update critical on first downloading notification. is_downloading_update_ = true; if (!HasCriticalUpdate()) { LOG(INFO) << "Non-critical update available: " << library->status().new_version; ExitUpdate(REASON_UPDATE_NON_CRITICAL); } else { LOG(INFO) << "Critical update available: " << library->status().new_version; } } actor_->ShowCurtain(false); int download_progress = static_cast<int>( library->status().download_progress * kDownloadProgressIncrement); actor_->SetProgress(kBeforeDownloadProgress + download_progress); } break; case UPDATE_STATUS_VERIFYING: MakeSureScreenIsShown(); actor_->SetProgress(kBeforeVerifyingProgress); break; case UPDATE_STATUS_FINALIZING: MakeSureScreenIsShown(); actor_->SetProgress(kBeforeFinalizingProgress); break; case UPDATE_STATUS_UPDATED_NEED_REBOOT: MakeSureScreenIsShown(); // Make sure that first OOBE stage won't be shown after reboot. WizardController::MarkOobeCompleted(); actor_->SetProgress(kProgressComplete); if (HasCriticalUpdate()) { actor_->ShowCurtain(false); VLOG(1) << "Initiate reboot after update"; CrosLibrary::Get()->GetUpdateLibrary()->RebootAfterUpdate(); reboot_timer_.Start(base::TimeDelta::FromSeconds(reboot_check_delay_), this, &UpdateScreen::OnWaitForRebootTimeElapsed); } else { ExitUpdate(REASON_UPDATE_NON_CRITICAL); } break; case UPDATE_STATUS_IDLE: case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: ExitUpdate(REASON_UPDATE_ENDED); break; default: NOTREACHED(); break; } } void UpdateScreen::StartUpdate() { if (!CrosLibrary::Get()->EnsureLoaded()) { LOG(ERROR) << "Error loading CrosLibrary"; ExitUpdate(REASON_UPDATE_INIT_FAILED); } else { CrosLibrary::Get()->GetUpdateLibrary()->AddObserver(this); VLOG(1) << "Initiate update check"; CrosLibrary::Get()->GetUpdateLibrary()->RequestUpdateCheck( StartUpdateCallback, this); } } void UpdateScreen::CancelUpdate() { ExitUpdate(REASON_UPDATE_CANCELED); } void UpdateScreen::Show() { is_shown_ = true; actor_->Show(); actor_->SetProgress(kBeforeUpdateCheckProgress); } void UpdateScreen::Hide() { actor_->Hide(); is_shown_ = false; } gfx::Size UpdateScreen::GetScreenSize() const { return gfx::Size(kUpdateScreenWidth, kUpdateScreenHeight); } void UpdateScreen::ExitUpdate(UpdateScreen::ExitReason reason) { ScreenObserver* observer = delegate()->GetObserver(this); if (CrosLibrary::Get()->EnsureLoaded()) CrosLibrary::Get()->GetUpdateLibrary()->RemoveObserver(this); switch (reason) { case REASON_UPDATE_CANCELED: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case REASON_UPDATE_INIT_FAILED: observer->OnExit(ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE); break; case REASON_UPDATE_NON_CRITICAL: case REASON_UPDATE_ENDED: { UpdateLibrary* update_library = CrosLibrary::Get()->GetUpdateLibrary(); switch (update_library->status().status) { case UPDATE_STATUS_UPDATE_AVAILABLE: case UPDATE_STATUS_UPDATED_NEED_REBOOT: case UPDATE_STATUS_DOWNLOADING: case UPDATE_STATUS_FINALIZING: case UPDATE_STATUS_VERIFYING: DCHECK(!HasCriticalUpdate()); // Noncritical update, just exit screen as if there is no update. // no break case UPDATE_STATUS_IDLE: observer->OnExit(ScreenObserver::UPDATE_NOUPDATE); break; case UPDATE_STATUS_ERROR: case UPDATE_STATUS_REPORTING_ERROR_EVENT: observer->OnExit(is_checking_for_update_ ? ScreenObserver::UPDATE_ERROR_CHECKING_FOR_UPDATE : ScreenObserver::UPDATE_ERROR_UPDATING); break; default: NOTREACHED(); } } break; default: NOTREACHED(); } } void UpdateScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking user for a manual reboot."; MakeSureScreenIsShown(); actor_->ShowManualRebootInfo(); } void UpdateScreen::MakeSureScreenIsShown() { if (!is_shown_) delegate()->ShowCurrentScreen(); } void UpdateScreen::SetRebootCheckDelay(int seconds) { if (seconds <= 0) reboot_timer_.Stop(); DCHECK(!reboot_timer_.IsRunning()); reboot_check_delay_ = seconds; } bool UpdateScreen::HasCriticalUpdate() { if (is_ignore_update_deadlines_) return true; std::string deadline; // Checking for update flag file causes us to do blocking IO on UI thread. // Temporarily allow it until we fix http://crosbug.com/11106 base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath update_deadline_file_path(kUpdateDeadlineFile); if (!file_util::ReadFileToString(update_deadline_file_path, &deadline) || deadline.empty()) { return false; } // TODO(dpolukhin): Analyze file content. Now we can just assume that // if the file exists and not empty, there is critical update. return true; } } // namespace chromeos <|endoftext|>
<commit_before>/************************************\ * Copyright (C) 2007 by Sarten-X * \************************************/ #include "config.h" // This is generated in build/config.h from <src>/config.h.in by cmake #include "disconet.h" #include "drawing.h" #include <iostream> #include <sstream> #include <sys/time.h> #include <unistd.h> void loop (runtime_options options); int main(int argc, char* argv[]) { runtime_options options; // Otherwise, remember the chosen interface. options.interface = ""; options.profile = false; options.xscale = 1; options.yscale = 1; // TODO: Reimplement a help message // If a dumb number of parameters was supplied, print the usage message and exit. //if(!(argc == 2 || argc == 4)) { // std::cerr << "Usage: " << argv[0] << " <interface> [xscale yscale]" << std::endl; // return 1; //} int option; opterr = 0; while ((option = getopt (argc, argv, "h:w:i:p")) != -1) switch (option) { case 'h': options.yscale = atof(optarg); case 'w': options.xscale = atof(optarg); case 'i': options.interface = optarg; case 'p': options.profile = true; } if (options.interface == "") { options.interface = argv[optind]; } std::cout << "Finding network interface" << std::endl; // Attempt to get network statistics if (get_network_state(options.interface, NULL) != 0) { // Couldn't find the interface, exit "gracefully" std::cerr << "Failed to find interface \"" << options.interface << "\"" << std::endl; return -1; } if (options.profile) { #ifdef HAVE_PCAP std::cout << "Initializing pcap" << std::endl; if (initialize_pcap(options.interface) != 0) { // Couldn't find the interface, exit "gracefully" std::cerr << "Failed to initialize pcap for \"" << options.interface << "\"" << std::endl; return -1; } #else std::cerr << "Not compiled with libpcap support. Profiling not available." << std::endl; return -1; #endif // HAVE_PCAP } std::cout << "Initializing ncurses" << std::endl; initialize_drawing(); // All configuration is done. std::cout << "Starting monitoring" << std::endl; loop(options); return 0; } void loop (runtime_options options) { int h, w; timeval start_time, end_time; // Declare space for the number of tiles and storing old traffic calculation. long long number = -1; unsigned long long oldtraffic = 0; // Declare placeholders for all the fields in /proc/net/dev. I wallow in wasted RAM. net_state current, old; // Start main loop. This should have some kind of exit. while (1) { gettimeofday(&start_time, NULL); // Save a copy of old data, for calculating change. old = current; if (options.profile) { #ifdef HAVE_PCAP if(get_pcap_network_state(&current) != 0) break; #endif // HAVE_PCAP } else { if(get_network_state(options.interface, &current) != 0) break; } // Begin calculations //std::cout << current.rcvbytes << " " << current.rcvpackets << " " << current.xmtbytes << " " << current.xmtpackets << "\r" << std::endl; paint_drawing(current, options.xscale, options.yscale); gettimeofday(&end_time, NULL); long int usec = REFRESH_TIME - (((end_time.tv_sec - start_time.tv_sec) * 1000000 + end_time.tv_usec) - start_time.tv_usec); if (usec > 0) usleep(usec); // Wait for next interval refresh_drawing(); } uninitialize_drawing(); } <commit_msg>Consistent handling of (de)initialization<commit_after>/************************************\ * Copyright (C) 2007 by Sarten-X * \************************************/ #include "config.h" // This is generated in build/config.h from <src>/config.h.in by cmake #include "disconet.h" #include "drawing.h" #include <iostream> #include <sstream> #include <sys/time.h> #include <unistd.h> void loop (runtime_options options); int main(int argc, char* argv[]) { runtime_options options; // Otherwise, remember the chosen interface. options.interface = ""; options.profile = false; options.xscale = 1; options.yscale = 1; // TODO: Reimplement a help message // If a dumb number of parameters was supplied, print the usage message and exit. //if(!(argc == 2 || argc == 4)) { // std::cerr << "Usage: " << argv[0] << " <interface> [xscale yscale]" << std::endl; // return 1; //} int option; opterr = 0; while ((option = getopt (argc, argv, "h:w:i:p")) != -1) switch (option) { case 'h': options.yscale = atof(optarg); case 'w': options.xscale = atof(optarg); case 'i': options.interface = optarg; case 'p': options.profile = true; } if (options.interface == "") { options.interface = argv[optind]; } std::cout << "Finding network interface" << std::endl; // Attempt to get network statistics if (get_network_state(options.interface, NULL) != 0) { // Couldn't find the interface, exit "gracefully" std::cerr << "Failed to find interface \"" << options.interface << "\"" << std::endl; return -1; } if (options.profile) { #ifdef HAVE_PCAP std::cout << "Initializing pcap" << std::endl; if (initialize_pcap(options.interface) != 0) { // Couldn't find the interface, exit "gracefully" std::cerr << "Failed to initialize pcap for \"" << options.interface << "\"" << std::endl; return -1; } #else std::cerr << "Not compiled with libpcap support. Profiling not available." << std::endl; return -1; #endif // HAVE_PCAP } std::cout << "Initializing ncurses" << std::endl; initialize_drawing(); // All configuration is done. std::cout << "Starting monitoring" << std::endl; loop(options); std::cout << "Cleaning up" << std::endl; uninitialize_drawing(); return 0; } void loop (runtime_options options) { int h, w; timeval start_time, end_time; // Declare space for the number of tiles and storing old traffic calculation. long long number = -1; unsigned long long oldtraffic = 0; // Declare placeholders for all the fields in /proc/net/dev. I wallow in wasted RAM. net_state current, old; // Start main loop. This should have some kind of exit. while (1) { gettimeofday(&start_time, NULL); // Save a copy of old data, for calculating change. old = current; if (options.profile) { #ifdef HAVE_PCAP if(get_pcap_network_state(&current) != 0) break; #endif // HAVE_PCAP } else { if(get_network_state(options.interface, &current) != 0) break; } // Begin calculations //std::cout << current.rcvbytes << " " << current.rcvpackets << " " << current.xmtbytes << " " << current.xmtpackets << "\r" << std::endl; paint_drawing(current, options.xscale, options.yscale); gettimeofday(&end_time, NULL); long int usec = REFRESH_TIME - (((end_time.tv_sec - start_time.tv_sec) * 1000000 + end_time.tv_usec) - start_time.tv_usec); if (usec > 0) usleep(usec); // Wait for next interval refresh_drawing(); } } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch.hpp" #include <memory> #include <sstream> #include "Event.hpp" #include "TimeWarpEventDispatcher.hpp" #include "TimeWarpEventSet.hpp" #include "mocks.hpp" TEST_CASE("Test the event set operations") { unsigned int num_objects = 4, num_schedulers = 1, num_threads = 1; warped::TimeWarpEventSet twes; twes.initialize(num_objects, num_schedulers, num_threads); std::shared_ptr<warped::Event> spe; REQUIRE(twes.getEvent(0) == nullptr); SECTION("Insert event (+ve, -ve), get event and start scheduling events") { twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 15})); twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 10})); twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 11})); twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 10, false})); twes. startScheduling(0); twes.insertEvent(1, std::shared_ptr<warped::Event>(new test_Event {"b", 9})); twes. startScheduling(1); twes.insertEvent(1, std::shared_ptr<warped::Event>(new test_Event {"b", 9, false})); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "b"); CHECK(spe->timestamp() == 9); CHECK(spe->event_type_ == warped::EventType::POSITIVE); twes.replenishScheduler(1, spe); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "b"); CHECK(spe->timestamp() == 9); CHECK(spe->event_type_ == warped::EventType::NEGATIVE); twes.rollback(1, 9); auto list_obj1 = twes.getEventsForCoastForward(1); CHECK(list_obj1->size() == 1); CHECK((*list_obj1)[0]->timestamp() == 9); CHECK((*list_obj1)[0]->event_type_ == warped::EventType::POSITIVE); twes.startScheduling(1); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "a"); CHECK(spe->timestamp() == 11); twes.replenishScheduler(0, spe); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "a"); CHECK(spe->timestamp() == 15); twes.replenishScheduler(0, spe); spe = twes.getEvent(0); REQUIRE(spe == nullptr); twes.rollback(0, 10); auto list_obj0 = twes.getEventsForCoastForward(0); CHECK(list_obj0->size() == 2); CHECK((*list_obj0)[0]->timestamp() == 11); CHECK((*list_obj0)[1]->timestamp() == 15); } } <commit_msg>modified the event set unit tests to test some weird scenarios.<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch.hpp" #include <memory> #include <sstream> #include "Event.hpp" #include "TimeWarpEventDispatcher.hpp" #include "TimeWarpEventSet.hpp" #include "mocks.hpp" TEST_CASE("Test the event set operations") { unsigned int num_objects = 4, num_schedulers = 1, num_threads = 1; warped::TimeWarpEventSet twes; twes.initialize(num_objects, num_schedulers, num_threads); std::shared_ptr<warped::Event> spe; REQUIRE(twes.getEvent(0) == nullptr); SECTION("Insert event (+ve, -ve), get event and start scheduling events") { twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 15})); twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 10})); twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 9})); twes.insertEvent(0, std::shared_ptr<warped::Event>(new test_Event {"a", 10, false})); twes. startScheduling(0); twes.insertEvent(1, std::shared_ptr<warped::Event>(new test_Event {"b", 9})); twes. startScheduling(1); twes.insertEvent(1, std::shared_ptr<warped::Event>(new test_Event {"b", 9, false})); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "a"); CHECK(spe->timestamp() == 9); CHECK(spe->event_type_ == warped::EventType::POSITIVE); twes.replenishScheduler(0, spe); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "b"); CHECK(spe->timestamp() == 9); CHECK(spe->event_type_ == warped::EventType::POSITIVE); twes.replenishScheduler(1, spe); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "b"); CHECK(spe->timestamp() == 9); CHECK(spe->event_type_ == warped::EventType::NEGATIVE); twes.rollback(1, 9); auto list_obj1 = twes.getEventsForCoastForward(1); CHECK(list_obj1->size() == 1); CHECK((*list_obj1)[0]->timestamp() == 9); CHECK((*list_obj1)[0]->event_type_ == warped::EventType::POSITIVE); twes.startScheduling(1); spe = twes.getEvent(0); REQUIRE(spe == nullptr); twes.replenishScheduler(0, spe); spe = twes.getEvent(0); REQUIRE(spe != nullptr); CHECK(spe->receiverName() == "a"); CHECK(spe->timestamp() == 15); twes.replenishScheduler(0, spe); spe = twes.getEvent(0); REQUIRE(spe == nullptr); twes.rollback(0, 10); auto list_obj0 = twes.getEventsForCoastForward(0); CHECK(list_obj0->size() == 2); CHECK((*list_obj0)[0]->timestamp() == 11); CHECK((*list_obj0)[1]->timestamp() == 15); } } <|endoftext|>
<commit_before>#include <Halide.h> using namespace Halide; #include "../png.h" #define PI 3.14159 Func gradientMagnitude(Func f, Expr width, Expr height) { Var x, y, c, a, b; Expr isTop = y <= 10; Expr isBottom = y >= height - 10; Expr isLeft = x <= 10; Expr isRight = x >= width - 10; Func dI2("dI2"); dI2(x, y, a, b) = pow(f(x, y, 0) - f(x+a, y+b, 0), 2) + pow(f(x, y, 1) - f(x+a, y+b, 1), 2) + pow(f(x, y, 1) - f(x+a, y+b, 1), 2); Func dI("dI"); dI(x, y, a, b) = sqrt(dI2(x, y, a, b)); Func gradient2D("gradient2D"); gradient2D(x, y) = select(isTop, 0.0f, 1.0f)*dI(x, y, 0, -1) + select(isBottom, 0.0f, 1.0f)*dI(x, y, 0, 1) + select(isLeft, 0.0f, 1.0f)*dI(x, y, -1, 0) + select(isRight, 0.0f, 1.0f)*dI(x, y, 1, 0); Func norm("norm"); norm(x, y) = select(isTop, 0.0f, 1.0f) + select(isBottom, 0.0f, 1.0f) + select(isLeft, 0.0f, 1.0f) + select(isRight, 0.0f, 1.0f); Func gradient("gradient"); gradient(x, y, c) = gradient2D(x, y)/norm(x, y); return gradient; } int main(int argc, char **argv) { // Uniform<int> k; UniformImage input(UInt(16), 3); Var x("x"), y("y"), c("c"), xo("blockidx"), yo("blockidy"), xi("threadidx"), yi("threadidy"); // The algorithm Func clampH("clampH"); clampH(y) = clamp(y, 0, input.height() - 1); Func clampW("clampW"); clampW(x) = clamp(x, 0, input.width() - 1); // Convert to floating point Func floating("floating"); floating(x, y, c) = cast<float>(input(x, y, c)) / 65535.0f; // Set a boundary condition Func clamped("clamped"); clamped(x, y, c) = floating(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c); Func g; g = gradientMagnitude(clamped, input.width(), input.height()); RDom yr(0, input.height()); Func energy("energy"); energy(x, y, c) = g(x, y, c); energy(x, yr, c) = g(x, yr, c) + min(min(energy(x, yr - 1, c), energy(clampW(x - 1), yr - 1, c)), energy(clampW(x + 1), yr - 1, c)); // important for correctness that we calculate row by row energy.update().transpose(yr, x); RDom xr(1, input.width() - 1); Func minEnergy("minEnergy"); minEnergy(y) = 0; minEnergy(y) = select(energy(xr, y, 0) < energy(clampW(minEnergy(y)), y, 0), xr, minEnergy(y)); // serves as reduction that goes from input.height() - 1 to 0 Expr flipY = input.height() - yr - 1; // calculate location of seam Func seam("seam"); seam(y) = minEnergy(y); seam(flipY - 1) = select(select( energy( clampW(seam(flipY) - 1), flipY - 1, 0) < energy( clampW(seam(flipY) + 1), flipY - 1, 0), energy( clampW(seam(flipY) - 1), flipY - 1, 0), energy( clampW(seam(flipY) + 1), flipY - 1, 0) ) < energy( clampW(seam(flipY)), flipY - 1, 0), select( energy( clampW(seam(flipY) - 1), flipY - 1, 0) < energy( clampW(seam(flipY) + 1), flipY - 1, 0), clampW(seam(flipY) - 1), clampW(seam(flipY) + 1) ), clampW(seam(flipY)) ); // remove seam Func output("output"); output(x, y, c) = clamped(x, y, c); output(x, yr, c) = select(x < seam(yr), clamped(x, yr, c), select(x + 1 < input.width(), clamped(x + 1, yr, c), select( yr%2==0, 0.0f, 1.0f ))); // draws seam Func seams("seams"); seams(x, y, c) = clamped(x, y, c); seams(x, yr, c) = select(x==seam(yr), select(c==0, 1.0f, 0.0f), clamped(x,yr,c)); // Convert back to 16-bit Func outputClamped("outputClamped"); outputClamped(x, y, c) = cast<uint16_t>(output(x, y, c) * 65535.0f); // schedule outputClamped.compileToFile("seam_carving"); return 0; } <commit_msg>Fixed transpose call in seam_carving<commit_after>#include <Halide.h> using namespace Halide; #include "../png.h" #define PI 3.14159 Func gradientMagnitude(Func f, Expr width, Expr height) { Var x, y, c, a, b; Expr isTop = y <= 10; Expr isBottom = y >= height - 10; Expr isLeft = x <= 10; Expr isRight = x >= width - 10; Func dI2("dI2"); dI2(x, y, a, b) = pow(f(x, y, 0) - f(x+a, y+b, 0), 2) + pow(f(x, y, 1) - f(x+a, y+b, 1), 2) + pow(f(x, y, 1) - f(x+a, y+b, 1), 2); Func dI("dI"); dI(x, y, a, b) = sqrt(dI2(x, y, a, b)); Func gradient2D("gradient2D"); gradient2D(x, y) = select(isTop, 0.0f, 1.0f)*dI(x, y, 0, -1) + select(isBottom, 0.0f, 1.0f)*dI(x, y, 0, 1) + select(isLeft, 0.0f, 1.0f)*dI(x, y, -1, 0) + select(isRight, 0.0f, 1.0f)*dI(x, y, 1, 0); Func norm("norm"); norm(x, y) = select(isTop, 0.0f, 1.0f) + select(isBottom, 0.0f, 1.0f) + select(isLeft, 0.0f, 1.0f) + select(isRight, 0.0f, 1.0f); Func gradient("gradient"); gradient(x, y, c) = gradient2D(x, y)/norm(x, y); return gradient; } int main(int argc, char **argv) { // Uniform<int> k; UniformImage input(UInt(16), 3); Var x("x"), y("y"), c("c"), xo("blockidx"), yo("blockidy"), xi("threadidx"), yi("threadidy"); // The algorithm Func clampH("clampH"); clampH(y) = clamp(y, 0, input.height() - 1); Func clampW("clampW"); clampW(x) = clamp(x, 0, input.width() - 1); // Convert to floating point Func floating("floating"); floating(x, y, c) = cast<float>(input(x, y, c)) / 65535.0f; // Set a boundary condition Func clamped("clamped"); clamped(x, y, c) = floating(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c); Func g; g = gradientMagnitude(clamped, input.width(), input.height()); RDom yr(0, input.height()); Func energy("energy"); energy(x, y, c) = g(x, y, c); energy(x, yr, c) = g(x, yr, c) + min(min(energy(x, yr - 1, c), energy(clampW(x - 1), yr - 1, c)), energy(clampW(x + 1), yr - 1, c)); RDom xr(1, input.width() - 1); Func minEnergy("minEnergy"); minEnergy(y) = 0; minEnergy(y) = select(energy(xr, y, 0) < energy(clampW(minEnergy(y)), y, 0), xr, minEnergy(y)); // serves as reduction that goes from input.height() - 1 to 0 Expr flipY = input.height() - yr - 1; // calculate location of seam Func seam("seam"); seam(y) = minEnergy(y); seam(flipY - 1) = select(select( energy( clampW(seam(flipY) - 1), flipY - 1, 0) < energy( clampW(seam(flipY) + 1), flipY - 1, 0), energy( clampW(seam(flipY) - 1), flipY - 1, 0), energy( clampW(seam(flipY) + 1), flipY - 1, 0) ) < energy( clampW(seam(flipY)), flipY - 1, 0), select( energy( clampW(seam(flipY) - 1), flipY - 1, 0) < energy( clampW(seam(flipY) + 1), flipY - 1, 0), clampW(seam(flipY) - 1), clampW(seam(flipY) + 1) ), clampW(seam(flipY)) ); // remove seam Func output("output"); output(x, y, c) = clamped(x, y, c); output(x, yr, c) = select(x < seam(yr), clamped(x, yr, c), select(x + 1 < input.width(), clamped(x + 1, yr, c), select( yr%2==0, 0.0f, 1.0f ))); // draws seam Func seams("seams"); seams(x, y, c) = clamped(x, y, c); seams(x, yr, c) = select(x==seam(yr), select(c==0, 1.0f, 0.0f), clamped(x,yr,c)); // Convert back to 16-bit Func outputClamped("outputClamped"); outputClamped(x, y, c) = cast<uint16_t>(output(x, y, c) * 65535.0f); // schedule outputClamped.compileToFile("seam_carving"); return 0; } <|endoftext|>
<commit_before>#ifndef GNR_DISPATCH_HPP # define GNR_DISPATCH_HPP # pragma once #include <type_traits> #include <utility> namespace gnr { namespace detail { template <typename A, typename ...B> struct front { using type = A; }; template <typename ...A> using front_t = typename front<A...>::type; } constexpr decltype(auto) dispatch(auto const i, auto&& ...f) noexcept(noexcept((f(), ...))) requires( std::is_enum_v<std::remove_const_t<decltype(i)>> && std::conjunction_v< std::is_same< std::decay_t< decltype(std::declval<detail::front_t<decltype(f)...>>()()) >, std::decay_t<decltype(std::declval<decltype(f)>()())> >... > ) { using int_t = std::underlying_type_t<std::remove_const_t<decltype(i)>>; using R = decltype(std::declval<detail::front_t<decltype(f)...>>()()); return [&]<auto ...I>(std::integer_sequence<int_t, I...>) noexcept(noexcept((f(), ...))) -> decltype(auto) { if constexpr(std::is_void_v<R>) { ((I == int_t(i) ? (f(), 0) : 0), ...); } else if constexpr(std::is_array_v<std::remove_reference_t<R>>) { std::remove_extent_t<std::remove_reference_t<R>>(*r)[]; ((I == i ? (r = reinterpret_cast<decltype(r)>(&f()), 0) : 0), ...); return *r; } else if constexpr(std::is_reference_v<R>) { std::remove_reference_t<R>* r; ((I == int_t(i) ? (r = &f(), 0) : 0), ...); return *r; } else { R r; ((I == int_t(i) ? (r = f(), 0) : 0), ...); return r; } }(std::make_integer_sequence<int_t, sizeof...(f)>()); } constexpr decltype(auto) select(auto const i, auto&& ...v) noexcept requires( std::is_integral_v<std::remove_const_t<decltype(i)>> && std::conjunction_v< std::is_same< std::decay_t< decltype(std::declval<detail::front_t<decltype(v)...>>()) >, std::decay_t<decltype(std::declval<decltype(v)>())> >... > ) { using R = detail::front_t<decltype(v)...>; return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> decltype(auto) { if constexpr(std::is_array_v<std::remove_reference_t<R>>) { std::remove_extent_t<std::remove_reference_t<R>>(*r)[]; ((I == i ? (r = reinterpret_cast<decltype(r)>(&v), 0) : 0), ...); return *r; } else { std::remove_reference_t<R>* r; ((I == i ? (r = &v, 0) : 0), ...); return *r; } }(std::make_index_sequence<sizeof...(v)>()); } } #endif // GNR_DISPATCH_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_DISPATCH_HPP # define GNR_DISPATCH_HPP # pragma once #include <type_traits> #include <utility> namespace gnr { namespace detail { template <typename A, typename ...B> struct front { using type = A; }; template <typename ...A> using front_t = typename front<A...>::type; } constexpr decltype(auto) dispatch(auto const i, auto&& ...f) noexcept(noexcept((f(), ...))) requires( std::is_enum_v<std::remove_const_t<decltype(i)>> && std::conjunction_v< std::is_same< std::decay_t< decltype(std::declval<detail::front_t<decltype(f)...>>()()) >, std::decay_t<decltype(std::declval<decltype(f)>()())> >... > ) { using int_t = std::underlying_type_t<std::remove_const_t<decltype(i)>>; using R = decltype(std::declval<detail::front_t<decltype(f)...>>()()); return [&]<auto ...I>(std::integer_sequence<int_t, I...>) noexcept(noexcept((f(), ...))) -> decltype(auto) { if constexpr(std::is_void_v<R>) { ((I == int_t(i) ? (f(), 0) : 0), ...); } else if constexpr(std::is_array_v<std::remove_reference_t<R>>) { std::remove_extent_t<std::remove_reference_t<R>>(*r)[]; ( ( I == int_t(i) ? r = reinterpret_cast<decltype(r)>(&f()) : nullptr ), ... ); return *r; } else if constexpr(std::is_reference_v<R>) { std::remove_reference_t<R>* r; ((I == int_t(i) ? r = &f() : nullptr), ...); return *r; } else { R r; ((I == int_t(i) ? (r = f(), 0) : 0), ...); return r; } }(std::make_integer_sequence<int_t, sizeof...(f)>()); } constexpr decltype(auto) select(auto const i, auto&& ...v) noexcept requires( std::is_integral_v<std::remove_const_t<decltype(i)>> && std::conjunction_v< std::is_same< std::decay_t< decltype(std::declval<detail::front_t<decltype(v)...>>()) >, std::decay_t<decltype(std::declval<decltype(v)>())> >... > ) { using R = detail::front_t<decltype(v)...>; return [&]<auto ...I>(std::index_sequence<I...>) noexcept -> decltype(auto) { if constexpr(std::is_array_v<std::remove_reference_t<R>>) { std::remove_extent_t<std::remove_reference_t<R>>(*r)[]; ((I == i ? r = reinterpret_cast<decltype(r)>(&v) : nullptr), ...); return *r; } else { std::remove_reference_t<R>* r; ((I == i ? r = &v : nullptr), ...); return *r; } }(std::make_index_sequence<sizeof...(v)>()); } } #endif // GNR_DISPATCH_HPP <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <iostream> #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/common/password_form.h" namespace autofill { PasswordForm::PasswordForm() : scheme(SCHEME_HTML), password_autocomplete_set(true), ssl_valid(false), preferred(false), blacklisted_by_user(false), type(TYPE_MANUAL), times_used(0) { } PasswordForm::~PasswordForm() { } bool PasswordForm::IsPublicSuffixMatch() const { return !original_signon_realm.empty(); } bool PasswordForm::operator==(const PasswordForm& form) const { return signon_realm == form.signon_realm && origin == form.origin && action == form.action && submit_element == form.submit_element && username_element == form.username_element && username_value == form.username_value && other_possible_usernames == form.other_possible_usernames && password_element == form.password_element && password_value == form.password_value && password_autocomplete_set == form.password_autocomplete_set && old_password_element == form.old_password_element && old_password_value == form.old_password_value && ssl_valid == form.ssl_valid && preferred == form.preferred && date_created == form.date_created && blacklisted_by_user == form.blacklisted_by_user && type == form.type && times_used == form.times_used && form_data == form.form_data; } bool PasswordForm::operator!=(const PasswordForm& form) const { return !operator==(form); } std::ostream& operator<<(std::ostream& os, const PasswordForm& form) { return os << "scheme: " << form.scheme << " signon_realm: " << form.signon_realm << " origin: " << form.origin << " action: " << form.action << " submit_element: " << UTF16ToUTF8(form.submit_element) << " username_elem: " << UTF16ToUTF8(form.username_element) << " username_value: " << UTF16ToUTF8(form.username_value) << " password_elem: " << UTF16ToUTF8(form.password_element) << " password_value: " << UTF16ToUTF8(form.password_value) << " old_password_element: " << UTF16ToUTF8(form.old_password_element) << " old_password_value: " << UTF16ToUTF8(form.old_password_value) << " autocomplete_set:" << form.password_autocomplete_set << " blacklisted: " << form.blacklisted_by_user << " preferred: " << form.preferred << " ssl_valid: " << form.ssl_valid << " date_created: " << form.date_created.ToDoubleT() << " type: " << form.type << " times_used: " << form.times_used << " form_data: " << form.form_data; } } // namespace autofill <commit_msg>Fix a static initializer regression.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <ostream> #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/common/password_form.h" namespace autofill { PasswordForm::PasswordForm() : scheme(SCHEME_HTML), password_autocomplete_set(true), ssl_valid(false), preferred(false), blacklisted_by_user(false), type(TYPE_MANUAL), times_used(0) { } PasswordForm::~PasswordForm() { } bool PasswordForm::IsPublicSuffixMatch() const { return !original_signon_realm.empty(); } bool PasswordForm::operator==(const PasswordForm& form) const { return signon_realm == form.signon_realm && origin == form.origin && action == form.action && submit_element == form.submit_element && username_element == form.username_element && username_value == form.username_value && other_possible_usernames == form.other_possible_usernames && password_element == form.password_element && password_value == form.password_value && password_autocomplete_set == form.password_autocomplete_set && old_password_element == form.old_password_element && old_password_value == form.old_password_value && ssl_valid == form.ssl_valid && preferred == form.preferred && date_created == form.date_created && blacklisted_by_user == form.blacklisted_by_user && type == form.type && times_used == form.times_used && form_data == form.form_data; } bool PasswordForm::operator!=(const PasswordForm& form) const { return !operator==(form); } std::ostream& operator<<(std::ostream& os, const PasswordForm& form) { return os << "scheme: " << form.scheme << " signon_realm: " << form.signon_realm << " origin: " << form.origin << " action: " << form.action << " submit_element: " << UTF16ToUTF8(form.submit_element) << " username_elem: " << UTF16ToUTF8(form.username_element) << " username_value: " << UTF16ToUTF8(form.username_value) << " password_elem: " << UTF16ToUTF8(form.password_element) << " password_value: " << UTF16ToUTF8(form.password_value) << " old_password_element: " << UTF16ToUTF8(form.old_password_element) << " old_password_value: " << UTF16ToUTF8(form.old_password_value) << " autocomplete_set:" << form.password_autocomplete_set << " blacklisted: " << form.blacklisted_by_user << " preferred: " << form.preferred << " ssl_valid: " << form.ssl_valid << " date_created: " << form.date_created.ToDoubleT() << " type: " << form.type << " times_used: " << form.times_used << " form_data: " << form.form_data; } } // namespace autofill <|endoftext|>
<commit_before>#include "World.h" #include "SensoryInput.h" #include <iostream> #include <algorithm> #include <list> // Must be defined in the header if they are used there. //const int World::width = 30; //const int World::height = 20; //const int World::initialPopulationSize = 30; World::World(){ buildCage(20, upLeft); buildCage(40, upRight); buildCage(60, right); buildCage(80, downRight); buildWalls(); sprinklePlants(3000); regeneratePopulation(); image.Create(width*2+1, height*2); } World::~World(){ for(std::list<Pet *>::iterator i=pets.begin(); i != pets.end(); ++i){ delete *i; } for(std::list<Pet *>::iterator i=petArchive.begin(); i != petArchive.end(); ++i){ delete *i; } } int World::coordinateToIndex(int x, int y){ return y*width + x; } int World::movePosition(int position, Direction direction){ int x = position % width; int y = position / width; // Odd rows are indented half a hexagon. switch (direction) { case left: --x; break; case downLeft: if (! (y % 2)) --x; ++y; break; case upLeft: if (! (y % 2)) --x; --y; break; case right: ++x; break; case upRight: if (y % 2) ++x; --y; break; case downRight: if (y % 2) ++x; ++y; break; default: break; } x = (x + width) % width; y = (y + height) % height; return coordinateToIndex(x, y); } Direction World::offsetDirectionByRelativeDirection(Direction direction, RelativeDirection relativeDirection){ return static_cast<Direction>( (static_cast<int>(direction) + static_cast<int>(numDirections) + static_cast<int>(relativeDirection)) % static_cast<int>(numDirections) ); } void World::buildCage(int sideLength, Direction openingDirection){ // Draw a "cage" of walls with one side open. // Begin in the center. int position = coordinateToIndex(width/2, height/2); // Move to starting position for(int i=0; i<sideLength; ++i){ position = movePosition(position, openingDirection); } cells[position].impassable = true; // Draw a semi circle. (5 sides of 6.) Direction direction = offsetDirectionByRelativeDirection(openingDirection, backwardLeft); for(int j=0; j<5; ++j){ // Draw one side. for(int i=0; i<sideLength; ++i){ // Take a step. position = movePosition(position, direction); // Place wall. cells[position].impassable = true; } // Turn. direction = offsetDirectionByRelativeDirection(direction, forwardLeft); } } void World::buildWalls(){ // Place walls along the sides of the world. // Place wall. for(int x=0; x<width; ++x){ cells[x].impassable = true; cells[x + width*(height-1)].impassable = true; } for(int y=0; y<height; ++y){ cells[y*width].impassable = true; cells[y*width + (width-1)].impassable = true; } } void World::regeneratePopulation(){ // Remove any remaining Pet. while(pets.size()){ removePet(pets.back()); } // Use archived pets for only half of ththe population, to weed out the bad ones. int maxNumPetsToReuse = initialPopulationSize / 2; if (petArchive.size() > maxNumPetsToReuse) { petArchive.resize(maxNumPetsToReuse); } // Generate Pets to fill up the initialPopulationSize. for(int i=0; i<initialPopulationSize && i<width*height; ++i){ Pet *pet = 0; // Reuse the recently died Pets. if (!petArchive.empty()) { pet = petArchive.back(); petArchive.pop_back(); } // Create new ones if the archive is not large enough. if (!pet) { pet = new Pet(); } if (0 > addPetAndPlaceRandomly(pet, PetState(0, static_cast<Direction>(rand() % numDirections), 1))) { // Stop if no more pets can fit. break; } } // Try not to introduce bias by the order in which Pets are processed. std::vector<Pet *> v(pets.begin(), pets.end()); random_shuffle(v.begin(), v.end()); pets = std::list<Pet *>(v.begin(), v.end()); } void World::sprinklePlants(int numPlants){ for(int i=0; i<numPlants; ++i){ int position = rand() % (width*height); WorldCell &cell = cells[position]; cell.plantGrowth = 0.005; cell.plantEnergy = cell.plantMaxEnergy; } } void World::render(sf::RenderWindow &window){ for(int y=0; y < height; ++y){ // Indent odd lines to line up hexagonally. int indentation = y % 2 ? 1: 0; for(int x=0; x < width; ++x){ // Get the relevant cell. WorldCell &cell = cells[coordinateToIndex(x, y)]; // Find a suitable color. sf::Color color = sf::Color::Black; if (cell.pet) { color = cell.pet->color; } else { if (cell.impassable) { color = sf::Color::White; } else { if (cell.plantEnergy > 0) { color = sf::Color(0, 255 * cell.plantEnergy, 0); } } } // Plot the cell. image.SetPixel(indentation + x*2 + 1, y*2 , color); image.SetPixel(indentation + x*2 , y*2 , color); image.SetPixel(indentation + x*2 + 1, y*2 + 1, color); image.SetPixel(indentation + x*2 , y*2 + 1, color); } } window.Draw(sf::Sprite(image)); } bool World::step(){ // Update Pets. std::list<Pet *>::iterator i = pets.begin(); while (i != pets.end()) { Pet *pet = *i; // Advance i before applayPetIntention, so the loop won't crash when a Pet is erased. i++; applyPetIntentionToPet(pet, pet->getPetIntentionForSensoryInput(SensoryInput(this, pet))); } // Update WorldCells. for (int i=0; i<width*height; ++i) { WorldCell &cell = cells[i]; // Plant growth. cell.plantEnergy = std::min(cell.plantEnergy + cell.plantGrowth, cell.plantMaxEnergy); } // Is is the world still populated? return pets.size() > 1; } void World::applyPetIntentionToPet(Pet *pet, PetIntention petIntention){ PetState &currentState = petStates[pet]; PetState newState = currentState; // Eat plants. newState.energy += cells[currentState.position].plantEnergy; cells[currentState.position].plantEnergy = 0; // Clamp the Pet's energy. newState.energy = std::min(newState.energy, PetState::maxEnergy); Direction oldDirection = currentState.direction; Direction newDirection = offsetDirectionByRelativeDirection(oldDirection, petIntention.relativeDirection); // Calculate the target position. int newPosition = movePosition(currentState.position, newDirection); // Does the Pet want to mate, and is it possible? if ((petIntention.action & mate) && cells[newPosition].pet && newState.energy > PetState::breedEnergy) { // Mate for (Direction direction = firstDirection; direction < numDirections; ++direction) { int neighbourPosition = movePosition(currentState.position, direction); WorldCell &cell = cells[neighbourPosition]; if (!cell.pet && !cell.impassable) { Pet *child = new Pet(*pet, *(cells[newPosition].pet)); addPet(child, PetState(neighbourPosition, direction, PetState::breedEnergy / 6)); } } newState.energy -= PetState::breedEnergy; } else { // Does the Pet want to battle, and is it possible? if ((petIntention.action & battle) && cells[newPosition].pet) { PetState &opponentState = petStates[cells[newPosition].pet]; // If the Pet is stronger than the opponent, eat it. if (currentState.energy > opponentState.energy) { newState.energy -= PetState::battleEnergy; if (newState.isAlive()) { newState.energy += opponentState.energy; opponentState.energy = 0; // removePet(cells[newPosition].pet); newState.energy = std::min(newState.energy, PetState::maxEnergy); } } // Actually move. newState.direction = newDirection; newState.position = newPosition; cells[currentState.position].pet = 0; cells[newState.position].pet = pet; // Moving consumes some energy. } // Does the Pet want to move, and is it possible? if ((petIntention.action & move) && !cells[newPosition].impassable && !cells[newPosition].pet) { // Actually move. newState.direction = newDirection; newState.position = newPosition; cells[currentState.position].pet = 0; cells[newState.position].pet = pet; // Moving consumes some energy. newState.energy -= PetState::moveEnergy; } } // Just staying alive takes energy. newState.energy -= PetState::liveEnergy; // Age the pet. ++newState.age; petStates[pet] = newState; // Handle death. if (!newState.isAlive()) { // For now, dying Pets just disappear. removePet(pet); } } int World::addPetAndPlaceRandomly(Pet *newPet, PetState newState) { // Walk over the list until a living Pet is found, max one lap. int worldSize = width * height; int randomStartPosition = rand() % worldSize; for (int i = 0; i < worldSize; ++i) { int currentPosition = (randomStartPosition + i) % worldSize; // Try to place it here. newState.position = currentPosition; if (addPet(newPet, newState)) { return currentPosition; } } // No valid position was found, so return an invalid position. return -1; } bool World::addPet(Pet *newPet, PetState const &newState) { // Refuse to add Pets at any position already occupied by a Pet. if (cells[newState.position].pet) { return false; } // Refuse to add Pets at walls. if (cells[newState.position].impassable) { return false; } cells[newState.position].pet = newPet; pets.push_front(newPet); // push_front is OK, but not push_back, since the list "pets" is being itterated over while this function is called. petStates[newPet] = newState; return true; } void World::removePet(Pet *pet) { cells[petStates[pet].position].pet = 0; pets.remove(pet); petStates.erase(pet); petArchive.push_back(pet); } <commit_msg>Fixed pet archive memory 'leak'.<commit_after>#include "World.h" #include "SensoryInput.h" #include <iostream> #include <algorithm> #include <list> // Must be defined in the header if they are used there. //const int World::width = 30; //const int World::height = 20; //const int World::initialPopulationSize = 30; World::World(){ buildCage(20, upLeft); buildCage(35, downRight); buildCage(50, upLeft); buildCage(65, downRight); buildCage(80, upLeft); buildCage(95, downRight); buildWalls(); sprinklePlants(3000); regeneratePopulation(); image.Create(width*2+1, height*2); } World::~World(){ for(std::list<Pet *>::iterator i=pets.begin(); i != pets.end(); ++i){ delete *i; } for(std::list<Pet *>::iterator i=petArchive.begin(); i != petArchive.end(); ++i){ delete *i; } } int World::coordinateToIndex(int x, int y){ return y*width + x; } int World::movePosition(int position, Direction direction){ int x = position % width; int y = position / width; // Odd rows are indented half a hexagon. switch (direction) { case left: --x; break; case downLeft: if (! (y % 2)) --x; ++y; break; case upLeft: if (! (y % 2)) --x; --y; break; case right: ++x; break; case upRight: if (y % 2) ++x; --y; break; case downRight: if (y % 2) ++x; ++y; break; default: break; } x = (x + width) % width; y = (y + height) % height; return coordinateToIndex(x, y); } Direction World::offsetDirectionByRelativeDirection(Direction direction, RelativeDirection relativeDirection){ return static_cast<Direction>( (static_cast<int>(direction) + static_cast<int>(numDirections) + static_cast<int>(relativeDirection)) % static_cast<int>(numDirections) ); } void World::buildCage(int sideLength, Direction openingDirection){ // Draw a "cage" of walls with one side open. // Begin in the center. int position = coordinateToIndex(width/2, height/2); // Move to starting position for(int i=0; i<sideLength; ++i){ position = movePosition(position, openingDirection); } cells[position].impassable = true; // Draw a semi circle. (5 sides of 6.) Direction direction = offsetDirectionByRelativeDirection(openingDirection, backwardLeft); for(int j=0; j<5; ++j){ // Draw one side. for(int i=0; i<sideLength; ++i){ // Take a step. position = movePosition(position, direction); // Place wall. cells[position].impassable = true; } // Turn. direction = offsetDirectionByRelativeDirection(direction, forwardLeft); } } void World::buildWalls(){ // Place walls along the sides of the world. // Place wall. for(int x=0; x<width; ++x){ cells[x].impassable = true; cells[x + width*(height-1)].impassable = true; } for(int y=0; y<height; ++y){ cells[y*width].impassable = true; cells[y*width + (width-1)].impassable = true; } } void World::regeneratePopulation(){ // Remove any remaining Pet. while(pets.size()){ removePet(pets.back()); } // Use archived pets for only half of ththe population, to weed out the bad ones. int maxNumPetsToReuse = initialPopulationSize / 2; if (petArchive.size() > maxNumPetsToReuse) { petArchive.resize(maxNumPetsToReuse); } // Generate Pets to fill up the initialPopulationSize. for(int i=0; i<initialPopulationSize && i<width*height; ++i){ Pet *pet = 0; // Reuse the recently died Pets. if (!petArchive.empty()) { pet = petArchive.back(); petArchive.pop_back(); } // Create new ones if the archive is not large enough. if (!pet) { pet = new Pet(); } if (0 > addPetAndPlaceRandomly(pet, PetState(0, static_cast<Direction>(rand() % numDirections), 1))) { // Stop if no more pets can fit. break; } } // Try not to introduce bias by the order in which Pets are processed. std::vector<Pet *> v(pets.begin(), pets.end()); random_shuffle(v.begin(), v.end()); pets = std::list<Pet *>(v.begin(), v.end()); } void World::sprinklePlants(int numPlants){ for(int i=0; i<numPlants; ++i){ int position = rand() % (width*height); WorldCell &cell = cells[position]; cell.plantGrowth = 0.005; cell.plantEnergy = cell.plantMaxEnergy; } } void World::render(sf::RenderWindow &window){ for(int y=0; y < height; ++y){ // Indent odd lines to line up hexagonally. int indentation = y % 2 ? 1: 0; for(int x=0; x < width; ++x){ // Get the relevant cell. WorldCell &cell = cells[coordinateToIndex(x, y)]; // Find a suitable color. sf::Color color = sf::Color::Black; if (cell.pet) { color = cell.pet->color; } else { if (cell.impassable) { color = sf::Color::White; } else { if (cell.plantEnergy > 0) { color = sf::Color(0, 255 * cell.plantEnergy, 0); } } } // Plot the cell. image.SetPixel(indentation + x*2 + 1, y*2 , color); image.SetPixel(indentation + x*2 , y*2 , color); image.SetPixel(indentation + x*2 + 1, y*2 + 1, color); image.SetPixel(indentation + x*2 , y*2 + 1, color); } } window.Draw(sf::Sprite(image)); } bool World::step(){ // Update Pets. std::list<Pet *>::iterator i = pets.begin(); while (i != pets.end()) { Pet *pet = *i; // Advance i before applayPetIntention, so the loop won't crash when a Pet is erased. i++; applyPetIntentionToPet(pet, pet->getPetIntentionForSensoryInput(SensoryInput(this, pet))); } // Update WorldCells. for (int i=0; i<width*height; ++i) { WorldCell &cell = cells[i]; // Plant growth. cell.plantEnergy = std::min(cell.plantEnergy + cell.plantGrowth, cell.plantMaxEnergy); } // Is is the world still populated? return pets.size() > 1; } void World::applyPetIntentionToPet(Pet *pet, PetIntention petIntention){ PetState &currentState = petStates[pet]; PetState newState = currentState; // Eat plants. newState.energy += cells[currentState.position].plantEnergy; cells[currentState.position].plantEnergy = 0; // Clamp the Pet's energy. newState.energy = std::min(newState.energy, PetState::maxEnergy); Direction oldDirection = currentState.direction; Direction newDirection = offsetDirectionByRelativeDirection(oldDirection, petIntention.relativeDirection); // Calculate the target position. int newPosition = movePosition(currentState.position, newDirection); // Does the Pet want to mate, and is it possible? if ((petIntention.action & mate) && cells[newPosition].pet && newState.energy > PetState::breedEnergy) { // Mate for (Direction direction = firstDirection; direction < numDirections; ++direction) { int neighbourPosition = movePosition(currentState.position, direction); WorldCell &cell = cells[neighbourPosition]; if (!cell.pet && !cell.impassable) { Pet *child = new Pet(*pet, *(cells[newPosition].pet)); addPet(child, PetState(neighbourPosition, direction, PetState::breedEnergy / 6)); } } newState.energy -= PetState::breedEnergy; } else { // Does the Pet want to battle, and is it possible? if ((petIntention.action & battle) && cells[newPosition].pet) { PetState &opponentState = petStates[cells[newPosition].pet]; // If the Pet is stronger than the opponent, eat it. if (currentState.energy > opponentState.energy) { newState.energy -= PetState::battleEnergy; if (newState.isAlive()) { newState.energy += opponentState.energy; opponentState.energy = 0; // removePet(cells[newPosition].pet); newState.energy = std::min(newState.energy, PetState::maxEnergy); } } // Actually move. newState.direction = newDirection; newState.position = newPosition; cells[currentState.position].pet = 0; cells[newState.position].pet = pet; // Moving consumes some energy. } // Does the Pet want to move, and is it possible? if ((petIntention.action & move) && !cells[newPosition].impassable && !cells[newPosition].pet) { // Actually move. newState.direction = newDirection; newState.position = newPosition; cells[currentState.position].pet = 0; cells[newState.position].pet = pet; // Moving consumes some energy. newState.energy -= PetState::moveEnergy; } } // Just staying alive takes energy. newState.energy -= PetState::liveEnergy; // Age the pet. ++newState.age; petStates[pet] = newState; // Handle death. if (!newState.isAlive()) { // For now, dying Pets just disappear. removePet(pet); } } int World::addPetAndPlaceRandomly(Pet *newPet, PetState newState) { // Walk over the list until a living Pet is found, max one lap. int worldSize = width * height; int randomStartPosition = rand() % worldSize; for (int i = 0; i < worldSize; ++i) { int currentPosition = (randomStartPosition + i) % worldSize; // Try to place it here. newState.position = currentPosition; if (addPet(newPet, newState)) { return currentPosition; } } // No valid position was found, so return an invalid position. return -1; } bool World::addPet(Pet *newPet, PetState const &newState) { // Refuse to add Pets at any position already occupied by a Pet. if (cells[newState.position].pet) { return false; } // Refuse to add Pets at walls. if (cells[newState.position].impassable) { return false; } cells[newState.position].pet = newPet; pets.push_front(newPet); // push_front is OK, but not push_back, since the list "pets" is being itterated over while this function is called. petStates[newPet] = newState; return true; } void World::removePet(Pet *pet) { cells[petStates[pet].position].pet = 0; pets.remove(pet); petStates.erase(pet); petArchive.push_back(pet); // Keep the archive from growing larger than needed. while (petArchive.size() > initialPopulationSize / 2) { Pet *pet = petArchive.front(); petArchive.pop_front(); delete pet; } } <|endoftext|>
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/metrics/drive_metrics_provider.h" #include <windows.h> #include <ntddscsi.h> #include <winioctl.h> #include <vector> #include "base/files/file.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/win/windows_version.h" namespace metrics { namespace { // Semi-copy of similarly named struct from ata.h in WinDDK. struct IDENTIFY_DEVICE_DATA { USHORT UnusedWords[217]; USHORT NominalMediaRotationRate; USHORT MoreUnusedWords[38]; }; COMPILE_ASSERT(sizeof(IDENTIFY_DEVICE_DATA) == 512, IdentifyDeviceDataSize); struct AtaRequest { ATA_PASS_THROUGH_EX query; IDENTIFY_DEVICE_DATA result; }; struct PaddedAtaRequest { DWORD bytes_returned; // Intentionally above |request| for alignment. AtaRequest request; private: // Prevents some crashes from bad drivers. http://crbug.com/514822 BYTE kUnusedBadDriverSpace[256]; }; } // namespace // static bool DriveMetricsProvider::HasSeekPenalty(const base::FilePath& path, bool* has_seek_penalty) { std::vector<base::FilePath::StringType> components; path.GetComponents(&components); int flags = base::File::FLAG_OPEN; bool win7_or_higher = base::win::GetVersion() >= base::win::VERSION_WIN7; if (!win7_or_higher) flags |= base::File::FLAG_READ | base::File::FLAG_WRITE; base::File volume(base::FilePath(L"\\\\.\\" + components[0]), flags); if (!volume.IsValid()) return false; if (win7_or_higher) { STORAGE_PROPERTY_QUERY query = {}; query.QueryType = PropertyStandardQuery; query.PropertyId = StorageDeviceSeekPenaltyProperty; DEVICE_SEEK_PENALTY_DESCRIPTOR result; DWORD bytes_returned; BOOL success = DeviceIoControl( volume.GetPlatformFile(), IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), &result, sizeof(result), &bytes_returned, NULL); if (success == FALSE || bytes_returned < sizeof(result)) return false; *has_seek_penalty = result.IncursSeekPenalty != FALSE; } else { PaddedAtaRequest padded = {}; AtaRequest* request = &padded.request; request->query.AtaFlags = ATA_FLAGS_DATA_IN; request->query.CurrentTaskFile[6] = ID_CMD; request->query.DataBufferOffset = sizeof(request->query); request->query.DataTransferLength = sizeof(request->result); request->query.Length = sizeof(request->query); request->query.TimeOutValue = 10; DWORD* bytes_returned = &padded.bytes_returned; BOOL success = DeviceIoControl( volume.GetPlatformFile(), IOCTL_ATA_PASS_THROUGH, request, sizeof(*request), request, sizeof(*request), bytes_returned, NULL); if (success == FALSE || *bytes_returned < sizeof(*request) || request->query.CurrentTaskFile[0]) { return false; } // Detect device driver writes further than request + bad driver space. // http://crbug.com/514822 CHECK_LE(*bytes_returned, sizeof(padded) - sizeof(*bytes_returned)); *has_seek_penalty = request->result.NominalMediaRotationRate != 1; } return true; } } // namespace metrics <commit_msg>Instruct clang to ignore kUnusedBadDriverSpace<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/metrics/drive_metrics_provider.h" #include <windows.h> #include <ntddscsi.h> #include <winioctl.h> #include <vector> #include "base/compiler_specific.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/win/windows_version.h" namespace metrics { namespace { // Semi-copy of similarly named struct from ata.h in WinDDK. struct IDENTIFY_DEVICE_DATA { USHORT UnusedWords[217]; USHORT NominalMediaRotationRate; USHORT MoreUnusedWords[38]; }; COMPILE_ASSERT(sizeof(IDENTIFY_DEVICE_DATA) == 512, IdentifyDeviceDataSize); struct AtaRequest { ATA_PASS_THROUGH_EX query; IDENTIFY_DEVICE_DATA result; }; struct PaddedAtaRequest { DWORD bytes_returned; // Intentionally above |request| for alignment. AtaRequest request; private: // Prevents some crashes from bad drivers. http://crbug.com/514822 BYTE kUnusedBadDriverSpace[256] ALLOW_UNUSED_TYPE; }; } // namespace // static bool DriveMetricsProvider::HasSeekPenalty(const base::FilePath& path, bool* has_seek_penalty) { std::vector<base::FilePath::StringType> components; path.GetComponents(&components); int flags = base::File::FLAG_OPEN; bool win7_or_higher = base::win::GetVersion() >= base::win::VERSION_WIN7; if (!win7_or_higher) flags |= base::File::FLAG_READ | base::File::FLAG_WRITE; base::File volume(base::FilePath(L"\\\\.\\" + components[0]), flags); if (!volume.IsValid()) return false; if (win7_or_higher) { STORAGE_PROPERTY_QUERY query = {}; query.QueryType = PropertyStandardQuery; query.PropertyId = StorageDeviceSeekPenaltyProperty; DEVICE_SEEK_PENALTY_DESCRIPTOR result; DWORD bytes_returned; BOOL success = DeviceIoControl( volume.GetPlatformFile(), IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), &result, sizeof(result), &bytes_returned, NULL); if (success == FALSE || bytes_returned < sizeof(result)) return false; *has_seek_penalty = result.IncursSeekPenalty != FALSE; } else { PaddedAtaRequest padded = {}; AtaRequest* request = &padded.request; request->query.AtaFlags = ATA_FLAGS_DATA_IN; request->query.CurrentTaskFile[6] = ID_CMD; request->query.DataBufferOffset = sizeof(request->query); request->query.DataTransferLength = sizeof(request->result); request->query.Length = sizeof(request->query); request->query.TimeOutValue = 10; DWORD* bytes_returned = &padded.bytes_returned; BOOL success = DeviceIoControl( volume.GetPlatformFile(), IOCTL_ATA_PASS_THROUGH, request, sizeof(*request), request, sizeof(*request), bytes_returned, NULL); if (success == FALSE || *bytes_returned < sizeof(*request) || request->query.CurrentTaskFile[0]) { return false; } // Detect device driver writes further than request + bad driver space. // http://crbug.com/514822 CHECK_LE(*bytes_returned, sizeof(padded) - sizeof(*bytes_returned)); *has_seek_penalty = request->result.NominalMediaRotationRate != 1; } return true; } } // namespace metrics <|endoftext|>
<commit_before>#include "testdirectoryiterator.h" #include "vislib/error.h" #include "vislib/File.h" #include "vislib/Path.h" #include "vislib/Exception.h" #include "vislib/String.h" #include "vislib/StringConverter.h" #include "vislib/DirectoryIterator.h" #include "vislib/Array.h" #include "vislib/Stack.h" #include "testhelper.h" #include "vislib/SystemMessage.h" #include <iostream> #ifdef _WIN32 #include <direct.h> #pragma warning ( disable : 4996 ) #define SNPRINTF _snprintf #define FORMATINT64 "%I64u" #else /* _WIN32 */ #include <sys/stat.h> #include <sys/types.h> #define SNPRINTF snprintf #define FORMATINT64 "%lu" #endif /* _WIN32 */ #define BUF_SIZE 4096 using namespace vislib::sys; using namespace vislib; static void TestDirectoryIteratorA(Array<StringA> dirs, Array<StringA> files) { int i; File f; DirectoryEntry<CharTraitsA> de; char buf[BUF_SIZE]; Stack<StringA> st; try { for (i = 0; i < static_cast<int>(dirs.Count()); i++) { #ifdef _WIN32 _mkdir(dirs[i]); #else /* _WIN32 */ //std::cout << "Making directory " << dirs[i] << std::endl; if (mkdir(dirs[i], S_IXUSR | S_IRUSR | S_IWUSR) != 0) { int e = GetLastError(); std::cout << e << " " << static_cast<const char *>(SystemMessage(e)) << std::endl; } #endif /* _WIN32 */ } for (i = 0; i < static_cast<int>(files.Count()); i++) { f.Open(files[i], File::WRITE_ONLY, File::SHARE_READWRITE, File::CREATE_ONLY); f.Close(); } st.Push(dirs[0]); i = 0; StringA relPath; while (!st.IsEmpty()) { DirectoryIterator<CharTraitsA> di(relPath = st.Pop()); while (di.HasNext()) { i++; de = di.Next(); if (de.Type == DirectoryEntry<CharTraitsA>::DIRECTORY) { st.Push(relPath + Path::SEPARATOR_A + de.Path); } } } SNPRINTF(buf, static_cast<size_t>(BUF_SIZE - 1), "Found all %d entries", static_cast<int>(dirs.Count() - 1 + files.Count())); AssertEqual(buf, static_cast<int>(dirs.Count() - 1 + files.Count()), i); for (i = 0; i < static_cast<int>(files.Count()); i++) { File::Delete(files[i]); } for (i = static_cast<int>(dirs.Count() - 1); i >= 0; i--) { #ifdef _WIN32 _rmdir(dirs[i]); #else /* _WIN32 */ rmdir(dirs[i]); #endif /* _WIN32 */ } } catch (vislib::Exception e) { std::cout << e.GetMsgA() << std::endl; } } static void TestDirectoryIteratorW(Array<StringW> dirs, Array<StringW> files) { int i; File f; DirectoryEntry<CharTraitsW> de; char buf[BUF_SIZE]; Stack<StringW> st; try { for (i = 0; i < static_cast<int>(dirs.Count()); i++) { #ifdef _WIN32 _wmkdir(dirs[i]); #else /* _WIN32 */ //std::cout << "Making directory " << StringA(dirs[i]) << std::endl; if (mkdir(StringA(dirs[i]), S_IXUSR | S_IRUSR | S_IWUSR) != 0) { int e = GetLastError(); std::cout << e << " " << static_cast<const char *>(SystemMessage(e)) << std::endl; } #endif /* _WIN32 */ } for (i = 0; i < static_cast<int>(files.Count()); i++) { f.Open(files[i], File::WRITE_ONLY, File::SHARE_READWRITE, File::CREATE_ONLY); f.Close(); } st.Push(dirs[0]); i = 0; StringW relPath; while (!st.IsEmpty()) { relPath = st.Pop(); DirectoryIterator<CharTraitsW> di(relPath); while (di.HasNext()) { i++; de = di.Next(); if (de.Type == DirectoryEntry<CharTraitsW>::DIRECTORY) { st.Push(relPath + Path::SEPARATOR_W + de.Path); } } } SNPRINTF(buf, static_cast<size_t>(BUF_SIZE - 1), "Found all %d entries", static_cast<int>(dirs.Count() - 1 + files.Count())); AssertEqual(buf, static_cast<int>(dirs.Count() - 1 + files.Count()), i); for (i = 0; i < static_cast<int>(files.Count()); i++) { File::Delete(files[i]); } for (i = static_cast<int>(dirs.Count() - 1); i >= 0; i--) { #ifdef _WIN32 _wrmdir(dirs[i]); #else /* _WIN32 */ rmdir(StringA(dirs[i])); #endif /* _WIN32 */ } } catch (vislib::Exception e) { std::cout << e.GetMsgA() << std::endl; } } void TestDirectoryIterator(void) { Array<StringA> dirs; Array<StringA> files; dirs.Append("level0"); dirs.Append(dirs[0] + Path::SEPARATOR_A + "level1"); dirs.Append(dirs[1] + Path::SEPARATOR_A + "level2"); files.Append(dirs[0] + Path::SEPARATOR_A + "level0.0"); files.Append(dirs[0] + Path::SEPARATOR_A + "level0.1"); files.Append(dirs[2] + Path::SEPARATOR_A + "level2.0"); ::TestDirectoryIteratorA(dirs, files); Array<StringW> wdirs; Array<StringW> wfiles; wdirs.Append(L"berlevel0"); wdirs.Append(wdirs[0] + Path::SEPARATOR_W + L"berlevel1"); wdirs.Append(wdirs[1] + Path::SEPARATOR_W + L"berlevel2"); wfiles.Append(wdirs[0] + Path::SEPARATOR_W + L"berlevel0.0"); wfiles.Append(wdirs[0] + Path::SEPARATOR_W + L"berlevel0.1"); wfiles.Append(wdirs[2] + Path::SEPARATOR_W + L"berlevel2.0"); ::TestDirectoryIteratorW(wdirs, wfiles); } <commit_msg>Changed coding to UTF-8 WITHOUT SIGNATURE (!). Works on gcc 4 now.<commit_after>#include "testdirectoryiterator.h" #include "vislib/error.h" #include "vislib/File.h" #include "vislib/Path.h" #include "vislib/Exception.h" #include "vislib/String.h" #include "vislib/StringConverter.h" #include "vislib/DirectoryIterator.h" #include "vislib/Array.h" #include "vislib/Stack.h" #include "testhelper.h" #include "vislib/SystemMessage.h" #include <iostream> #ifdef _WIN32 #include <direct.h> #pragma warning ( disable : 4996 ) #define SNPRINTF _snprintf #define FORMATINT64 "%I64u" #else /* _WIN32 */ #include <sys/stat.h> #include <sys/types.h> #define SNPRINTF snprintf #define FORMATINT64 "%lu" #endif /* _WIN32 */ #define BUF_SIZE 4096 using namespace vislib::sys; using namespace vislib; static void TestDirectoryIteratorA(Array<StringA> dirs, Array<StringA> files) { int i; File f; DirectoryEntry<CharTraitsA> de; char buf[BUF_SIZE]; Stack<StringA> st; try { for (i = 0; i < static_cast<int>(dirs.Count()); i++) { #ifdef _WIN32 _mkdir(dirs[i]); #else /* _WIN32 */ //std::cout << "Making directory " << dirs[i] << std::endl; if (mkdir(dirs[i], S_IXUSR | S_IRUSR | S_IWUSR) != 0) { int e = GetLastError(); std::cout << e << " " << static_cast<const char *>(SystemMessage(e)) << std::endl; } #endif /* _WIN32 */ } for (i = 0; i < static_cast<int>(files.Count()); i++) { f.Open(files[i], File::WRITE_ONLY, File::SHARE_READWRITE, File::CREATE_ONLY); f.Close(); } st.Push(dirs[0]); i = 0; StringA relPath; while (!st.IsEmpty()) { DirectoryIterator<CharTraitsA> di(relPath = st.Pop()); while (di.HasNext()) { i++; de = di.Next(); if (de.Type == DirectoryEntry<CharTraitsA>::DIRECTORY) { st.Push(relPath + Path::SEPARATOR_A + de.Path); } } } SNPRINTF(buf, static_cast<size_t>(BUF_SIZE - 1), "Found all %d entries", static_cast<int>(dirs.Count() - 1 + files.Count())); AssertEqual(buf, static_cast<int>(dirs.Count() - 1 + files.Count()), i); for (i = 0; i < static_cast<int>(files.Count()); i++) { File::Delete(files[i]); } for (i = static_cast<int>(dirs.Count() - 1); i >= 0; i--) { #ifdef _WIN32 _rmdir(dirs[i]); #else /* _WIN32 */ rmdir(dirs[i]); #endif /* _WIN32 */ } } catch (vislib::Exception e) { std::cout << e.GetMsgA() << std::endl; } } static void TestDirectoryIteratorW(Array<StringW> dirs, Array<StringW> files) { int i; File f; DirectoryEntry<CharTraitsW> de; char buf[BUF_SIZE]; Stack<StringW> st; try { for (i = 0; i < static_cast<int>(dirs.Count()); i++) { #ifdef _WIN32 _wmkdir(dirs[i]); #else /* _WIN32 */ //std::cout << "Making directory " << StringA(dirs[i]) << std::endl; if (mkdir(StringA(dirs[i]), S_IXUSR | S_IRUSR | S_IWUSR) != 0) { int e = GetLastError(); std::cout << e << " " << static_cast<const char *>(SystemMessage(e)) << std::endl; } #endif /* _WIN32 */ } for (i = 0; i < static_cast<int>(files.Count()); i++) { f.Open(files[i], File::WRITE_ONLY, File::SHARE_READWRITE, File::CREATE_ONLY); f.Close(); } st.Push(dirs[0]); i = 0; StringW relPath; while (!st.IsEmpty()) { relPath = st.Pop(); DirectoryIterator<CharTraitsW> di(relPath); while (di.HasNext()) { i++; de = di.Next(); if (de.Type == DirectoryEntry<CharTraitsW>::DIRECTORY) { st.Push(relPath + Path::SEPARATOR_W + de.Path); } } } SNPRINTF(buf, static_cast<size_t>(BUF_SIZE - 1), "Found all %d entries", static_cast<int>(dirs.Count() - 1 + files.Count())); AssertEqual(buf, static_cast<int>(dirs.Count() - 1 + files.Count()), i); for (i = 0; i < static_cast<int>(files.Count()); i++) { File::Delete(files[i]); } for (i = static_cast<int>(dirs.Count() - 1); i >= 0; i--) { #ifdef _WIN32 _wrmdir(dirs[i]); #else /* _WIN32 */ rmdir(StringA(dirs[i])); #endif /* _WIN32 */ } } catch (vislib::Exception e) { std::cout << e.GetMsgA() << std::endl; } } void TestDirectoryIterator(void) { Array<StringA> dirs; Array<StringA> files; dirs.Append("level0"); dirs.Append(dirs[0] + Path::SEPARATOR_A + "level1"); dirs.Append(dirs[1] + Path::SEPARATOR_A + "level2"); files.Append(dirs[0] + Path::SEPARATOR_A + "level0.0"); files.Append(dirs[0] + Path::SEPARATOR_A + "level0.1"); files.Append(dirs[2] + Path::SEPARATOR_A + "level2.0"); ::TestDirectoryIteratorA(dirs, files); Array<StringW> wdirs; Array<StringW> wfiles; wdirs.Append(L"Überlevel0"); wdirs.Append(wdirs[0] + Path::SEPARATOR_W + L"Überlevel1"); wdirs.Append(wdirs[1] + Path::SEPARATOR_W + L"Überlevel2"); wfiles.Append(wdirs[0] + Path::SEPARATOR_W + L"Überlevel0.0"); wfiles.Append(wdirs[0] + Path::SEPARATOR_W + L"Überlevel0.1"); wfiles.Append(wdirs[2] + Path::SEPARATOR_W + L"Überlevel2.0"); ::TestDirectoryIteratorW(wdirs, wfiles); } <|endoftext|>
<commit_before><?hh //partial namespace hhpack\publisher\example; require_once __DIR__ . '/../vendor/autoload.php'; use hhpack\publisher\MessagePublicher; use hhpack\publisher\example\DomainMessage; use hhpack\publisher\example\DomainMessageSubscriber; $publisher = new MessagePublisher(); $publisher->registerSubscriber(new DomainMessageSubscriber()); $publisher->publish(new DomainMessage()); <commit_msg>wrap funcion for type check<commit_after><?hh //partial namespace hhpack\publisher\example; require_once __DIR__ . '/../vendor/autoload.php'; use hhpack\publisher\MessagePublicher; use hhpack\publisher\example\DomainMessage; use hhpack\publisher\example\DomainMessageSubscriber; function publisher_main() : void { $publisher = new MessagePublisher(); $publisher->registerSubscriber(new DomainMessageSubscriber()); $publisher->publish(new DomainMessage()); } publisher_main(); <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TPrivilegesResultSet.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 06:39:42 $ * * 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 CONNECTIVITY_PRIVILEGESRESULTSET_HXX #define CONNECTIVITY_PRIVILEGESRESULTSET_HXX #ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_ #include "FDatabaseMetaDataResultSet.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif namespace connectivity { class OResultSetPrivileges : public ODatabaseMetaDataResultSet { ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> m_xTables; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow> m_xRow; sal_Bool m_bResetValues; protected: virtual const ORowSetValue& getValue(sal_Int32 columnIndex); public: OResultSetPrivileges(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta ,const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern); // ::cppu::OComponentHelper virtual void SAL_CALL disposing(void); // XResultSet virtual sal_Bool SAL_CALL next( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // CONNECTIVITY_PRIVILEGESRESULTSET_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.372); FILE MERGED 2008/04/01 10:53:17 thb 1.3.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:05 rt 1.3.372.1: #i87441# Change license header to LPGL v3.<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: TPrivilegesResultSet.hxx,v $ * $Revision: 1.4 $ * * 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 CONNECTIVITY_PRIVILEGESRESULTSET_HXX #define CONNECTIVITY_PRIVILEGESRESULTSET_HXX #include "FDatabaseMetaDataResultSet.hxx" #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> namespace connectivity { class OResultSetPrivileges : public ODatabaseMetaDataResultSet { ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> m_xTables; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow> m_xRow; sal_Bool m_bResetValues; protected: virtual const ORowSetValue& getValue(sal_Int32 columnIndex); public: OResultSetPrivileges(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _rxMeta ,const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern); // ::cppu::OComponentHelper virtual void SAL_CALL disposing(void); // XResultSet virtual sal_Bool SAL_CALL next( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } #endif // CONNECTIVITY_PRIVILEGESRESULTSET_HXX <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2011 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \file StackExporter.cpp \author Jens Krueger SCI Institute University of Utah */ #include "StdTuvokDefines.h" #ifndef TUVOK_NO_QT #include <QtGui/QImage> #include <QtGui/QImageWriter> #endif #include "StackExporter.h" #include <Basics/SysTools.h> #include <Basics/LargeRAWFile.h> #include "Controller/Controller.h" std::vector<std::pair<std::string,std::string>> StackExporter::GetSuportedImageFormats() { std::vector<std::pair<std::string,std::string>> formats; formats.push_back(std::make_pair("raw","RAW RGBA file without header information")); #ifndef TUVOK_NO_QT QList<QByteArray> listImageFormats = QImageWriter::supportedImageFormats(); for (int i = 0;i<listImageFormats.size();i++) { QByteArray imageFormat = listImageFormats[i]; QString qStrImageFormat(imageFormat); formats.push_back(std::make_pair(qStrImageFormat.toStdString(),"Qt Image Format")); } #endif return formats; } bool StackExporter::WriteImage(unsigned char* pData, const std::string& strFilename, const UINT64VECTOR2& vSize, uint64_t iComponentCount) { if (iComponentCount != 4 && iComponentCount != 3) return false; if (SysTools::ToLowerCase(SysTools::GetExt(strFilename)) == "raw") { LargeRAWFile out(strFilename); if (!out.Create()) return false; out.WriteRAW(pData, vSize.area()*iComponentCount); out.Close(); } #ifndef TUVOK_NO_QT QImage qTargetFile(QSize(int(vSize.x), int(vSize.y)), iComponentCount == 4 ? QImage::Format_ARGB32 : QImage::Format_RGB32); size_t i = 0; if (iComponentCount == 4) { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgba(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]), int(pData[i+3]))); i+=4; } } } else { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgb(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]))); i+=3; } } } return qTargetFile.save(strFilename.c_str()); #else return false; #endif } bool StackExporter::WriteSlice(unsigned char* pData, const TransferFunction1D* pTrans, uint64_t iBitWidth, const std::string& strCurrentDiFilename, const UINT64VECTOR2& vSize, float fRescale, uint64_t iComponentCount) { size_t iImageCompCount = (iComponentCount == 3 || iComponentCount == 2) ? 3 : 4; using namespace boost; // for uintXX_t types. switch (iComponentCount) { case 1 : switch (iBitWidth) { case 8 : ApplyTFInplace(pData, vSize, fRescale, pTrans); break; case 16 : ApplyTFInplace(reinterpret_cast<uint16_t*>(pData), vSize, fRescale, pTrans); break; case 32 : ApplyTFInplace(reinterpret_cast<uint32_t*>(pData), vSize, fRescale, pTrans); break; default : return false; } break; case 2 : PadInplace(pData, vSize, 3, 1, 0); break; default : break; // all other cases (RGB & RGBA) are written as they are } // write data to disk std::string strCurrentTargetFilename = SysTools::FindNextSequenceName(strCurrentDiFilename); return WriteImage(pData,strCurrentTargetFilename, vSize, iImageCompCount); } void StackExporter::PadInplace(unsigned char* pData, UINT64VECTOR2 vSize, unsigned int iStepping, unsigned int iPadcount, unsigned char iValue) { assert(iStepping > iPadcount) ; for (size_t i = 0;i<vSize.area();++i) { size_t sourcePos = (iStepping - iPadcount) * (vSize.area()-(i+1)); size_t targetPos = iStepping * (vSize.area()-(i+1)); for (unsigned int j = 0;j<iStepping;++j) { if ( j < iStepping - iPadcount) pData[targetPos] = pData[sourcePos]; else pData[targetPos] = iValue; targetPos++; sourcePos++; } } } bool StackExporter::WriteStacks(const std::string& strRAWFilename, const std::string& strTargetFilename, const TransferFunction1D* pTrans, uint64_t iBitWidth, uint64_t iComponentCount, float fRescale, UINT64VECTOR3 vDomainSize, bool bAllDirs) { if (iComponentCount > 4) { T_ERROR("Invalid channel count, no more than four components are accepted by the stack exporter."); return false; } size_t iDataByteWith = size_t(iBitWidth/8); // convert to 8bit for more than 1 comp data if (iBitWidth != 8 && iComponentCount > 1) { T_ERROR("Invalid bit depth, only 8bit data is accepted by the stack exporter for multi channel data."); return false; /* LargeRAWFile quantizeDataSource(strRAWFilename); if (!quantizeDataSource.Open(true)) return false; // TODO quantize quantizeDataSource.Close(); iDataByteWith = 1; */ } LargeRAWFile dataSource(strRAWFilename); if (!dataSource.Open()) return false; size_t iMaxPair = size_t((vDomainSize.x <= vDomainSize.y && vDomainSize.x <= vDomainSize.z) ? vDomainSize.z * vDomainSize.y : ( (vDomainSize.y <= vDomainSize.x && vDomainSize.y <= vDomainSize.z) ? vDomainSize.x * vDomainSize.z : vDomainSize.x * vDomainSize.y)); unsigned char* pData = new unsigned char[4*iMaxPair*iDataByteWith]; UINT64VECTOR2 vSize(vDomainSize.z, vDomainSize.y); std::string strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_x"); size_t elemSize = iComponentCount*iDataByteWith; if (bAllDirs) { for (uint64_t x = 0;x<vDomainSize.x;x++) { MESSAGE("Exporting X-Axis Stack. Processing Image %llu of %llu", x+1, vDomainSize.x); uint64_t offset = 0; for (uint64_t v = 0;v<vDomainSize.y;v++) { for (uint64_t u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (x+u*vDomainSize.x*vDomainSize.y+v*vDomainSize.x) ); dataSource.ReadRAW(pData+offset, elemSize); offset += elemSize; } } if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",x); delete [] pData; dataSource.Close(); } } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.z); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_y"); for (uint64_t y = 0;y<vDomainSize.y;y++) { MESSAGE("Exporting Y-Axis Stack. Processing Image %llu of %llu", y+1, vDomainSize.y); uint64_t offset = 0; for (uint64_t u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (y*vDomainSize.x+u*vDomainSize.x*vDomainSize.y) ); dataSource.ReadRAW(pData+offset, vDomainSize.x*elemSize); offset += vDomainSize.x*elemSize; } if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",y); delete [] pData; dataSource.Close(); } } dataSource.SeekPos(0); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_z"); } else { strCurrentDirTargetFilename = strTargetFilename; } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.y); for (uint64_t z = 0;z<vDomainSize.z;z++) { MESSAGE("Exporting Z-Axis Stack. Processing Image %llu of %llu", z+1, vDomainSize.z); dataSource.ReadRAW(pData, vDomainSize.x*vDomainSize.y*elemSize); if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",z); delete [] pData; dataSource.Close(); } } dataSource.Close(); delete [] pData; return true; } <commit_msg>Fix double-free, simplify memory management.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2011 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \file StackExporter.cpp \author Jens Krueger SCI Institute University of Utah */ #include "StdTuvokDefines.h" #include <memory> #ifndef TUVOK_NO_QT #include <QtGui/QImage> #include <QtGui/QImageWriter> #endif #include "StackExporter.h" #include "Basics/SysTools.h" #include "Basics/LargeRAWFile.h" #include "Basics/nonstd.h" #include "Controller/Controller.h" std::vector<std::pair<std::string,std::string>> StackExporter::GetSuportedImageFormats() { std::vector<std::pair<std::string,std::string>> formats; formats.push_back(std::make_pair("raw","RAW RGBA file without header information")); #ifndef TUVOK_NO_QT QList<QByteArray> listImageFormats = QImageWriter::supportedImageFormats(); for (int i = 0;i<listImageFormats.size();i++) { QByteArray imageFormat = listImageFormats[i]; QString qStrImageFormat(imageFormat); formats.push_back(std::make_pair(qStrImageFormat.toStdString(),"Qt Image Format")); } #endif return formats; } bool StackExporter::WriteImage(unsigned char* pData, const std::string& strFilename, const UINT64VECTOR2& vSize, uint64_t iComponentCount) { if (iComponentCount != 4 && iComponentCount != 3) return false; if (SysTools::ToLowerCase(SysTools::GetExt(strFilename)) == "raw") { LargeRAWFile out(strFilename); if (!out.Create()) return false; out.WriteRAW(pData, vSize.area()*iComponentCount); out.Close(); } #ifndef TUVOK_NO_QT QImage qTargetFile(QSize(int(vSize.x), int(vSize.y)), iComponentCount == 4 ? QImage::Format_ARGB32 : QImage::Format_RGB32); size_t i = 0; if (iComponentCount == 4) { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgba(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]), int(pData[i+3]))); i+=4; } } } else { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgb(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]))); i+=3; } } } return qTargetFile.save(strFilename.c_str()); #else return false; #endif } bool StackExporter::WriteSlice(unsigned char* pData, const TransferFunction1D* pTrans, uint64_t iBitWidth, const std::string& strCurrentDiFilename, const UINT64VECTOR2& vSize, float fRescale, uint64_t iComponentCount) { size_t iImageCompCount = (iComponentCount == 3 || iComponentCount == 2) ? 3 : 4; using namespace boost; // for uintXX_t types. switch (iComponentCount) { case 1 : switch (iBitWidth) { case 8 : ApplyTFInplace(pData, vSize, fRescale, pTrans); break; case 16 : ApplyTFInplace(reinterpret_cast<uint16_t*>(pData), vSize, fRescale, pTrans); break; case 32 : ApplyTFInplace(reinterpret_cast<uint32_t*>(pData), vSize, fRescale, pTrans); break; default : return false; } break; case 2 : PadInplace(pData, vSize, 3, 1, 0); break; default : break; // all other cases (RGB & RGBA) are written as they are } // write data to disk std::string strCurrentTargetFilename = SysTools::FindNextSequenceName(strCurrentDiFilename); return WriteImage(pData,strCurrentTargetFilename, vSize, iImageCompCount); } void StackExporter::PadInplace(unsigned char* pData, UINT64VECTOR2 vSize, unsigned int iStepping, unsigned int iPadcount, unsigned char iValue) { assert(iStepping > iPadcount) ; for (size_t i = 0;i<vSize.area();++i) { size_t sourcePos = (iStepping - iPadcount) * (vSize.area()-(i+1)); size_t targetPos = iStepping * (vSize.area()-(i+1)); for (unsigned int j = 0;j<iStepping;++j) { if ( j < iStepping - iPadcount) pData[targetPos] = pData[sourcePos]; else pData[targetPos] = iValue; targetPos++; sourcePos++; } } } bool StackExporter::WriteStacks(const std::string& strRAWFilename, const std::string& strTargetFilename, const TransferFunction1D* pTrans, uint64_t iBitWidth, uint64_t iComponentCount, float fRescale, UINT64VECTOR3 vDomainSize, bool bAllDirs) { if (iComponentCount > 4) { T_ERROR("Invalid channel count, no more than four components are accepted by the stack exporter."); return false; } size_t iDataByteWith = size_t(iBitWidth/8); // convert to 8bit for more than 1 comp data if (iBitWidth != 8 && iComponentCount > 1) { T_ERROR("Invalid bit depth, only 8bit data is accepted by the stack exporter for multi channel data."); return false; /* LargeRAWFile quantizeDataSource(strRAWFilename); if (!quantizeDataSource.Open(true)) return false; // TODO quantize quantizeDataSource.Close(); iDataByteWith = 1; */ } LargeRAWFile dataSource(strRAWFilename); if (!dataSource.Open()) return false; size_t iMaxPair = size_t((vDomainSize.x <= vDomainSize.y && vDomainSize.x <= vDomainSize.z) ? vDomainSize.z * vDomainSize.y : ( (vDomainSize.y <= vDomainSize.x && vDomainSize.y <= vDomainSize.z) ? vDomainSize.x * vDomainSize.z : vDomainSize.x * vDomainSize.y)); std::shared_ptr<unsigned char> data( new unsigned char[4*iMaxPair*iDataByteWith], nonstd::DeleteArray<unsigned char>() ); UINT64VECTOR2 vSize(vDomainSize.z, vDomainSize.y); std::string strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_x"); size_t elemSize = iComponentCount*iDataByteWith; if (bAllDirs) { for (uint64_t x = 0;x<vDomainSize.x;x++) { MESSAGE("Exporting X-Axis Stack. Processing Image %llu of %llu", x+1, vDomainSize.x); uint64_t offset = 0; for (uint64_t v = 0;v<vDomainSize.y;v++) { for (uint64_t u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (x+u*vDomainSize.x*vDomainSize.y+v*vDomainSize.x) ); dataSource.ReadRAW(data.get()+offset, elemSize); offset += elemSize; } } if (!WriteSlice(data.get(), pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",x); dataSource.Close(); } } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.z); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_y"); for (uint64_t y = 0;y<vDomainSize.y;y++) { MESSAGE("Exporting Y-Axis Stack. Processing Image %llu of %llu", y+1, vDomainSize.y); uint64_t offset = 0; for (uint64_t u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (y*vDomainSize.x+u*vDomainSize.x*vDomainSize.y) ); dataSource.ReadRAW(data.get()+offset, vDomainSize.x*elemSize); offset += vDomainSize.x*elemSize; } if (!WriteSlice(data.get(), pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",y); dataSource.Close(); } } dataSource.SeekPos(0); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_z"); } else { strCurrentDirTargetFilename = strTargetFilename; } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.y); for (uint64_t z = 0;z<vDomainSize.z;z++) { MESSAGE("Exporting Z-Axis Stack. Processing Image %llu of %llu", z+1, vDomainSize.z); dataSource.ReadRAW(data.get(), vDomainSize.x*vDomainSize.y*elemSize); if (!WriteSlice(data.get(), pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",z); dataSource.Close(); } } dataSource.Close(); return true; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2011 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \file StackExporter.cpp \author Jens Krueger SCI Institute University of Utah */ #include "boost/cstdint.hpp" #ifndef TUVOK_NO_QT #include <QtGui/QImage> #include <QtGui/QImageWriter> #endif #include "StackExporter.h" #include <Basics/SysTools.h> #include <Basics/LargeRAWFile.h> #include "Controller/Controller.h" std::vector<std::pair<std::string,std::string> > StackExporter::GetSuportedImageFormats() { std::vector<std::pair<std::string,std::string> > formats; formats.push_back(std::make_pair("raw","RAW RGBA file without header information")); #ifndef TUVOK_NO_QT QList<QByteArray> listImageFormats = QImageWriter::supportedImageFormats(); for (int i = 0;i<listImageFormats.size();i++) { QByteArray imageFormat = listImageFormats[i]; QString qStrImageFormat(imageFormat); formats.push_back(std::make_pair(qStrImageFormat.toStdString(),"Qt Image Format")); } #endif return formats; } bool StackExporter::WriteImage(unsigned char* pData, const std::string& strFilename, const UINT64VECTOR2& vSize, UINT64 iComponentCount) { if (iComponentCount != 4 && iComponentCount != 3) return false; if (SysTools::ToLowerCase(SysTools::GetExt(strFilename)) == "raw") { LargeRAWFile out(strFilename); if (!out.Create()) return false; out.WriteRAW(pData, vSize.area()*iComponentCount); out.Close(); } #ifndef TUVOK_NO_QT QImage qTargetFile(QSize(vSize.x, vSize.y), iComponentCount == 4 ? QImage::Format_ARGB32 : QImage::Format_RGB32); size_t i = 0; if (iComponentCount == 4) { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgba(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]), int(pData[i+3]))); i+=4; } } } else { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgb(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]))); i+=3; } } } return qTargetFile.save(strFilename.c_str()); #else return false; #endif } bool StackExporter::WriteSlice(unsigned char* pData, const TransferFunction1D* pTrans, UINT64 iBitWidth, const std::string& strCurrentDiFilename, const UINT64VECTOR2& vSize, float fRescale, UINT64 iComponentCount) { size_t iImageCompCount = (iComponentCount == 3 || iComponentCount == 2) ? 3 : 4; using namespace boost; // for uintXX_t types. switch (iComponentCount) { case 1 : switch (iBitWidth) { case 8 : ApplyTFInplace(pData, vSize, fRescale, pTrans); break; case 16 : ApplyTFInplace(reinterpret_cast<uint16_t*>(pData), vSize, fRescale, pTrans); break; case 32 : ApplyTFInplace(reinterpret_cast<uint32_t*>(pData), vSize, fRescale, pTrans); break; default : return false; } break; case 2 : PadInplace(pData, vSize, 3, 1, 0); break; default : break; // all other cases (RGB & RGBA) are written as they are } // write data to disk std::string strCurrentTargetFilename = SysTools::FindNextSequenceName(strCurrentDiFilename); return WriteImage(pData,strCurrentTargetFilename, vSize, iImageCompCount); } void StackExporter::PadInplace(unsigned char* pData, UINT64VECTOR2 vSize, unsigned int iStepping, unsigned int iPadcount, unsigned char iValue) { assert(iStepping > iPadcount) ; for (size_t i = 0;i<vSize.area();++i) { size_t sourcePos = (iStepping - iPadcount) * (vSize.area()-(i+1)); size_t targetPos = iStepping * (vSize.area()-(i+1)); for (unsigned int j = 0;j<iStepping;++j) { if ( j < iStepping - iPadcount) pData[targetPos] = pData[sourcePos]; else pData[targetPos] = iValue; targetPos++; sourcePos++; } } } bool StackExporter::WriteStacks(const std::string& strRAWFilename, const std::string& strTargetFilename, const TransferFunction1D* pTrans, UINT64 iBitWidth, UINT64 iComponentCount, float fRescale, UINT64VECTOR3 vDomainSize, bool bAllDirs) { if (iComponentCount > 4) { T_ERROR("Invalid channel count, no more than four components are accepted by the stack exporter."); return false; } size_t iDataByteWith = size_t(iBitWidth/8); // convert to 8bit for more than 1 comp data if (iBitWidth != 8 && iComponentCount > 1) { T_ERROR("Invalid bit depth, only 8bit data is accepted by the stack exporter for multi channel data."); return false; /* LargeRAWFile quantizeDataSource(strRAWFilename); if (!quantizeDataSource.Open(true)) return false; // TODO quantize quantizeDataSource.Close(); iDataByteWith = 1; */ } LargeRAWFile dataSource(strRAWFilename); if (!dataSource.Open()) return false; size_t iMaxPair = size_t((vDomainSize.x <= vDomainSize.y && vDomainSize.x <= vDomainSize.z) ? vDomainSize.z * vDomainSize.y : ( (vDomainSize.y <= vDomainSize.x && vDomainSize.y <= vDomainSize.z) ? vDomainSize.x * vDomainSize.z : vDomainSize.x * vDomainSize.y)); unsigned char* pData = new unsigned char[4*iMaxPair*iDataByteWith]; UINT64VECTOR2 vSize(vDomainSize.z, vDomainSize.y); std::string strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_x"); size_t elemSize = iComponentCount*iDataByteWith; if (bAllDirs) { for (UINT64 x = 0;x<vDomainSize.x;x++) { MESSAGE("Exporting X-Axis Stack. Processing Image %llu of %llu", x+1, vDomainSize.x); UINT64 offset = 0; for (UINT64 v = 0;v<vDomainSize.y;v++) { for (UINT64 u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (x+u*vDomainSize.x*vDomainSize.y+v*vDomainSize.x) ); dataSource.ReadRAW(pData+offset, elemSize); offset += elemSize; } } if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",x); delete [] pData; dataSource.Close(); } } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.z); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_y"); for (UINT64 y = 0;y<vDomainSize.y;y++) { MESSAGE("Exporting Y-Axis Stack. Processing Image %llu of %llu", y+1, vDomainSize.y); UINT64 offset = 0; for (UINT64 u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (y*vDomainSize.x+u*vDomainSize.x*vDomainSize.y) ); dataSource.ReadRAW(pData+offset, vDomainSize.x*elemSize); offset += vDomainSize.x*elemSize; } if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",y); delete [] pData; dataSource.Close(); } } dataSource.SeekPos(0); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_z"); } else { strCurrentDirTargetFilename = strTargetFilename; } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.y); for (UINT64 z = 0;z<vDomainSize.z;z++) { MESSAGE("Exporting Z-Axis Stack. Processing Image %llu of %llu", z+1, vDomainSize.z); dataSource.ReadRAW(pData, vDomainSize.x*vDomainSize.y*elemSize); if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",z); delete [] pData; dataSource.Close(); } } dataSource.Close(); delete [] pData; return true; } <commit_msg>fixed 64 bit windows warning<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2011 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \file StackExporter.cpp \author Jens Krueger SCI Institute University of Utah */ #include "boost/cstdint.hpp" #ifndef TUVOK_NO_QT #include <QtGui/QImage> #include <QtGui/QImageWriter> #endif #include "StackExporter.h" #include <Basics/SysTools.h> #include <Basics/LargeRAWFile.h> #include "Controller/Controller.h" std::vector<std::pair<std::string,std::string> > StackExporter::GetSuportedImageFormats() { std::vector<std::pair<std::string,std::string> > formats; formats.push_back(std::make_pair("raw","RAW RGBA file without header information")); #ifndef TUVOK_NO_QT QList<QByteArray> listImageFormats = QImageWriter::supportedImageFormats(); for (int i = 0;i<listImageFormats.size();i++) { QByteArray imageFormat = listImageFormats[i]; QString qStrImageFormat(imageFormat); formats.push_back(std::make_pair(qStrImageFormat.toStdString(),"Qt Image Format")); } #endif return formats; } bool StackExporter::WriteImage(unsigned char* pData, const std::string& strFilename, const UINT64VECTOR2& vSize, UINT64 iComponentCount) { if (iComponentCount != 4 && iComponentCount != 3) return false; if (SysTools::ToLowerCase(SysTools::GetExt(strFilename)) == "raw") { LargeRAWFile out(strFilename); if (!out.Create()) return false; out.WriteRAW(pData, vSize.area()*iComponentCount); out.Close(); } #ifndef TUVOK_NO_QT QImage qTargetFile(QSize(int(vSize.x), int(vSize.y)), iComponentCount == 4 ? QImage::Format_ARGB32 : QImage::Format_RGB32); size_t i = 0; if (iComponentCount == 4) { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgba(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]), int(pData[i+3]))); i+=4; } } } else { for (int y = 0;y<int(vSize.y);y++) { for (int x = 0;x<int(vSize.x);x++) { qTargetFile.setPixel(x,y, qRgb(int(pData[i+0]), int(pData[i+1]), int(pData[i+2]))); i+=3; } } } return qTargetFile.save(strFilename.c_str()); #else return false; #endif } bool StackExporter::WriteSlice(unsigned char* pData, const TransferFunction1D* pTrans, UINT64 iBitWidth, const std::string& strCurrentDiFilename, const UINT64VECTOR2& vSize, float fRescale, UINT64 iComponentCount) { size_t iImageCompCount = (iComponentCount == 3 || iComponentCount == 2) ? 3 : 4; using namespace boost; // for uintXX_t types. switch (iComponentCount) { case 1 : switch (iBitWidth) { case 8 : ApplyTFInplace(pData, vSize, fRescale, pTrans); break; case 16 : ApplyTFInplace(reinterpret_cast<uint16_t*>(pData), vSize, fRescale, pTrans); break; case 32 : ApplyTFInplace(reinterpret_cast<uint32_t*>(pData), vSize, fRescale, pTrans); break; default : return false; } break; case 2 : PadInplace(pData, vSize, 3, 1, 0); break; default : break; // all other cases (RGB & RGBA) are written as they are } // write data to disk std::string strCurrentTargetFilename = SysTools::FindNextSequenceName(strCurrentDiFilename); return WriteImage(pData,strCurrentTargetFilename, vSize, iImageCompCount); } void StackExporter::PadInplace(unsigned char* pData, UINT64VECTOR2 vSize, unsigned int iStepping, unsigned int iPadcount, unsigned char iValue) { assert(iStepping > iPadcount) ; for (size_t i = 0;i<vSize.area();++i) { size_t sourcePos = (iStepping - iPadcount) * (vSize.area()-(i+1)); size_t targetPos = iStepping * (vSize.area()-(i+1)); for (unsigned int j = 0;j<iStepping;++j) { if ( j < iStepping - iPadcount) pData[targetPos] = pData[sourcePos]; else pData[targetPos] = iValue; targetPos++; sourcePos++; } } } bool StackExporter::WriteStacks(const std::string& strRAWFilename, const std::string& strTargetFilename, const TransferFunction1D* pTrans, UINT64 iBitWidth, UINT64 iComponentCount, float fRescale, UINT64VECTOR3 vDomainSize, bool bAllDirs) { if (iComponentCount > 4) { T_ERROR("Invalid channel count, no more than four components are accepted by the stack exporter."); return false; } size_t iDataByteWith = size_t(iBitWidth/8); // convert to 8bit for more than 1 comp data if (iBitWidth != 8 && iComponentCount > 1) { T_ERROR("Invalid bit depth, only 8bit data is accepted by the stack exporter for multi channel data."); return false; /* LargeRAWFile quantizeDataSource(strRAWFilename); if (!quantizeDataSource.Open(true)) return false; // TODO quantize quantizeDataSource.Close(); iDataByteWith = 1; */ } LargeRAWFile dataSource(strRAWFilename); if (!dataSource.Open()) return false; size_t iMaxPair = size_t((vDomainSize.x <= vDomainSize.y && vDomainSize.x <= vDomainSize.z) ? vDomainSize.z * vDomainSize.y : ( (vDomainSize.y <= vDomainSize.x && vDomainSize.y <= vDomainSize.z) ? vDomainSize.x * vDomainSize.z : vDomainSize.x * vDomainSize.y)); unsigned char* pData = new unsigned char[4*iMaxPair*iDataByteWith]; UINT64VECTOR2 vSize(vDomainSize.z, vDomainSize.y); std::string strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_x"); size_t elemSize = iComponentCount*iDataByteWith; if (bAllDirs) { for (UINT64 x = 0;x<vDomainSize.x;x++) { MESSAGE("Exporting X-Axis Stack. Processing Image %llu of %llu", x+1, vDomainSize.x); UINT64 offset = 0; for (UINT64 v = 0;v<vDomainSize.y;v++) { for (UINT64 u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (x+u*vDomainSize.x*vDomainSize.y+v*vDomainSize.x) ); dataSource.ReadRAW(pData+offset, elemSize); offset += elemSize; } } if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",x); delete [] pData; dataSource.Close(); } } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.z); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_y"); for (UINT64 y = 0;y<vDomainSize.y;y++) { MESSAGE("Exporting Y-Axis Stack. Processing Image %llu of %llu", y+1, vDomainSize.y); UINT64 offset = 0; for (UINT64 u = 0;u<vDomainSize.z;u++) { dataSource.SeekPos(elemSize * (y*vDomainSize.x+u*vDomainSize.x*vDomainSize.y) ); dataSource.ReadRAW(pData+offset, vDomainSize.x*elemSize); offset += vDomainSize.x*elemSize; } if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",y); delete [] pData; dataSource.Close(); } } dataSource.SeekPos(0); strCurrentDirTargetFilename = SysTools::AppendFilename(strTargetFilename, "_z"); } else { strCurrentDirTargetFilename = strTargetFilename; } vSize = UINT64VECTOR2(vDomainSize.x, vDomainSize.y); for (UINT64 z = 0;z<vDomainSize.z;z++) { MESSAGE("Exporting Z-Axis Stack. Processing Image %llu of %llu", z+1, vDomainSize.z); dataSource.ReadRAW(pData, vDomainSize.x*vDomainSize.y*elemSize); if (!WriteSlice(pData, pTrans, iBitWidth, strCurrentDirTargetFilename, vSize, fRescale, iComponentCount)) { T_ERROR("Unable to write stack image %llu.",z); delete [] pData; dataSource.Close(); } } dataSource.Close(); delete [] pData; return true; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright 2000, 2010 Oracle and/or its affiliates. * 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 Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ /************************************************************************* ************************************************************************* * * simple client application registering and using the counter component. * ************************************************************************* *************************************************************************/ #include <stdio.h> #include <sal/main.h> #include <rtl/ustring.hxx> #include <osl/diagnose.h> #include <cppuhelper/bootstrap.hxx> // generated c++ interfaces #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <foo/XCountable.hpp> using namespace foo; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; using namespace ::rtl; //======================================================================= SAL_IMPLEMENT_MAIN() { try { Reference< XComponentContext > xContext(::cppu::defaultBootstrap_InitialComponentContext()); OSL_ENSURE( xContext.is(), "### bootstrap failed!\n" ); Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager(); OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" ); Reference< XInterface > xx = xMgr->createInstanceWithContext( OUString::createFromAscii("foo.Counter"), xContext); OSL_ENSURE( xx.is(), "### cannot get service instance of \"foo.Counter\"!" ); Reference< XCountable > xCount( xx, UNO_QUERY ); OSL_ENSURE( xCount.is(), "### cannot query XCountable interface of service instance \"foo.Counter\"!" ); if (xCount.is()) { xCount->setCount( 42 ); fprintf( stdout , "%d," , (int)xCount->getCount() ); fprintf( stdout , "%d," , (int)xCount->increment() ); fprintf( stdout , "%d\n" , (int)xCount->decrement() ); } Reference< XComponent >::query( xContext )->dispose(); } catch( Exception& e) { printf("Error: caught exception:\n %s\n", OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr()); exit(1); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Missing return<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright 2000, 2010 Oracle and/or its affiliates. * 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 Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ /************************************************************************* ************************************************************************* * * simple client application registering and using the counter component. * ************************************************************************* *************************************************************************/ #include "sal/config.h" #include <cstdlib> #include <stdio.h> #include <sal/main.h> #include <rtl/ustring.hxx> #include <osl/diagnose.h> #include <cppuhelper/bootstrap.hxx> // generated c++ interfaces #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <foo/XCountable.hpp> using namespace foo; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; using namespace ::rtl; //======================================================================= SAL_IMPLEMENT_MAIN() { try { Reference< XComponentContext > xContext(::cppu::defaultBootstrap_InitialComponentContext()); OSL_ENSURE( xContext.is(), "### bootstrap failed!\n" ); Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager(); OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" ); Reference< XInterface > xx = xMgr->createInstanceWithContext( OUString::createFromAscii("foo.Counter"), xContext); OSL_ENSURE( xx.is(), "### cannot get service instance of \"foo.Counter\"!" ); Reference< XCountable > xCount( xx, UNO_QUERY ); OSL_ENSURE( xCount.is(), "### cannot query XCountable interface of service instance \"foo.Counter\"!" ); if (xCount.is()) { xCount->setCount( 42 ); fprintf( stdout , "%d," , (int)xCount->getCount() ); fprintf( stdout , "%d," , (int)xCount->increment() ); fprintf( stdout , "%d\n" , (int)xCount->decrement() ); } Reference< XComponent >::query( xContext )->dispose(); return EXIT_SUCCESS; } catch( Exception& e) { printf("Error: caught exception:\n %s\n", OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr()); return EXIT_FAILURE; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>//===- RegionInfo.cpp - SESE region detection analysis --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Detects single entry single exit regions in the control flow graph. //===----------------------------------------------------------------------===// #include "llvm/Analysis/RegionInfo.h" #include "llvm/Analysis/RegionInfoImpl.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/RegionIterator.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include <algorithm> #include <iterator> #include <set> using namespace llvm; #define DEBUG_TYPE "region" namespace llvm { template class RegionBase<RegionTraits<Function>>; template class RegionNodeBase<RegionTraits<Function>>; template class RegionInfoBase<RegionTraits<Function>>; } STATISTIC(numRegions, "The # of regions"); STATISTIC(numSimpleRegions, "The # of simple regions"); // Always verify if expensive checking is enabled. static cl::opt<bool,true> VerifyRegionInfoX( "verify-region-info", cl::location(RegionInfoBase<RegionTraits<Function>>::VerifyRegionInfo), cl::desc("Verify region info (time consuming)")); static cl::opt<Region::PrintStyle, true> printStyleX("print-region-style", cl::location(RegionInfo::printStyle), cl::Hidden, cl::desc("style of printing regions"), cl::values( clEnumValN(Region::PrintNone, "none", "print no details"), clEnumValN(Region::PrintBB, "bb", "print regions in detail with block_iterator"), clEnumValN(Region::PrintRN, "rn", "print regions in detail with element_iterator"), clEnumValEnd)); //===----------------------------------------------------------------------===// // Region implementation // Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI, DominatorTree *DT, Region *Parent) : RegionBase<RegionTraits<Function>>(Entry, Exit, RI, DT, Parent) { } Region::~Region() { } //===----------------------------------------------------------------------===// // RegionInfo implementation // RegionInfo::RegionInfo() : RegionInfoBase<RegionTraits<Function>>() { } RegionInfo::~RegionInfo() { } void RegionInfo::updateStatistics(Region *R) { ++numRegions; // TODO: Slow. Should only be enabled if -stats is used. if (R->isSimple()) ++numSimpleRegions; } void RegionInfo::RegionInfo::recalculate(Function &F, DominatorTree *DT_, PostDominatorTree *PDT_, DominanceFrontier *DF_) { DT = DT_; PDT = PDT_; DF = DF_; TopLevelRegion = new Region(&F.getEntryBlock(), nullptr, this, DT, nullptr); updateStatistics(TopLevelRegion); calculate(F); } //===----------------------------------------------------------------------===// // RegionInfoPass implementation // RegionInfoPass::RegionInfoPass() : FunctionPass(ID) { initializeRegionInfoPassPass(*PassRegistry::getPassRegistry()); } RegionInfoPass::~RegionInfoPass() { } bool RegionInfoPass::runOnFunction(Function &F) { releaseMemory(); auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); auto PDT = &getAnalysis<PostDominatorTree>(); auto DF = &getAnalysis<DominanceFrontier>(); RI.recalculate(F, DT, PDT, DF); return false; } void RegionInfoPass::releaseMemory() { RI.releaseMemory(); } void RegionInfoPass::verifyAnalysis() const { RI.verifyAnalysis(); } void RegionInfoPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequiredTransitive<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTree>(); AU.addRequired<DominanceFrontier>(); } void RegionInfoPass::print(raw_ostream &OS, const Module *) const { RI.print(OS); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void RegionInfoPass::dump() const { RI.dump(); } #endif char RegionInfoPass::ID = 0; INITIALIZE_PASS_BEGIN(RegionInfoPass, "regions", "Detect single entry single exit regions", true, true) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(PostDominatorTree) INITIALIZE_PASS_DEPENDENCY(DominanceFrontier) INITIALIZE_PASS_END(RegionInfoPass, "regions", "Detect single entry single exit regions", true, true) // Create methods available outside of this file, to use them // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by // the link time optimization. namespace llvm { FunctionPass *createRegionInfoPass() { return new RegionInfoPass(); } } <commit_msg>Fix msc17 build. RegionInfo::RegionInfo::recalculate() doesn't make sense.<commit_after>//===- RegionInfo.cpp - SESE region detection analysis --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Detects single entry single exit regions in the control flow graph. //===----------------------------------------------------------------------===// #include "llvm/Analysis/RegionInfo.h" #include "llvm/Analysis/RegionInfoImpl.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/RegionIterator.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include <algorithm> #include <iterator> #include <set> using namespace llvm; #define DEBUG_TYPE "region" namespace llvm { template class RegionBase<RegionTraits<Function>>; template class RegionNodeBase<RegionTraits<Function>>; template class RegionInfoBase<RegionTraits<Function>>; } STATISTIC(numRegions, "The # of regions"); STATISTIC(numSimpleRegions, "The # of simple regions"); // Always verify if expensive checking is enabled. static cl::opt<bool,true> VerifyRegionInfoX( "verify-region-info", cl::location(RegionInfoBase<RegionTraits<Function>>::VerifyRegionInfo), cl::desc("Verify region info (time consuming)")); static cl::opt<Region::PrintStyle, true> printStyleX("print-region-style", cl::location(RegionInfo::printStyle), cl::Hidden, cl::desc("style of printing regions"), cl::values( clEnumValN(Region::PrintNone, "none", "print no details"), clEnumValN(Region::PrintBB, "bb", "print regions in detail with block_iterator"), clEnumValN(Region::PrintRN, "rn", "print regions in detail with element_iterator"), clEnumValEnd)); //===----------------------------------------------------------------------===// // Region implementation // Region::Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI, DominatorTree *DT, Region *Parent) : RegionBase<RegionTraits<Function>>(Entry, Exit, RI, DT, Parent) { } Region::~Region() { } //===----------------------------------------------------------------------===// // RegionInfo implementation // RegionInfo::RegionInfo() : RegionInfoBase<RegionTraits<Function>>() { } RegionInfo::~RegionInfo() { } void RegionInfo::updateStatistics(Region *R) { ++numRegions; // TODO: Slow. Should only be enabled if -stats is used. if (R->isSimple()) ++numSimpleRegions; } void RegionInfo::recalculate(Function &F, DominatorTree *DT_, PostDominatorTree *PDT_, DominanceFrontier *DF_) { DT = DT_; PDT = PDT_; DF = DF_; TopLevelRegion = new Region(&F.getEntryBlock(), nullptr, this, DT, nullptr); updateStatistics(TopLevelRegion); calculate(F); } //===----------------------------------------------------------------------===// // RegionInfoPass implementation // RegionInfoPass::RegionInfoPass() : FunctionPass(ID) { initializeRegionInfoPassPass(*PassRegistry::getPassRegistry()); } RegionInfoPass::~RegionInfoPass() { } bool RegionInfoPass::runOnFunction(Function &F) { releaseMemory(); auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); auto PDT = &getAnalysis<PostDominatorTree>(); auto DF = &getAnalysis<DominanceFrontier>(); RI.recalculate(F, DT, PDT, DF); return false; } void RegionInfoPass::releaseMemory() { RI.releaseMemory(); } void RegionInfoPass::verifyAnalysis() const { RI.verifyAnalysis(); } void RegionInfoPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); AU.addRequiredTransitive<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTree>(); AU.addRequired<DominanceFrontier>(); } void RegionInfoPass::print(raw_ostream &OS, const Module *) const { RI.print(OS); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) void RegionInfoPass::dump() const { RI.dump(); } #endif char RegionInfoPass::ID = 0; INITIALIZE_PASS_BEGIN(RegionInfoPass, "regions", "Detect single entry single exit regions", true, true) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(PostDominatorTree) INITIALIZE_PASS_DEPENDENCY(DominanceFrontier) INITIALIZE_PASS_END(RegionInfoPass, "regions", "Detect single entry single exit regions", true, true) // Create methods available outside of this file, to use them // "include/llvm/LinkAllPasses.h". Otherwise the pass would be deleted by // the link time optimization. namespace llvm { FunctionPass *createRegionInfoPass() { return new RegionInfoPass(); } } <|endoftext|>
<commit_before>// Copyright 2014 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 "content/renderer/scheduler/renderer_scheduler.h" #include "content/renderer/scheduler/null_renderer_scheduler.h" namespace content { RendererScheduler::RendererScheduler() { } RendererScheduler::~RendererScheduler() { } // static scoped_ptr<RendererScheduler> RendererScheduler::Create() { // TODO(rmcilroy): Use the RendererSchedulerImpl when the scheduler is enabled return make_scoped_ptr(new NullRendererScheduler()); } } // namespace content <commit_msg>content: Enable the RendererScheduler by default.<commit_after>// Copyright 2014 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 "content/renderer/scheduler/renderer_scheduler.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "content/public/common/content_switches.h" #include "content/renderer/scheduler/null_renderer_scheduler.h" #include "content/renderer/scheduler/renderer_scheduler_impl.h" namespace content { RendererScheduler::RendererScheduler() { } RendererScheduler::~RendererScheduler() { } // static scoped_ptr<RendererScheduler> RendererScheduler::Create() { CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableBlinkScheduler)) { return make_scoped_ptr(new NullRendererScheduler()); } else { return make_scoped_ptr( new RendererSchedulerImpl(base::MessageLoopProxy::current())); } } } // namespace content <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2017 Vasily Khoruzhick 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 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 */ #include "rawspeedconfig.h" #ifdef HAVE_ZLIB #include "common/FloatingPoint.h" // for fp16ToFloat, fp24ToFloat #include "common/Point.h" // for iPoint2D #include "decoders/RawDecoderException.h" // for ThrowRDE #include "decompressors/DeflateDecompressor.h" #include "io/Endianness.h" // for getHostEndianness, Endianness #include <cassert> // for assert #include <cstdint> // for uint32_t, uint16_t #include <cstdio> // for size_t #include <zlib.h> // for uncompress, zError, Z_OK namespace rawspeed { // decodeFPDeltaRow(): MIT License, copyright 2014 Javier Celaya // <jcelaya@gmail.com> static inline void decodeFPDeltaRow(unsigned char* src, unsigned char* dst, size_t tileWidth, size_t realTileWidth, unsigned int bytesps, int factor) { // DecodeDeltaBytes for (size_t col = factor; col < realTileWidth * bytesps; ++col) { // Yes, this is correct, and is symmetrical with EncodeDeltaBytes in // hdrmerge, and they both combined are lossless. // This is indeed working in modulo-2^n arighmetics. src[col] = static_cast<unsigned char>(src[col] + src[col - factor]); } // Reorder bytes into the image // 16 and 32-bit versions depend on local architecture, 24-bit does not if (bytesps == 3) { for (size_t col = 0; col < tileWidth; ++col) { dst[col * 3] = src[col]; dst[col * 3 + 1] = src[col + realTileWidth]; dst[col * 3 + 2] = src[col + realTileWidth * 2]; } } else { if (getHostEndianness() == Endianness::little) { for (size_t col = 0; col < tileWidth; ++col) { for (size_t byte = 0; byte < bytesps; ++byte) dst[col * bytesps + byte] = src[col + realTileWidth * (bytesps - byte - 1)]; } } else { for (size_t col = 0; col < tileWidth; ++col) { for (size_t byte = 0; byte < bytesps; ++byte) dst[col * bytesps + byte] = src[col + realTileWidth * byte]; } } } } static inline void expandFP16(unsigned char* src, unsigned char* dst, int width) { const auto* src16 = reinterpret_cast<uint16_t*>(src); auto* dst32 = reinterpret_cast<uint32_t*>(dst); for (int x = width - 1; x >= 0; x--) dst32[x] = fp16ToFloat(src16[x]); } static inline void expandFP24(unsigned char* src, unsigned char* dst, int width) { const auto* src8 = reinterpret_cast<uint8_t*>(src); auto* dst32 = reinterpret_cast<uint32_t*>(dst); for (int x = width - 1; x >= 0; x--) dst32[x] = fp24ToFloat((src8[3 * x + 0] << 16) | (src8[3 * x + 1] << 8) | src8[3 * x + 2]); } void DeflateDecompressor::decode( std::unique_ptr<unsigned char[]>* uBuffer, // NOLINT iPoint2D maxDim, iPoint2D dim, iPoint2D off) { uLongf dstLen = sizeof(float) * maxDim.area(); if (!*uBuffer) *uBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[dstLen]); // NOLINT const auto cSize = input.getRemainSize(); const unsigned char* cBuffer = input.getData(cSize); if (int err = uncompress(uBuffer->get(), &dstLen, cBuffer, cSize); err != Z_OK) { ThrowRDE("failed to uncompress tile: %d (%s)", err, zError(err)); } int predFactor = 0; switch (predictor) { case 3: predFactor = 1; break; case 34894: predFactor = 2; break; case 34895: predFactor = 4; break; default: predFactor = 0; break; } predFactor *= mRaw->getCpp(); int bytesps = bps / 8; std::vector<unsigned char> tmp_storage; if (predFactor && bytesps != 4) tmp_storage.resize(bytesps * dim.x); for (auto row = 0; row < dim.y; ++row) { unsigned char* src = uBuffer->get() + row * maxDim.x * bytesps; unsigned char* dst = mRaw->getData() + ((off.y + row) * mRaw->pitch + off.x * sizeof(float)); unsigned char* tmp = dst; if (predFactor) { if (bytesps != 4) tmp = tmp_storage.data(); decodeFPDeltaRow(src, tmp, dim.x, maxDim.x, bytesps, predFactor); } assert(bytesps >= 2 && bytesps <= 4); switch (bytesps) { case 2: expandFP16(tmp, dst, dim.x); break; case 3: expandFP24(tmp, dst, dim.x); break; case 4: // No need to expand FP32 break; default: __builtin_unreachable(); } } } } // namespace rawspeed #else #pragma message \ "ZLIB is not present! Deflate compression will not be supported!" #endif <commit_msg>`DeflateDecompressor::expandFP*()`: use forward-direction loops<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2017 Vasily Khoruzhick 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 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 */ #include "rawspeedconfig.h" #ifdef HAVE_ZLIB #include "common/FloatingPoint.h" // for fp16ToFloat, fp24ToFloat #include "common/Point.h" // for iPoint2D #include "decoders/RawDecoderException.h" // for ThrowRDE #include "decompressors/DeflateDecompressor.h" #include "io/Endianness.h" // for getHostEndianness, Endianness #include <cassert> // for assert #include <cstdint> // for uint32_t, uint16_t #include <cstdio> // for size_t #include <zlib.h> // for uncompress, zError, Z_OK namespace rawspeed { // decodeFPDeltaRow(): MIT License, copyright 2014 Javier Celaya // <jcelaya@gmail.com> static inline void decodeFPDeltaRow(unsigned char* src, unsigned char* dst, size_t tileWidth, size_t realTileWidth, unsigned int bytesps, int factor) { // DecodeDeltaBytes for (size_t col = factor; col < realTileWidth * bytesps; ++col) { // Yes, this is correct, and is symmetrical with EncodeDeltaBytes in // hdrmerge, and they both combined are lossless. // This is indeed working in modulo-2^n arighmetics. src[col] = static_cast<unsigned char>(src[col] + src[col - factor]); } // Reorder bytes into the image // 16 and 32-bit versions depend on local architecture, 24-bit does not if (bytesps == 3) { for (size_t col = 0; col < tileWidth; ++col) { dst[col * 3] = src[col]; dst[col * 3 + 1] = src[col + realTileWidth]; dst[col * 3 + 2] = src[col + realTileWidth * 2]; } } else { if (getHostEndianness() == Endianness::little) { for (size_t col = 0; col < tileWidth; ++col) { for (size_t byte = 0; byte < bytesps; ++byte) dst[col * bytesps + byte] = src[col + realTileWidth * (bytesps - byte - 1)]; } } else { for (size_t col = 0; col < tileWidth; ++col) { for (size_t byte = 0; byte < bytesps; ++byte) dst[col * bytesps + byte] = src[col + realTileWidth * byte]; } } } } static inline void expandFP16(unsigned char* src, unsigned char* dst, int width) { const auto* src16 = reinterpret_cast<uint16_t*>(src); auto* dst32 = reinterpret_cast<uint32_t*>(dst); for (int x = 0; x < width; x++) dst32[x] = fp16ToFloat(src16[x]); } static inline void expandFP24(unsigned char* src, unsigned char* dst, int width) { const auto* src8 = reinterpret_cast<uint8_t*>(src); auto* dst32 = reinterpret_cast<uint32_t*>(dst); for (int x = 0; x < width; x++) dst32[x] = fp24ToFloat((src8[3 * x + 0] << 16) | (src8[3 * x + 1] << 8) | src8[3 * x + 2]); } void DeflateDecompressor::decode( std::unique_ptr<unsigned char[]>* uBuffer, // NOLINT iPoint2D maxDim, iPoint2D dim, iPoint2D off) { uLongf dstLen = sizeof(float) * maxDim.area(); if (!*uBuffer) *uBuffer = std::unique_ptr<unsigned char[]>(new unsigned char[dstLen]); // NOLINT const auto cSize = input.getRemainSize(); const unsigned char* cBuffer = input.getData(cSize); if (int err = uncompress(uBuffer->get(), &dstLen, cBuffer, cSize); err != Z_OK) { ThrowRDE("failed to uncompress tile: %d (%s)", err, zError(err)); } int predFactor = 0; switch (predictor) { case 3: predFactor = 1; break; case 34894: predFactor = 2; break; case 34895: predFactor = 4; break; default: predFactor = 0; break; } predFactor *= mRaw->getCpp(); int bytesps = bps / 8; std::vector<unsigned char> tmp_storage; if (predFactor && bytesps != 4) tmp_storage.resize(bytesps * dim.x); for (auto row = 0; row < dim.y; ++row) { unsigned char* src = uBuffer->get() + row * maxDim.x * bytesps; unsigned char* dst = mRaw->getData() + ((off.y + row) * mRaw->pitch + off.x * sizeof(float)); unsigned char* tmp = dst; if (predFactor) { if (bytesps != 4) tmp = tmp_storage.data(); decodeFPDeltaRow(src, tmp, dim.x, maxDim.x, bytesps, predFactor); } assert(bytesps >= 2 && bytesps <= 4); switch (bytesps) { case 2: expandFP16(tmp, dst, dim.x); break; case 3: expandFP24(tmp, dst, dim.x); break; case 4: // No need to expand FP32 break; default: __builtin_unreachable(); } } } } // namespace rawspeed #else #pragma message \ "ZLIB is not present! Deflate compression will not be supported!" #endif <|endoftext|>
<commit_before>#ifndef TYPES_HPP_1AMW8QS7 #define TYPES_HPP_1AMW8QS7 #include "../domains/types.hpp" /************** * Triangular * **************/ typedef viennagrid::result_of::element<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian2D_Vertex_t; typedef viennagrid::result_of::handle<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian2D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian2D_VertexRange_t; typedef viennagrid::result_of::element<TriangularCartesian3D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian3D_Vertex_t; typedef viennagrid::result_of::handle<TriangularCartesian3D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian3D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian3D_VertexRange_t; typedef viennagrid::result_of::element<TriangularCylindrical3D_Domain_t, viennagrid::vertex_tag>::type TriangularCylindrical3D_Vertex_t; typedef viennagrid::result_of::handle<TriangularCylindrical3D_Domain_t, viennagrid::vertex_tag>::type TriangularCylindrical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCylindrical3D_VertexRange_t; typedef viennagrid::result_of::element<TriangularPolar2D_Domain_t, viennagrid::vertex_tag>::type TriangularPolar2D_Vertex_t; typedef viennagrid::result_of::handle<TriangularPolar2D_Domain_t, viennagrid::vertex_tag>::type TriangularPolar2D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularPolar2D_VertexRange_t; typedef viennagrid::result_of::element<TriangularSpherical3D_Domain_t, viennagrid::vertex_tag>::type TriangularSpherical3D_Vertex_t; typedef viennagrid::result_of::handle<TriangularSpherical3D_Domain_t, viennagrid::vertex_tag>::type TriangularSpherical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularSpherical3D_VertexRange_t; /***************** * Quadrilateral * *****************/ typedef viennagrid::result_of::element<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian2D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian2D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian2D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralCartesian3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian3D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralCartesian3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian3D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian3D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralCylindrical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCylindrical3D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralCylindrical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCylindrical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCylindrical3D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralPolar2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralPolar2D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralPolar2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralPolar2D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralPolar2D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralSpherical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralSpherical3D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralSpherical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralSpherical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralSpherical3D_VertexRange_t; #endif /* end of include guard: TYPES_HPP_1AMW8QS7 */ <commit_msg>Fix 'vertices/types.hpp'.<commit_after>#ifndef TYPES_HPP_1AMW8QS7 #define TYPES_HPP_1AMW8QS7 #include "../domains/types.hpp" /************** * Triangular * **************/ typedef viennagrid::result_of::element<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian2D_Vertex_t; typedef viennagrid::result_of::handle<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian2D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian2D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian2D_VertexRange_t; typedef viennagrid::result_of::element<TriangularCartesian3D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian3D_Vertex_t; typedef viennagrid::result_of::handle<TriangularCartesian3D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian3D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCartesian3D_Domain_t, viennagrid::vertex_tag>::type TriangularCartesian3D_VertexRange_t; typedef viennagrid::result_of::element<TriangularCylindrical3D_Domain_t, viennagrid::vertex_tag>::type TriangularCylindrical3D_Vertex_t; typedef viennagrid::result_of::handle<TriangularCylindrical3D_Domain_t, viennagrid::vertex_tag>::type TriangularCylindrical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularCylindrical3D_Domain_t, viennagrid::vertex_tag>::type TriangularCylindrical3D_VertexRange_t; typedef viennagrid::result_of::element<TriangularPolar2D_Domain_t, viennagrid::vertex_tag>::type TriangularPolar2D_Vertex_t; typedef viennagrid::result_of::handle<TriangularPolar2D_Domain_t, viennagrid::vertex_tag>::type TriangularPolar2D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularPolar2D_Domain_t, viennagrid::vertex_tag>::type TriangularPolar2D_VertexRange_t; typedef viennagrid::result_of::element<TriangularSpherical3D_Domain_t, viennagrid::vertex_tag>::type TriangularSpherical3D_Vertex_t; typedef viennagrid::result_of::handle<TriangularSpherical3D_Domain_t, viennagrid::vertex_tag>::type TriangularSpherical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<TriangularSpherical3D_Domain_t, viennagrid::vertex_tag>::type TriangularSpherical3D_VertexRange_t; /***************** * Quadrilateral * *****************/ typedef viennagrid::result_of::element<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian2D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian2D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian2D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralCartesian3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian3D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralCartesian3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian3D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCartesian3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCartesian3D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralCylindrical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCylindrical3D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralCylindrical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCylindrical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralCylindrical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralCylindrical3D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralPolar2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralPolar2D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralPolar2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralPolar2D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralPolar2D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralPolar2D_VertexRange_t; typedef viennagrid::result_of::element<QuadrilateralSpherical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralSpherical3D_Vertex_t; typedef viennagrid::result_of::handle<QuadrilateralSpherical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralSpherical3D_VertexHandle_t; typedef viennagrid::result_of::element_range<QuadrilateralSpherical3D_Domain_t, viennagrid::vertex_tag>::type QuadrilateralSpherical3D_VertexRange_t; #endif /* end of include guard: TYPES_HPP_1AMW8QS7 */ <|endoftext|>
<commit_before>--- src/tekcoinrpc.cpp.orig 2016-03-24 15:19:15 UTC +++ src/tekcoinrpc.cpp @@ -654,8 +654,8 @@ void ThreadRPCServer(void* parg) } // Forward declaration required for RPCListen -template <typename Protocol, typename SocketAcceptorService> -static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, +template <typename Protocol> +static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protoco> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, @@ -664,8 +664,8 @@ static void RPCAcceptHandler(boost::shar /** * Sets up I/O resources to accept and handle a new connection. */ -template <typename Protocol, typename SocketAcceptorService> -static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, +template <typename Protocol> +static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, ssl::context& context, const bool fUseSSL) { @@ -675,7 +675,7 @@ static void RPCListen(boost::shared_ptr< acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, - boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, + boost::bind(&RPCAcceptHandler<Protocol>, acceptor, boost::ref(context), fUseSSL, @@ -686,8 +686,8 @@ static void RPCListen(boost::shared_ptr< /** * Accept and handle incoming connection. */ -template <typename Protocol, typename SocketAcceptorService> -static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, +template <typename Protocol> +static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, @@ -762,7 +762,7 @@ void ThreadRPCServer2(void* parg) asio::io_service io_service; - ssl::context context(io_service, ssl::context::sslv23); + ssl::context context(ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); @@ -778,7 +778,7 @@ void ThreadRPCServer2(void* parg) else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); - SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); + SSL_CTX_set_cipher_list(context.native_handle(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets @@ -1072,7 +1072,7 @@ Object CallRPC(const string& strMethod, // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; - ssl::context context(io_service, ssl::context::sslv23); + ssl::context context(ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); <commit_msg>Fix build for boost 1.66<commit_after>--- src/tekcoinrpc.cpp.orig 2016-03-24 15:19:15 UTC +++ src/tekcoinrpc.cpp @@ -654,8 +654,8 @@ void ThreadRPCServer(void* parg) } // Forward declaration required for RPCListen -template <typename Protocol, typename SocketAcceptorService> -static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, +template <typename Protocol> +static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, @@ -664,8 +664,8 @@ static void RPCAcceptHandler(boost::shar /** * Sets up I/O resources to accept and handle a new connection. */ -template <typename Protocol, typename SocketAcceptorService> -static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, +template <typename Protocol> +static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, ssl::context& context, const bool fUseSSL) { @@ -675,7 +675,7 @@ static void RPCListen(boost::shared_ptr< acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, - boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, + boost::bind(&RPCAcceptHandler<Protocol>, acceptor, boost::ref(context), fUseSSL, @@ -686,8 +686,8 @@ static void RPCListen(boost::shared_ptr< /** * Accept and handle incoming connection. */ -template <typename Protocol, typename SocketAcceptorService> -static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, +template <typename Protocol> +static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, @@ -762,7 +762,7 @@ void ThreadRPCServer2(void* parg) asio::io_service io_service; - ssl::context context(io_service, ssl::context::sslv23); + ssl::context context(ssl::context::sslv23); if (fUseSSL) { context.set_options(ssl::context::no_sslv2); @@ -778,7 +778,7 @@ void ThreadRPCServer2(void* parg) else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); - SSL_CTX_set_cipher_list(context.impl(), strCiphers.c_str()); + SSL_CTX_set_cipher_list(context.native_handle(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets @@ -1072,7 +1072,7 @@ Object CallRPC(const string& strMethod, // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; - ssl::context context(io_service, ssl::context::sslv23); + ssl::context context(ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); <|endoftext|>
<commit_before>/* * GroupBulkRead.cpp * * Created on: 2016. 1. 28. * Author: zerom, leon */ #if defined(_WIN32) || defined(_WIN64) #define WINDLLEXPORT #endif #include <stdio.h> #include <algorithm> #include "dynamixel_sdk/GroupBulkRead.h" using namespace ROBOTIS; GroupBulkRead::GroupBulkRead(PortHandler *port, PacketHandler *ph) : port_(port), ph_(ph), last_result_(false), is_param_changed_(false), param_(0) { ClearParam(); } void GroupBulkRead::MakeParam() { if(id_list_.size() == 0) return; if(param_ != 0) delete[] param_; param_ = 0; if(ph_->GetProtocolVersion() == 1.0) param_ = new UINT8_T[id_list_.size() * 3]; // ID(1) + ADDR(1) + LENGTH(1) else // 2.0 param_ = new UINT8_T[id_list_.size() * 5]; // ID(1) + ADDR(2) + LENGTH(2) int _idx = 0; for(unsigned int _i = 0; _i < id_list_.size(); _i++) { UINT8_T _id = id_list_[_i]; if(ph_->GetProtocolVersion() == 1.0) { param_[_idx++] = (UINT8_T)length_list_[_id]; // LEN param_[_idx++] = _id; // ID param_[_idx++] = (UINT8_T)address_list_[_id]; // ADDR } else // 2.0 { param_[_idx++] = _id; // ID param_[_idx++] = DXL_LOBYTE(address_list_[_id]); // ADDR_L param_[_idx++] = DXL_HIBYTE(address_list_[_id]); // ADDR_H param_[_idx++] = DXL_LOBYTE(length_list_[_id]); // LEN_L param_[_idx++] = DXL_HIBYTE(length_list_[_id]); // LEN_H } } } bool GroupBulkRead::AddParam(UINT8_T id, UINT16_T start_address, UINT16_T data_length) { if(std::find(id_list_.begin(), id_list_.end(), id) != id_list_.end()) // id already exist return false; id_list_.push_back(id); length_list_[id] = data_length; address_list_[id] = start_address; data_list_[id] = new UINT8_T[data_length]; is_param_changed_ = true; return true; } void GroupBulkRead::RemoveParam(UINT8_T id) { std::vector<UINT8_T>::iterator it = std::find(id_list_.begin(), id_list_.end(), id); if(it == id_list_.end()) // NOT exist return; id_list_.erase(it); address_list_.erase(id); length_list_.erase(id); delete[] data_list_[id]; data_list_.erase(id); is_param_changed_ = true; } void GroupBulkRead::ClearParam() { if(id_list_.size() == 0) return; for(unsigned int _i = 0; _i < id_list_.size(); _i++) delete[] data_list_[id_list_[_i]]; id_list_.clear(); address_list_.clear(); length_list_.clear(); data_list_.clear(); if(param_ != 0) delete[] param_; param_ = 0; } int GroupBulkRead::TxPacket() { if(id_list_.size() == 0) return COMM_NOT_AVAILABLE; if(is_param_changed_ == true) MakeParam(); if(ph_->GetProtocolVersion() == 1.0) return ph_->BulkReadTx(port_, param_, id_list_.size() * 3); else // 2.0 return ph_->BulkReadTx(port_, param_, id_list_.size() * 5); } int GroupBulkRead::RxPacket() { int _cnt = id_list_.size(); int _result = COMM_RX_FAIL; last_result_ = false; if(_cnt == 0) return COMM_NOT_AVAILABLE; for(int _i = 0; _i < _cnt; _i++) { UINT8_T _id = id_list_[_i]; _result = ph_->ReadRx(port_, length_list_[_id], data_list_[_id]); if(_result != COMM_SUCCESS) { fprintf(stderr, "[GroupBulkRead::RxPacket] ID %d result : %d !!!!!!!!!!\n", _id, _result); return _result; } } if(_result == COMM_SUCCESS) last_result_ = true; return _result; } int GroupBulkRead::TxRxPacket() { int _result = COMM_TX_FAIL; _result = TxPacket(); if(_result != COMM_SUCCESS) return _result; return RxPacket(); } bool GroupBulkRead::IsAvailable(UINT8_T id, UINT16_T address, UINT16_T data_length) { UINT16_T _start_addr, _data_length; if(last_result_ == false || data_list_.find(id) == data_list_.end()) return false; _start_addr = address_list_[id]; _data_length = length_list_[id]; if(address < _start_addr || _start_addr + _data_length - data_length < address) return false; return true; } UINT32_T GroupBulkRead::GetData(UINT8_T id, UINT16_T address, UINT16_T data_length) { if(IsAvailable(id, address, data_length) == false) return 0; UINT16_T _start_addr = address_list_[id]; switch(data_length) { case 1: return data_list_[id][address - _start_addr]; case 2: return DXL_MAKEWORD(data_list_[id][address - _start_addr], data_list_[id][address - _start_addr + 1]); case 4: return DXL_MAKEDWORD(DXL_MAKEWORD(data_list_[id][address - _start_addr + 0], data_list_[id][address - _start_addr + 1]), DXL_MAKEWORD(data_list_[id][address - _start_addr + 2], data_list_[id][address - _start_addr + 3])); default: return 0; } } <commit_msg>removed error spam<commit_after>/* * GroupBulkRead.cpp * * Created on: 2016. 1. 28. * Author: zerom, leon */ #if defined(_WIN32) || defined(_WIN64) #define WINDLLEXPORT #endif #include <stdio.h> #include <algorithm> #include "dynamixel_sdk/GroupBulkRead.h" using namespace ROBOTIS; GroupBulkRead::GroupBulkRead(PortHandler *port, PacketHandler *ph) : port_(port), ph_(ph), last_result_(false), is_param_changed_(false), param_(0) { ClearParam(); } void GroupBulkRead::MakeParam() { if(id_list_.size() == 0) return; if(param_ != 0) delete[] param_; param_ = 0; if(ph_->GetProtocolVersion() == 1.0) param_ = new UINT8_T[id_list_.size() * 3]; // ID(1) + ADDR(1) + LENGTH(1) else // 2.0 param_ = new UINT8_T[id_list_.size() * 5]; // ID(1) + ADDR(2) + LENGTH(2) int _idx = 0; for(unsigned int _i = 0; _i < id_list_.size(); _i++) { UINT8_T _id = id_list_[_i]; if(ph_->GetProtocolVersion() == 1.0) { param_[_idx++] = (UINT8_T)length_list_[_id]; // LEN param_[_idx++] = _id; // ID param_[_idx++] = (UINT8_T)address_list_[_id]; // ADDR } else // 2.0 { param_[_idx++] = _id; // ID param_[_idx++] = DXL_LOBYTE(address_list_[_id]); // ADDR_L param_[_idx++] = DXL_HIBYTE(address_list_[_id]); // ADDR_H param_[_idx++] = DXL_LOBYTE(length_list_[_id]); // LEN_L param_[_idx++] = DXL_HIBYTE(length_list_[_id]); // LEN_H } } } bool GroupBulkRead::AddParam(UINT8_T id, UINT16_T start_address, UINT16_T data_length) { if(std::find(id_list_.begin(), id_list_.end(), id) != id_list_.end()) // id already exist return false; id_list_.push_back(id); length_list_[id] = data_length; address_list_[id] = start_address; data_list_[id] = new UINT8_T[data_length]; is_param_changed_ = true; return true; } void GroupBulkRead::RemoveParam(UINT8_T id) { std::vector<UINT8_T>::iterator it = std::find(id_list_.begin(), id_list_.end(), id); if(it == id_list_.end()) // NOT exist return; id_list_.erase(it); address_list_.erase(id); length_list_.erase(id); delete[] data_list_[id]; data_list_.erase(id); is_param_changed_ = true; } void GroupBulkRead::ClearParam() { if(id_list_.size() == 0) return; for(unsigned int _i = 0; _i < id_list_.size(); _i++) delete[] data_list_[id_list_[_i]]; id_list_.clear(); address_list_.clear(); length_list_.clear(); data_list_.clear(); if(param_ != 0) delete[] param_; param_ = 0; } int GroupBulkRead::TxPacket() { if(id_list_.size() == 0) return COMM_NOT_AVAILABLE; if(is_param_changed_ == true) MakeParam(); if(ph_->GetProtocolVersion() == 1.0) return ph_->BulkReadTx(port_, param_, id_list_.size() * 3); else // 2.0 return ph_->BulkReadTx(port_, param_, id_list_.size() * 5); } int GroupBulkRead::RxPacket() { int _cnt = id_list_.size(); int _result = COMM_RX_FAIL; last_result_ = false; if(_cnt == 0) return COMM_NOT_AVAILABLE; for(int _i = 0; _i < _cnt; _i++) { UINT8_T _id = id_list_[_i]; _result = ph_->ReadRx(port_, length_list_[_id], data_list_[_id]); if(_result != COMM_SUCCESS) { //fprintf(stderr, "[GroupBulkRead::RxPacket] ID %d result : %d !!!!!!!!!!\n", _id, _result); return _result; } } if(_result == COMM_SUCCESS) last_result_ = true; return _result; } int GroupBulkRead::TxRxPacket() { int _result = COMM_TX_FAIL; _result = TxPacket(); if(_result != COMM_SUCCESS) return _result; return RxPacket(); } bool GroupBulkRead::IsAvailable(UINT8_T id, UINT16_T address, UINT16_T data_length) { UINT16_T _start_addr, _data_length; if(last_result_ == false || data_list_.find(id) == data_list_.end()) return false; _start_addr = address_list_[id]; _data_length = length_list_[id]; if(address < _start_addr || _start_addr + _data_length - data_length < address) return false; return true; } UINT32_T GroupBulkRead::GetData(UINT8_T id, UINT16_T address, UINT16_T data_length) { if(IsAvailable(id, address, data_length) == false) return 0; UINT16_T _start_addr = address_list_[id]; switch(data_length) { case 1: return data_list_[id][address - _start_addr]; case 2: return DXL_MAKEWORD(data_list_[id][address - _start_addr], data_list_[id][address - _start_addr + 1]); case 4: return DXL_MAKEDWORD(DXL_MAKEWORD(data_list_[id][address - _start_addr + 0], data_list_[id][address - _start_addr + 1]), DXL_MAKEWORD(data_list_[id][address - _start_addr + 2], data_list_[id][address - _start_addr + 3])); default: return 0; } } <|endoftext|>
<commit_before>#include "TTModular.h" #include "TTScore.h" #include <iostream> #include <string> // A class for our application class DemoApp { public: DemoApp(){}; ~DemoApp(){}; // This application is divided into four main functions void SetupModular(); void SetupScore(); void SetMessage(std::string s); void Quit(); private: // Declare the application manager and our application TTObject mApplicationManager; TTObject mApplicationDemo; // Declare callbacks used to observe scenario execution TTObject mEventStatusChangedCallback; // Declare a thread used to poll information about scenario execution at another rate TTThread* mPollingThread; public: // Declare publicly all datas of our application to retreive them from the callback function TTObject mDataDemoParameter; // a parameter is relative to the state of our application TTObject mDataDemoMessage; // a message is a kind of command to send to our application TTObject mDataDemoReturn; // a return is a kind of notification sent by our application // Declare publicly the scenario to retreive it from the callback function TTObject mScenario; // Be friend with each callback or function friend TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value); friend TTErr DemoAppEventStatusChangedCallback(const TTValue& baton, const TTValue& value); friend void DemoAppScenarioPollingThread(DemoApp* demoApp); }; // Callback function to get data's value back TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value); // Callback function to be notified when an event status is changing TTErr DemoAppEventStatusChangedCallback(const TTValue& baton, const TTValue& value); // Function to poll information about scenario execution at another rate void DemoAppScenarioPollingThread(DemoApp* demoApp); int main(int argc, char **argv) { DemoApp app; TTLogMessage("\n*** Start of Jamoma Modular and Score demonstration ***\n"); app.SetupModular(); app.SetupScore(); // read command from console do { TTLogMessage("\nType a command : \n"); std::string s; std::getline(std::cin, s); // quit the application if (!s.compare("quit")) { app.Quit(); TTLogMessage("\n*** End of Jamoma Modular and Score demonstration ***\n"); return EXIT_SUCCESS; } // update mDataDemoMessage data with the command else { app.SetMessage(s); } } while (YES); } void DemoApp::SetupModular() { TTValue args; TTLogMessage("\n*** Initialisation of Modular environnement ***\n"); ///////////////////////////////////////////////////////////////////// // Init the Modular library (passing the folder path where all the dylibs are) TTModularInit("/usr/local/jamoma/extensions"); // Create an application manager mApplicationManager = TTObject("ApplicationManager"); TTLogMessage("\n*** Creation of mApplicationDemo application ***\n"); ///////////////////////////////////////////////////////////////////// // Create a local application called "demo" and get it back mApplicationDemo = mApplicationManager.send("ApplicationInstantiateLocal", "demo"); if (!mApplicationDemo.valid()) { TTLogError("Error : can't create demo application \n"); return; } TTLogMessage("\n*** Creation of mApplicationDemo datas ***\n"); ///////////////////////////////////////////////////////////////////// // Create a parameter data and set its callback function and baton and some attributes mDataDemoParameter = TTObject("Data", "parameter"); // Setup the callback mechanism to get the value back args = TTValue(TTPtr(this), mDataDemoParameter); mDataDemoParameter.set("baton", args); mDataDemoParameter.set("function", TTPtr(&DemoAppDataReturnValueCallback)); // Setup the data attributes depending of its use inside the application mDataDemoParameter.set("type", "decimal"); mDataDemoParameter.set("rangeBounds", TTValue(0., 1.)); mDataDemoParameter.set("rangeClipmode", "low"); mDataDemoParameter.set("description", "any information relative to the state of the application"); // Register the parameter data into mApplicationDemo at an address args = TTValue("/myParameter", mDataDemoParameter); mApplicationDemo.send("ObjectRegister", args); // Create a message data and set its callback function and baton and some attributes mDataDemoMessage = TTObject("Data", "message"); // Setup the callback mechanism to get the value back args = TTValue(TTPtr(this), mDataDemoMessage); mDataDemoMessage.set("baton", args); mDataDemoMessage.set("function", TTPtr(&DemoAppDataReturnValueCallback)); // Setup the data attributes depending of its use inside the application mDataDemoMessage.set("type", "string"); mDataDemoMessage.set("description", "any information to provide to the application"); // Register the message data into mApplicationDemo at an address args = TTValue("/myMessage", mDataDemoMessage); mApplicationDemo.send("ObjectRegister", args); // Create a return data and set its callback function and baton and some attributes mDataDemoReturn = TTObject("Data", "return"); // Setup the callback mechanism to get the value back args = TTValue(TTPtr(this), mDataDemoReturn); mDataDemoReturn.set("baton", args); mDataDemoReturn.set("function", TTPtr(&DemoAppDataReturnValueCallback)); // Setup the data attributes depending of its use inside the application mDataDemoReturn.set("type", "integer"); mDataDemoReturn.set("defaultValue", 0); mDataDemoReturn.set("description", "any information the application returns back"); // Register the return data into mApplicationDemo at an address args = TTValue("/myReturn", mDataDemoReturn); mApplicationDemo.send("ObjectRegister", args); // Initialise the application and all datas inside (using defaultValue attribute) mApplicationDemo.send("Init"); } void DemoApp::SetupScore() { TTObject xmlHandler("XmlHandler"); TTLogMessage("\n*** Initialisation of Score environnement ***\n"); ///////////////////////////////////////////////////////////////////// // Init the Score library (passing the folder path where all the dylibs are) TTScoreInit("/usr/local/jamoma/extensions"); TTLogMessage("\n*** Reading of an interactive scenario file ***\n"); ///////////////////////////////////////////////////////////////////// // Create an empty Scenario mScenario = TTObject("Scenario"); // Read DemoScenario1.score file to fill mScenario xmlHandler.set("object", mScenario); xmlHandler.send("Read", "../DemoScenario.score"); TTLogMessage("\n*** Prepare scenario observation ***\n"); ///////////////////////////////////////////////////////////////////// // Create a callback for the "EventStatusChanged" notification sent by each event mEventStatusChangedCallback = TTObject("callback"); mEventStatusChangedCallback.set("baton", TTPtr(this)); mEventStatusChangedCallback.set("function", TTPtr(&DemoAppEventStatusChangedCallback)); mEventStatusChangedCallback.set("notification", TTSymbol("EventStatusChanged")); // Get all events of the scenario and attach a callback to them TTValue timeEvents; mScenario.get("timeEvents", timeEvents); for (TTElementIter it = timeEvents.begin() ; it != timeEvents.end() ; it++) { TTObject event = TTElement(*it); event.registerObserverForNotifications(mEventStatusChangedCallback); } TTLogMessage("\n*** Start scenario execution ***\n"); ///////////////////////////////////////////////////////////////////// // Set the execution speed of the scenario mScenario.set("speed", 2.); // Start the scenario mScenario.send("Start"); // Poll Scenario information mPollingThread = new TTThread(TTThreadCallbackType(DemoAppScenarioPollingThread), this); } void DemoApp::SetMessage(std::string s) { TTSymbol message(s); mDataDemoMessage.send("Command", message); } void DemoApp::Quit() { TTLogMessage("\n*** Release mApplicationDemo datas ***\n"); ///////////////////////////////////////////////////////////////////// // Unregister the parameter if ( mApplicationDemo.send("ObjectUnregister", "/myParameter")) TTLogError("Error : can't unregister data at /myParameter address \n"); // Unregister the message if (mApplicationDemo.send("ObjectUnregister", "/myMessage")) TTLogError("Error : can't unregister data at /myMessage address \n"); // Unregister the return if (mApplicationDemo.send("ObjectUnregister", "/myReturn")) TTLogError("Error : can't unregister data at /myReturn address \n"); TTLogMessage("\n*** Release application ***\n"); ///////////////////////////////////////////////////////////////////// mApplicationManager.send("ApplicationRelease", "demo"); // delete the polling thread if (mPollingThread) mPollingThread->wait(); delete mPollingThread; } TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value) { DemoApp* demoApp = (DemoApp*)TTPtr(baton[0]); TTObject anObject = baton[1]; // Reteive which data has been updated if (anObject.instance() == demoApp->mDataDemoParameter.instance()) { // print the returned value TTLogMessage("/myParameter has been updated to %s \n", value.toString().data()); return kTTErrNone; } if (anObject.instance() == demoApp->mDataDemoMessage.instance()) { // print the returned value TTLogMessage("/myMessage has been updated to %s \n", value.toString().data()); return kTTErrNone; } if (anObject.instance() == demoApp->mDataDemoReturn.instance()) { // print the returned value TTLogMessage("/myReturn has been updated to %s \n", value.toString().data()); return kTTErrNone; } return kTTErrGeneric; } TTErr DemoAppEventStatusChangedCallback(const TTValue& baton, const TTValue& value) { DemoApp* demoApp = (DemoApp*)TTPtr(baton[0]); TTObject event = value[0]; TTSymbol newStatus = value[1]; TTSymbol oldStatus = value[2]; // get the name of the event TTSymbol name; event.get("name", name); // print the event status TTLogMessage("%s status : %s \n", name.c_str(), newStatus.c_str()); return kTTErrNone; } void DemoAppScenarioPollingThread(DemoApp* demoApp) { TTBoolean isRunning; do { // wait demoApp->mPollingThread->sleep(1); // look at the running state of the scnario demoApp->mScenario.get("running", isRunning); } while (isRunning); // quit DemoApp demoApp->Quit(); }<commit_msg>exiting the program properly<commit_after>#include "TTModular.h" #include "TTScore.h" #include <iostream> #include <string> // A class for our application class DemoApp { public: DemoApp(){}; ~DemoApp(){}; // This application is divided into four main functions void SetupModular(); void SetupScore(); void SetMessage(std::string s); void Quit(); private: // Declare the application manager and our application TTObject mApplicationManager; TTObject mApplicationDemo; // Declare callbacks used to observe scenario execution TTObject mEventStatusChangedCallback; // Declare a thread used to poll information about scenario execution at another rate TTThread* mPollingThread; public: // Declare publicly all datas of our application to retreive them from the callback function TTObject mDataDemoParameter; // a parameter is relative to the state of our application TTObject mDataDemoMessage; // a message is a kind of command to send to our application TTObject mDataDemoReturn; // a return is a kind of notification sent by our application // Declare publicly the scenario to retreive it from the callback function TTObject mScenario; // Be friend with each callback or function friend TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value); friend TTErr DemoAppEventStatusChangedCallback(const TTValue& baton, const TTValue& value); friend void DemoAppScenarioPollingThread(DemoApp* demoApp); }; // Callback function to get data's value back TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value); // Callback function to be notified when an event status is changing TTErr DemoAppEventStatusChangedCallback(const TTValue& baton, const TTValue& value); // Function to poll information about scenario execution at another rate void DemoAppScenarioPollingThread(DemoApp* demoApp); int main(int argc, char **argv) { DemoApp app; TTLogMessage("\n*** Start of Jamoma Modular and Score demonstration ***\n"); app.SetupModular(); app.SetupScore(); // read command from console do { TTLogMessage("\nType a command : \n"); std::string s; std::getline(std::cin, s); // quit the application if (!s.compare("quit")) { app.Quit(); TTLogMessage("\n*** End of Jamoma Modular and Score demonstration ***\n"); return EXIT_SUCCESS; } // update mDataDemoMessage data with the command else { app.SetMessage(s); } } while (YES); } void DemoApp::SetupModular() { TTValue args; TTLogMessage("\n*** Initialisation of Modular environnement ***\n"); ///////////////////////////////////////////////////////////////////// // Init the Modular library (passing the folder path where all the dylibs are) TTModularInit("/usr/local/jamoma/extensions"); // Create an application manager mApplicationManager = TTObject("ApplicationManager"); TTLogMessage("\n*** Creation of mApplicationDemo application ***\n"); ///////////////////////////////////////////////////////////////////// // Create a local application called "demo" and get it back mApplicationDemo = mApplicationManager.send("ApplicationInstantiateLocal", "demo"); if (!mApplicationDemo.valid()) { TTLogError("Error : can't create demo application \n"); return; } TTLogMessage("\n*** Creation of mApplicationDemo datas ***\n"); ///////////////////////////////////////////////////////////////////// // Create a parameter data and set its callback function and baton and some attributes mDataDemoParameter = TTObject("Data", "parameter"); // Setup the callback mechanism to get the value back args = TTValue(TTPtr(this), mDataDemoParameter); mDataDemoParameter.set("baton", args); mDataDemoParameter.set("function", TTPtr(&DemoAppDataReturnValueCallback)); // Setup the data attributes depending of its use inside the application mDataDemoParameter.set("type", "decimal"); mDataDemoParameter.set("rangeBounds", TTValue(0., 1.)); mDataDemoParameter.set("rangeClipmode", "low"); mDataDemoParameter.set("description", "any information relative to the state of the application"); // Register the parameter data into mApplicationDemo at an address args = TTValue("/myParameter", mDataDemoParameter); mApplicationDemo.send("ObjectRegister", args); // Create a message data and set its callback function and baton and some attributes mDataDemoMessage = TTObject("Data", "message"); // Setup the callback mechanism to get the value back args = TTValue(TTPtr(this), mDataDemoMessage); mDataDemoMessage.set("baton", args); mDataDemoMessage.set("function", TTPtr(&DemoAppDataReturnValueCallback)); // Setup the data attributes depending of its use inside the application mDataDemoMessage.set("type", "string"); mDataDemoMessage.set("description", "any information to provide to the application"); // Register the message data into mApplicationDemo at an address args = TTValue("/myMessage", mDataDemoMessage); mApplicationDemo.send("ObjectRegister", args); // Create a return data and set its callback function and baton and some attributes mDataDemoReturn = TTObject("Data", "return"); // Setup the callback mechanism to get the value back args = TTValue(TTPtr(this), mDataDemoReturn); mDataDemoReturn.set("baton", args); mDataDemoReturn.set("function", TTPtr(&DemoAppDataReturnValueCallback)); // Setup the data attributes depending of its use inside the application mDataDemoReturn.set("type", "integer"); mDataDemoReturn.set("defaultValue", 0); mDataDemoReturn.set("description", "any information the application returns back"); // Register the return data into mApplicationDemo at an address args = TTValue("/myReturn", mDataDemoReturn); mApplicationDemo.send("ObjectRegister", args); // Initialise the application and all datas inside (using defaultValue attribute) mApplicationDemo.send("Init"); } void DemoApp::SetupScore() { TTObject xmlHandler("XmlHandler"); TTLogMessage("\n*** Initialisation of Score environnement ***\n"); ///////////////////////////////////////////////////////////////////// // Init the Score library (passing the folder path where all the dylibs are) TTScoreInit("/usr/local/jamoma/extensions"); TTLogMessage("\n*** Reading of an interactive scenario file ***\n"); ///////////////////////////////////////////////////////////////////// // Create an empty Scenario mScenario = TTObject("Scenario"); // Read DemoScenario1.score file to fill mScenario xmlHandler.set("object", mScenario); xmlHandler.send("Read", "../DemoScenario.score"); TTLogMessage("\n*** Prepare scenario observation ***\n"); ///////////////////////////////////////////////////////////////////// // Create a callback for the "EventStatusChanged" notification sent by each event mEventStatusChangedCallback = TTObject("callback"); mEventStatusChangedCallback.set("baton", TTPtr(this)); mEventStatusChangedCallback.set("function", TTPtr(&DemoAppEventStatusChangedCallback)); mEventStatusChangedCallback.set("notification", TTSymbol("EventStatusChanged")); // Get all events of the scenario and attach a callback to them TTValue timeEvents; mScenario.get("timeEvents", timeEvents); for (TTElementIter it = timeEvents.begin() ; it != timeEvents.end() ; it++) { TTObject event = TTElement(*it); event.registerObserverForNotifications(mEventStatusChangedCallback); } TTLogMessage("\n*** Start scenario execution ***\n"); ///////////////////////////////////////////////////////////////////// // Set the execution speed of the scenario mScenario.set("speed", 2.); // Start the scenario mScenario.send("Start"); // Poll Scenario information mPollingThread = new TTThread(TTThreadCallbackType(DemoAppScenarioPollingThread), this); } void DemoApp::SetMessage(std::string s) { TTSymbol message(s); mDataDemoMessage.send("Command", message); } void DemoApp::Quit() { TTLogMessage("\n*** Release mApplicationDemo datas ***\n"); ///////////////////////////////////////////////////////////////////// // Unregister the parameter if ( mApplicationDemo.send("ObjectUnregister", "/myParameter")) TTLogError("Error : can't unregister data at /myParameter address \n"); // Unregister the message if (mApplicationDemo.send("ObjectUnregister", "/myMessage")) TTLogError("Error : can't unregister data at /myMessage address \n"); // Unregister the return if (mApplicationDemo.send("ObjectUnregister", "/myReturn")) TTLogError("Error : can't unregister data at /myReturn address \n"); TTLogMessage("\n*** Release application ***\n"); ///////////////////////////////////////////////////////////////////// mApplicationManager.send("ApplicationRelease", "demo"); // quit the program normally std::exit(EXIT_SUCCESS); } TTErr DemoAppDataReturnValueCallback(const TTValue& baton, const TTValue& value) { DemoApp* demoApp = (DemoApp*)TTPtr(baton[0]); TTObject anObject = baton[1]; // Reteive which data has been updated if (anObject.instance() == demoApp->mDataDemoParameter.instance()) { // print the returned value TTLogMessage("/myParameter has been updated to %s \n", value.toString().data()); return kTTErrNone; } if (anObject.instance() == demoApp->mDataDemoMessage.instance()) { // print the returned value TTLogMessage("/myMessage has been updated to %s \n", value.toString().data()); return kTTErrNone; } if (anObject.instance() == demoApp->mDataDemoReturn.instance()) { // print the returned value TTLogMessage("/myReturn has been updated to %s \n", value.toString().data()); return kTTErrNone; } return kTTErrGeneric; } TTErr DemoAppEventStatusChangedCallback(const TTValue& baton, const TTValue& value) { DemoApp* demoApp = (DemoApp*)TTPtr(baton[0]); TTObject event = value[0]; TTSymbol newStatus = value[1]; TTSymbol oldStatus = value[2]; // get the name of the event TTSymbol name; event.get("name", name); // print the event status TTLogMessage("%s status : %s \n", name.c_str(), newStatus.c_str()); return kTTErrNone; } void DemoAppScenarioPollingThread(DemoApp* demoApp) { TTBoolean isRunning; do { // wait demoApp->mPollingThread->sleep(1); // look at the running state of the scnario demoApp->mScenario.get("running", isRunning); } while (isRunning); // quit DemoApp demoApp->Quit(); }<|endoftext|>
<commit_before>// Author: Enrico Guiraud CERN 08/2020 /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RDF_COLUMNREADERS #define ROOT_RDF_COLUMNREADERS #include <ROOT/RDF/RDefineBase.hxx> #include <ROOT/RMakeUnique.hxx> #include <ROOT/RVec.hxx> #include <ROOT/TypeTraits.hxx> #include <TTreeReader.h> #include <TTreeReaderValue.h> #include <TTreeReaderArray.h> #include <cassert> #include <cstring> #include <limits> #include <memory> #include <string> #include <tuple> #include <typeinfo> #include <vector> namespace ROOT { namespace Internal { namespace RDF { using namespace ROOT::TypeTraits; namespace RDFDetail = ROOT::Detail::RDF; void CheckDefine(RDFDetail::RDefineBase &define, const std::type_info &tid); /** \class ROOT::Internal::RDF::RColumnReaderBase \ingroup dataframe \brief Pure virtual base class for all column reader types This pure virtual class provides a common base class for the different column reader types, e.g. RTreeColumnReader and RDSColumnReader. **/ class RColumnReaderBase { public: virtual ~RColumnReaderBase() = default; /// Return the column value for the given entry. Called at most once per entry. template <typename T> T &Get(Long64_t entry) { return *static_cast<T *>(GetImpl(entry)); } /// Perform clean-up operations if needed. Called at the end of a processing task. virtual void Reset() {} private: virtual void *GetImpl(Long64_t entry) = 0; }; /// Column reader for defined (aka custom) columns. template <typename T> class R__CLING_PTRCHECK(off) RDefineReader final : public RColumnReaderBase { /// Non-owning reference to the node responsible for the custom column. Needed when querying custom values. RDFDetail::RDefineBase &fDefine; /// Non-owning ptr to the value of a custom column. T *fCustomValuePtr = nullptr; /// The slot this value belongs to. unsigned int fSlot = std::numeric_limits<unsigned int>::max(); void *GetImpl(Long64_t entry) final { fDefine.Update(fSlot, entry); return fCustomValuePtr; } public: RDefineReader(unsigned int slot, RDFDetail::RDefineBase &define) : fDefine(define), fCustomValuePtr(static_cast<T *>(define.GetValuePtr(slot))), fSlot(slot) { CheckDefine(define, typeid(T)); } }; /// RTreeColumnReader specialization for TTree values read via TTreeReaderValues template <typename T> class R__CLING_PTRCHECK(off) RTreeColumnReader final : public RColumnReaderBase { std::unique_ptr<TTreeReaderValue<T>> fTreeValue; void *GetImpl(Long64_t) final { return fTreeValue->Get(); } public: /// Construct the RTreeColumnReader. Actual initialization is performed lazily by the Init method. RTreeColumnReader(TTreeReader &r, const std::string &colName) : fTreeValue(std::make_unique<TTreeReaderValue<T>>(r, colName.c_str())) { } /// Delete the TTreeReaderValue object. // // Without this call, a race condition is present in which a TTreeReader // and its TTreeReader{Value,Array}s can be deleted concurrently: // - Thread #1) a task ends and pushes back processing slot // - Thread #2) a task starts and overwrites thread-local TTreeReaderValues // - Thread #1) first task deletes TTreeReader // See https://github.com/root-project/root/commit/26e8ace6e47de6794ac9ec770c3bbff9b7f2e945 void Reset() final { fTreeValue.reset(); } }; /// RTreeColumnReader specialization for TTree values read via TTreeReaderArrays. /// /// TTreeReaderArrays are used whenever the RDF column type is RVec<T>. template <typename T> class R__CLING_PTRCHECK(off) RTreeColumnReader<RVec<T>> final : public RColumnReaderBase { std::unique_ptr<TTreeReaderArray<T>> fTreeArray; /// Enumerator for the memory layout of the branch enum class EStorageType : char { kContiguous, kUnknown, kSparse }; /// We return a reference to this RVec to clients, to guarantee a stable address and contiguous memory layout. RVec<T> fRVec; /// Signal whether we ever checked that the branch we are reading with a TTreeReaderArray stores array elements /// in contiguous memory. EStorageType fStorageType = EStorageType::kUnknown; /// Whether we already printed a warning about performing a copy of the TTreeReaderArray contents bool fCopyWarningPrinted = false; void *GetImpl(Long64_t) final { auto &readerArray = *fTreeArray; // We only use TTreeReaderArrays to read columns that users flagged as type `RVec`, so we need to check // that the branch stores the array as contiguous memory that we can actually wrap in an `RVec`. // Currently we need the first entry to have been loaded to perform the check // TODO Move check to constructor once ROOT-10823 is fixed and TTreeReaderArray itself exposes this information const auto arrSize = readerArray.GetSize(); if (EStorageType::kUnknown == fStorageType && arrSize > 1) { // We can decide since the array is long enough fStorageType = EStorageType::kContiguous; for (auto i = 0u; i < arrSize - 1; ++i) { if ((char *)&readerArray[i + 1] - (char *)&readerArray[i] != sizeof(T)) { fStorageType = EStorageType::kSparse; break; } } } const auto readerArraySize = readerArray.GetSize(); if (EStorageType::kContiguous == fStorageType || (EStorageType::kUnknown == fStorageType && readerArray.GetSize() < 2)) { if (readerArraySize > 0) { // trigger loading of the contents of the TTreeReaderArray // the address of the first element in the reader array is not necessarily equal to // the address returned by the GetAddress method auto readerArrayAddr = &readerArray.At(0); RVec<T> rvec(readerArrayAddr, readerArraySize); std::swap(fRVec, rvec); } else { RVec<T> emptyVec{}; std::swap(fRVec, emptyVec); } } else { // The storage is not contiguous or we don't know yet: we cannot but copy into the rvec #ifndef NDEBUG if (!fCopyWarningPrinted) { Warning("RTreeColumnReader::Get", "Branch %s hangs from a non-split branch. A copy is being performed in order " "to properly read the content.", readerArray.GetBranchName()); fCopyWarningPrinted = true; } #else (void)fCopyWarningPrinted; #endif if (readerArraySize > 0) { RVec<T> rvec(readerArray.begin(), readerArray.end()); std::swap(fRVec, rvec); } else { RVec<T> emptyVec{}; std::swap(fRVec, emptyVec); } } return &fRVec; } public: RTreeColumnReader(TTreeReader &r, const std::string &colName) : fTreeArray(std::make_unique<TTreeReaderArray<T>>(r, colName.c_str())) { } /// Delete the TTreeReaderArray object. void Reset() final { fTreeArray.reset(); } }; /// RTreeColumnReader specialization for arrays of boolean values read via TTreeReaderArrays. /// /// TTreeReaderArray<bool> is used whenever the RDF column type is RVec<bool>. template <> class R__CLING_PTRCHECK(off) RTreeColumnReader<RVec<bool>> final : public RColumnReaderBase { std::unique_ptr<TTreeReaderArray<bool>> fTreeArray; /// We return a reference to this RVec to clients, to guarantee a stable address and contiguous memory layout RVec<bool> fRVec; // We always copy the contents of TTreeReaderArray<bool> into an RVec<bool> (never take a view into the memory // buffer) because the underlying memory buffer might be the one of a std::vector<bool>, which is not a contiguous // slab of bool values. // Note that this also penalizes the case in which the column type is actually bool[], but the possible performance // gains in this edge case is probably not worth the extra complication required to differentiate the two cases. void *GetImpl(Long64_t) final { auto &readerArray = *fTreeArray; const auto readerArraySize = readerArray.GetSize(); if (readerArraySize > 0) { // always perform a copy RVec<bool> rvec(readerArray.begin(), readerArray.end()); std::swap(fRVec, rvec); } else { RVec<bool> emptyVec{}; std::swap(fRVec, emptyVec); } return &fRVec; } public: RTreeColumnReader(TTreeReader &r, const std::string &colName) : fTreeArray(std::make_unique<TTreeReaderArray<bool>>(r, colName.c_str())) { } /// Delete the TTreeReaderArray object. void Reset() final { fTreeArray.reset(); } }; /// Column reader type that deals with values read from RDataSources. template <typename T> class R__CLING_PTRCHECK(off) RDSColumnReader final : public RColumnReaderBase { T **fDSValuePtr = nullptr; void *GetImpl(Long64_t) final { return *fDSValuePtr; } public: RDSColumnReader(void * DSValuePtr) : fDSValuePtr(static_cast<T **>(DSValuePtr)) {} }; template <typename T> std::unique_ptr<RColumnReaderBase> MakeColumnReader(unsigned int slot, RDFDetail::RDefineBase *define, TTreeReader *r, const std::vector<void *> *DSValuePtrsPtr, const std::string &colName) { using Ret_t = std::unique_ptr<RColumnReaderBase>; if (define != nullptr) return Ret_t(new RDefineReader<T>(slot, *define)); if (DSValuePtrsPtr != nullptr) { auto &DSValuePtrs = *DSValuePtrsPtr; return Ret_t(new RDSColumnReader<T>(DSValuePtrs[slot])); } return Ret_t(new RTreeColumnReader<T>(*r, colName)); } template <typename T> std::unique_ptr<RColumnReaderBase> InitColumnReadersHelper(unsigned int slot, RDFDetail::RDefineBase *define, const std::map<std::string, std::vector<void *>> &DSValuePtrsMap, TTreeReader *r, const std::string &colName) { const auto DSValuePtrsIt = DSValuePtrsMap.find(colName); const std::vector<void *> *DSValuePtrsPtr = DSValuePtrsIt != DSValuePtrsMap.end() ? &DSValuePtrsIt->second : nullptr; R__ASSERT(define != nullptr || r != nullptr || DSValuePtrsPtr != nullptr); return MakeColumnReader<T>(slot, define, r, DSValuePtrsPtr, colName); } /// This type aggregates some of the arguments passed to InitColumnReaders. /// We need to pass a single RColumnReadersInfo object rather than each argument separately because with too many /// arguments passed, gcc 7.5.0 and cling disagree on the ABI, which leads to the last function argument being read /// incorrectly from a compiled InitColumnReaders symbols when invoked from a jitted symbol. struct RColumnReadersInfo { const std::vector<std::string> &fColNames; const RBookedDefines &fCustomCols; const bool *fIsDefine; const std::map<std::string, std::vector<void *>> &fDSValuePtrsMap; }; /// Initialize a tuple of column readers. template <typename... ColTypes> void InitColumnReaders(unsigned int slot, std::vector<std::unique_ptr<RColumnReaderBase>> &colReaders, TTreeReader *r, TypeList<ColTypes...>, const RColumnReadersInfo &colInfo) { // see RColumnReadersInfo for why we pass these arguments like this rather than directly as function arguments const auto &colNames = colInfo.fColNames; const auto &customCols = colInfo.fCustomCols; const bool *isDefine = colInfo.fIsDefine; const auto &DSValuePtrsMap = colInfo.fDSValuePtrsMap; const auto &customColMap = customCols.GetColumns(); using expander = int[]; // Hack to expand a parameter pack without c++17 fold expressions. // Construct the column readers int i = 0; (void)expander{ (colReaders.emplace_back(InitColumnReadersHelper<ColTypes>( slot, isDefine[i] ? customColMap.at(colNames[i]).get() : nullptr, DSValuePtrsMap, r, colNames[i])), ++i)..., 0}; (void)slot; // avoid _bogus_ "unused variable" warnings for slot on gcc 4.9 (void)r; // avoid "unused variable" warnings for r on gcc5.2 } } // namespace RDF } // namespace Internal } // namespace ROOT #endif // ROOT_RDF_COLUMNREADERS <commit_msg>[DF][NFC] RDefineReader does not need the template parameter<commit_after>// Author: Enrico Guiraud CERN 08/2020 /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RDF_COLUMNREADERS #define ROOT_RDF_COLUMNREADERS #include <ROOT/RDF/RDefineBase.hxx> #include <ROOT/RMakeUnique.hxx> #include <ROOT/RVec.hxx> #include <ROOT/TypeTraits.hxx> #include <TTreeReader.h> #include <TTreeReaderValue.h> #include <TTreeReaderArray.h> #include <cassert> #include <cstring> #include <limits> #include <memory> #include <string> #include <tuple> #include <typeinfo> #include <vector> namespace ROOT { namespace Internal { namespace RDF { using namespace ROOT::TypeTraits; namespace RDFDetail = ROOT::Detail::RDF; void CheckDefine(RDFDetail::RDefineBase &define, const std::type_info &tid); /** \class ROOT::Internal::RDF::RColumnReaderBase \ingroup dataframe \brief Pure virtual base class for all column reader types This pure virtual class provides a common base class for the different column reader types, e.g. RTreeColumnReader and RDSColumnReader. **/ class RColumnReaderBase { public: virtual ~RColumnReaderBase() = default; /// Return the column value for the given entry. Called at most once per entry. template <typename T> T &Get(Long64_t entry) { return *static_cast<T *>(GetImpl(entry)); } /// Perform clean-up operations if needed. Called at the end of a processing task. virtual void Reset() {} private: virtual void *GetImpl(Long64_t entry) = 0; }; /// Column reader for defined (aka custom) columns. class R__CLING_PTRCHECK(off) RDefineReader final : public RColumnReaderBase { /// Non-owning reference to the node responsible for the custom column. Needed when querying custom values. RDFDetail::RDefineBase &fDefine; /// Non-owning ptr to the value of a custom column. void *fCustomValuePtr = nullptr; /// The slot this value belongs to. unsigned int fSlot = std::numeric_limits<unsigned int>::max(); void *GetImpl(Long64_t entry) final { fDefine.Update(fSlot, entry); return fCustomValuePtr; } public: RDefineReader(unsigned int slot, RDFDetail::RDefineBase &define, const std::type_info &tid) : fDefine(define), fCustomValuePtr(define.GetValuePtr(slot)), fSlot(slot) { CheckDefine(define, tid); } }; /// RTreeColumnReader specialization for TTree values read via TTreeReaderValues template <typename T> class R__CLING_PTRCHECK(off) RTreeColumnReader final : public RColumnReaderBase { std::unique_ptr<TTreeReaderValue<T>> fTreeValue; void *GetImpl(Long64_t) final { return fTreeValue->Get(); } public: /// Construct the RTreeColumnReader. Actual initialization is performed lazily by the Init method. RTreeColumnReader(TTreeReader &r, const std::string &colName) : fTreeValue(std::make_unique<TTreeReaderValue<T>>(r, colName.c_str())) { } /// Delete the TTreeReaderValue object. // // Without this call, a race condition is present in which a TTreeReader // and its TTreeReader{Value,Array}s can be deleted concurrently: // - Thread #1) a task ends and pushes back processing slot // - Thread #2) a task starts and overwrites thread-local TTreeReaderValues // - Thread #1) first task deletes TTreeReader // See https://github.com/root-project/root/commit/26e8ace6e47de6794ac9ec770c3bbff9b7f2e945 void Reset() final { fTreeValue.reset(); } }; /// RTreeColumnReader specialization for TTree values read via TTreeReaderArrays. /// /// TTreeReaderArrays are used whenever the RDF column type is RVec<T>. template <typename T> class R__CLING_PTRCHECK(off) RTreeColumnReader<RVec<T>> final : public RColumnReaderBase { std::unique_ptr<TTreeReaderArray<T>> fTreeArray; /// Enumerator for the memory layout of the branch enum class EStorageType : char { kContiguous, kUnknown, kSparse }; /// We return a reference to this RVec to clients, to guarantee a stable address and contiguous memory layout. RVec<T> fRVec; /// Signal whether we ever checked that the branch we are reading with a TTreeReaderArray stores array elements /// in contiguous memory. EStorageType fStorageType = EStorageType::kUnknown; /// Whether we already printed a warning about performing a copy of the TTreeReaderArray contents bool fCopyWarningPrinted = false; void *GetImpl(Long64_t) final { auto &readerArray = *fTreeArray; // We only use TTreeReaderArrays to read columns that users flagged as type `RVec`, so we need to check // that the branch stores the array as contiguous memory that we can actually wrap in an `RVec`. // Currently we need the first entry to have been loaded to perform the check // TODO Move check to constructor once ROOT-10823 is fixed and TTreeReaderArray itself exposes this information const auto arrSize = readerArray.GetSize(); if (EStorageType::kUnknown == fStorageType && arrSize > 1) { // We can decide since the array is long enough fStorageType = EStorageType::kContiguous; for (auto i = 0u; i < arrSize - 1; ++i) { if ((char *)&readerArray[i + 1] - (char *)&readerArray[i] != sizeof(T)) { fStorageType = EStorageType::kSparse; break; } } } const auto readerArraySize = readerArray.GetSize(); if (EStorageType::kContiguous == fStorageType || (EStorageType::kUnknown == fStorageType && readerArray.GetSize() < 2)) { if (readerArraySize > 0) { // trigger loading of the contents of the TTreeReaderArray // the address of the first element in the reader array is not necessarily equal to // the address returned by the GetAddress method auto readerArrayAddr = &readerArray.At(0); RVec<T> rvec(readerArrayAddr, readerArraySize); std::swap(fRVec, rvec); } else { RVec<T> emptyVec{}; std::swap(fRVec, emptyVec); } } else { // The storage is not contiguous or we don't know yet: we cannot but copy into the rvec #ifndef NDEBUG if (!fCopyWarningPrinted) { Warning("RTreeColumnReader::Get", "Branch %s hangs from a non-split branch. A copy is being performed in order " "to properly read the content.", readerArray.GetBranchName()); fCopyWarningPrinted = true; } #else (void)fCopyWarningPrinted; #endif if (readerArraySize > 0) { RVec<T> rvec(readerArray.begin(), readerArray.end()); std::swap(fRVec, rvec); } else { RVec<T> emptyVec{}; std::swap(fRVec, emptyVec); } } return &fRVec; } public: RTreeColumnReader(TTreeReader &r, const std::string &colName) : fTreeArray(std::make_unique<TTreeReaderArray<T>>(r, colName.c_str())) { } /// Delete the TTreeReaderArray object. void Reset() final { fTreeArray.reset(); } }; /// RTreeColumnReader specialization for arrays of boolean values read via TTreeReaderArrays. /// /// TTreeReaderArray<bool> is used whenever the RDF column type is RVec<bool>. template <> class R__CLING_PTRCHECK(off) RTreeColumnReader<RVec<bool>> final : public RColumnReaderBase { std::unique_ptr<TTreeReaderArray<bool>> fTreeArray; /// We return a reference to this RVec to clients, to guarantee a stable address and contiguous memory layout RVec<bool> fRVec; // We always copy the contents of TTreeReaderArray<bool> into an RVec<bool> (never take a view into the memory // buffer) because the underlying memory buffer might be the one of a std::vector<bool>, which is not a contiguous // slab of bool values. // Note that this also penalizes the case in which the column type is actually bool[], but the possible performance // gains in this edge case is probably not worth the extra complication required to differentiate the two cases. void *GetImpl(Long64_t) final { auto &readerArray = *fTreeArray; const auto readerArraySize = readerArray.GetSize(); if (readerArraySize > 0) { // always perform a copy RVec<bool> rvec(readerArray.begin(), readerArray.end()); std::swap(fRVec, rvec); } else { RVec<bool> emptyVec{}; std::swap(fRVec, emptyVec); } return &fRVec; } public: RTreeColumnReader(TTreeReader &r, const std::string &colName) : fTreeArray(std::make_unique<TTreeReaderArray<bool>>(r, colName.c_str())) { } /// Delete the TTreeReaderArray object. void Reset() final { fTreeArray.reset(); } }; /// Column reader type that deals with values read from RDataSources. template <typename T> class R__CLING_PTRCHECK(off) RDSColumnReader final : public RColumnReaderBase { T **fDSValuePtr = nullptr; void *GetImpl(Long64_t) final { return *fDSValuePtr; } public: RDSColumnReader(void * DSValuePtr) : fDSValuePtr(static_cast<T **>(DSValuePtr)) {} }; template <typename T> std::unique_ptr<RColumnReaderBase> MakeColumnReader(unsigned int slot, RDFDetail::RDefineBase *define, TTreeReader *r, const std::vector<void *> *DSValuePtrsPtr, const std::string &colName) { using Ret_t = std::unique_ptr<RColumnReaderBase>; if (define != nullptr) return Ret_t(new RDefineReader(slot, *define, typeid(T))); if (DSValuePtrsPtr != nullptr) { auto &DSValuePtrs = *DSValuePtrsPtr; return Ret_t(new RDSColumnReader<T>(DSValuePtrs[slot])); } return Ret_t(new RTreeColumnReader<T>(*r, colName)); } template <typename T> std::unique_ptr<RColumnReaderBase> InitColumnReadersHelper(unsigned int slot, RDFDetail::RDefineBase *define, const std::map<std::string, std::vector<void *>> &DSValuePtrsMap, TTreeReader *r, const std::string &colName) { const auto DSValuePtrsIt = DSValuePtrsMap.find(colName); const std::vector<void *> *DSValuePtrsPtr = DSValuePtrsIt != DSValuePtrsMap.end() ? &DSValuePtrsIt->second : nullptr; R__ASSERT(define != nullptr || r != nullptr || DSValuePtrsPtr != nullptr); return MakeColumnReader<T>(slot, define, r, DSValuePtrsPtr, colName); } /// This type aggregates some of the arguments passed to InitColumnReaders. /// We need to pass a single RColumnReadersInfo object rather than each argument separately because with too many /// arguments passed, gcc 7.5.0 and cling disagree on the ABI, which leads to the last function argument being read /// incorrectly from a compiled InitColumnReaders symbols when invoked from a jitted symbol. struct RColumnReadersInfo { const std::vector<std::string> &fColNames; const RBookedDefines &fCustomCols; const bool *fIsDefine; const std::map<std::string, std::vector<void *>> &fDSValuePtrsMap; }; /// Initialize a tuple of column readers. template <typename... ColTypes> void InitColumnReaders(unsigned int slot, std::vector<std::unique_ptr<RColumnReaderBase>> &colReaders, TTreeReader *r, TypeList<ColTypes...>, const RColumnReadersInfo &colInfo) { // see RColumnReadersInfo for why we pass these arguments like this rather than directly as function arguments const auto &colNames = colInfo.fColNames; const auto &customCols = colInfo.fCustomCols; const bool *isDefine = colInfo.fIsDefine; const auto &DSValuePtrsMap = colInfo.fDSValuePtrsMap; const auto &customColMap = customCols.GetColumns(); using expander = int[]; // Hack to expand a parameter pack without c++17 fold expressions. // Construct the column readers int i = 0; (void)expander{ (colReaders.emplace_back(InitColumnReadersHelper<ColTypes>( slot, isDefine[i] ? customColMap.at(colNames[i]).get() : nullptr, DSValuePtrsMap, r, colNames[i])), ++i)..., 0}; (void)slot; // avoid _bogus_ "unused variable" warnings for slot on gcc 4.9 (void)r; // avoid "unused variable" warnings for r on gcc5.2 } } // namespace RDF } // namespace Internal } // namespace ROOT #endif // ROOT_RDF_COLUMNREADERS <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // // 'Bayesian Calculator' RooStats tutorial macro #701 // author: Gregory Schott // date Sep 2009 // // This tutorial shows an example of using the BayesianCalculator class // ///////////////////////////////////////////////////////////////////////// #include "RooRealVar.h" #include "RooProdPdf.h" #include "RooWorkspace.h" #include "RooDataSet.h" #include "RooStats/BayesianCalculator.h" #include "RooStats/SimpleInterval.h" using namespace RooFit; using namespace RooStats; void rs701_BayesianCalculator() { RooWorkspace* w = new RooWorkspace("w",true); w->factory("SUM::pdf(s[0,15]*Uniform(x[0,1]),b[1,0,2]*Uniform(x))"); w->factory("Gaussian::prior_b(b,1,1)"); w->factory("PROD::model(pdf,prior_b)"); RooAbsPdf* model = w->pdf("model"); // pdf*priorNuisance const RooArgSet nuisanceParameters(*(w->var("b"))); w->factory("Uniform::priorPOI(s)"); RooAbsRealLValue* POI = w->var("s"); RooAbsPdf* priorPOI = w->pdf("priorPOI"); w->factory("n[1]"); // observed number of events RooDataSet data("data","",RooArgSet(*(w->var("x")),*(w->var("n"))),"n"); data.add(RooArgSet(*(w->var("x"))),w->var("n")->getVal()); BayesianCalculator bcalc(data,*model,RooArgSet(*POI),*priorPOI,&nuisanceParameters); bcalc.SetTestSize(0.05); SimpleInterval* interval = bcalc.GetInterval(); std::cout << "90% CL interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or 95% CL limits\n"; RooPlot * plot = bcalc.GetPosteriorPlot(); plot->Draw(); // observe one event while expecting one background event -> the 95% CL upper limit on s is 4.10 // observe one event while expecting zero background event -> the 95% CL upper limit on s is 4.74 } <commit_msg>improve Bayesian tutorial<commit_after>///////////////////////////////////////////////////////////////////////// // // 'Bayesian Calculator' RooStats tutorial macro #701 // author: Gregory Schott // date Sep 2009 // // This tutorial shows an example of using the BayesianCalculator class // ///////////////////////////////////////////////////////////////////////// #include "RooRealVar.h" #include "RooWorkspace.h" #include "RooDataSet.h" #include "RooPlot.h" #include "RooMsgService.h" #include "RooStats/BayesianCalculator.h" #include "RooStats/SimpleInterval.h" #include "TCanvas.h" using namespace RooFit; using namespace RooStats; void rs701_BayesianCalculator(bool useBkg = true, double confLevel = 0.90) { RooWorkspace* w = new RooWorkspace("w",true); w->factory("SUM::pdf(s[0,15]*Uniform(x[0,1]),b[1,0,2]*Uniform(x))"); w->factory("Gaussian::prior_b(b,1,1)"); w->factory("PROD::model(pdf,prior_b)"); RooAbsPdf* model = w->pdf("model"); // pdf*priorNuisance RooArgSet nuisanceParameters(*(w->var("b"))); RooAbsRealLValue* POI = w->var("s"); RooAbsPdf* priorPOI = (RooAbsPdf *) w->factory("Uniform::priorPOI(s)"); RooAbsPdf* priorPOI2 = (RooAbsPdf *) w->factory("GenericPdf::priorPOI2('1/s',s)"); w->factory("n[3]"); // observed number of events // create a data set with n observed events RooDataSet data("data","",RooArgSet(*(w->var("x")),*(w->var("n"))),"n"); data.add(RooArgSet(*(w->var("x"))),w->var("n")->getVal()); // to suppress messgaes when pdf goes to zero RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ; RooArgSet * nuisPar = 0; if (useBkg) nuisPar = &nuisanceParameters; double size = 1.-confLevel; std::cout << "\nBayesian Result using a Flat prior " << std::endl; BayesianCalculator bcalc(data,*model,RooArgSet(*POI),*priorPOI, nuisPar); bcalc.SetTestSize(size); SimpleInterval* interval = bcalc.GetInterval(); double cl = bcalc.ConfidenceLevel(); std::cout << cl <<"% CL central interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or " << cl+(1.-cl)/2 << "% CL limits\n"; RooPlot * plot = bcalc.GetPosteriorPlot(); TCanvas * c1 = new TCanvas("c1","Bayesian Calculator Result"); c1->Divide(1,2); c1->cd(1); plot->Draw(); std::cout << "\nBayesian Result using a 1/s prior " << std::endl; BayesianCalculator bcalc2(data,*model,RooArgSet(*POI),*priorPOI2, nuisPar); bcalc2.SetTestSize(size); SimpleInterval* interval2 = bcalc2.GetInterval(); cl = bcalc2.ConfidenceLevel(); std::cout << cl <<"% CL central interval: [ " << interval2->LowerLimit() << " - " << interval2->UpperLimit() << " ] or " << cl+(1.-cl)/2 << "% CL limits\n"; RooPlot * plot2 = bcalc2.GetPosteriorPlot(); c1->cd(2); plot2->Draw(); c1->Update(); // observe one event while expecting one background event -> the 95% CL upper limit on s is 4.10 // observe one event while expecting zero background event -> the 95% CL upper limit on s is 4.74 } <|endoftext|>
<commit_before>#include <iostream> #include <node.h> #include <v8.h> #include "Config.hpp" #include "Converter.hpp" using namespace v8; using namespace opencc; string ToUtf8String(const Local<String>& str) { v8::String::Utf8Value utf8(str); return std::string(*utf8); } class OpenccBinding : public node::ObjectWrap { struct ConvertRequest { OpenccBinding* instance; string input; string output; Persistent<Function> callback; Optional<opencc::Exception> ex; }; Config config_; ConverterPtr converter_; public: explicit OpenccBinding(const string configFileName) { config_.LoadFile(configFileName); converter_ = config_.GetConverter(); } virtual ~OpenccBinding() { } string Convert(const string& input) { return converter_->Convert(input); } static Handle<Value> New(const Arguments& args) { HandleScope scope; OpenccBinding* instance; try { if (args.Length() >= 1 && args[0]->IsString()) { string configFile = ToUtf8String(args[0]->ToString()); instance = new OpenccBinding(configFile); } else { instance = new OpenccBinding("s2t.json"); } } catch (opencc::Exception& e) { ThrowException(v8::Exception::Error( String::New(e.what()))); return scope.Close(Undefined()); } instance->Wrap(args.This()); return args.This(); } static Handle<Value> Convert(const Arguments& args) { HandleScope scope; if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsFunction()) { ThrowException(v8::Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } ConvertRequest* conv_data = new ConvertRequest; conv_data->instance = ObjectWrap::Unwrap<OpenccBinding>(args.This()); conv_data->input = ToUtf8String(args[0]->ToString()); conv_data->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); conv_data->ex = Optional<opencc::Exception>(); uv_work_t* req = new uv_work_t; req->data = conv_data; uv_queue_work(uv_default_loop(), req, DoConvert, (uv_after_work_cb)AfterConvert); return Undefined(); } static void DoConvert(uv_work_t* req) { ConvertRequest* conv_data = static_cast<ConvertRequest*>(req->data); OpenccBinding* instance = conv_data->instance; try { conv_data->output = instance->Convert(conv_data->input); } catch (opencc::Exception& e) { conv_data->ex = Optional<opencc::Exception>(e); } } static void AfterConvert(uv_work_t* req) { HandleScope scope; ConvertRequest* conv_data = static_cast<ConvertRequest*>(req->data); Local<Value> err = Local<Value>::New(Undefined()); Local<String> converted = String::New(conv_data->output.c_str()); if (!conv_data->ex.IsNull()) { err = String::New(conv_data->ex.Get().what()); } const unsigned argc = 2; Local<Value> argv[argc] = { err, Local<Value>::New(converted) }; conv_data->callback->Call(Context::GetCurrent()->Global(), argc, argv); conv_data->callback.Dispose(); delete conv_data; delete req; } static Handle<Value> ConvertSync(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsString()) { ThrowException(v8::Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } OpenccBinding* instance = ObjectWrap::Unwrap<OpenccBinding>(args.This()); string input = ToUtf8String(args[0]->ToString()); string output; try { output = instance->Convert(input); } catch (opencc::Exception& e) { ThrowException(v8::Exception::Error( String::New(e.what()))); return scope.Close(Undefined()); } Local<String> converted = String::New(output.c_str()); return scope.Close(converted); } static void init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(OpenccBinding::New); tpl->SetClassName(String::NewSymbol("Opencc")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("convert"), FunctionTemplate::New(Convert)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("convertSync"), FunctionTemplate::New(ConvertSync)->GetFunction()); // Constructor Persistent<Function> constructor = Persistent<Function>::New( tpl->GetFunction()); target->Set(String::NewSymbol("Opencc"), constructor); } }; void init(Handle<Object> target) { OpenccBinding::init(target); } NODE_MODULE(binding, init); <commit_msg>Fix node binding<commit_after>#include <iostream> #include <node.h> #include <v8.h> #include "Config.hpp" #include "Converter.hpp" using namespace v8; using namespace opencc; string ToUtf8String(const Local<String>& str) { v8::String::Utf8Value utf8(str); return std::string(*utf8); } class OpenccBinding : public node::ObjectWrap { struct ConvertRequest { OpenccBinding* instance; string input; string output; Persistent<Function> callback; Optional<opencc::Exception> ex; }; const Config config_; const ConverterPtr converter_; public: explicit OpenccBinding(const string configFileName) : config_(Config::NewFromFile(configFileName)), converter_(config_.GetConverter()) {} virtual ~OpenccBinding() { } string Convert(const string& input) { return converter_->Convert(input); } static Handle<Value> New(const Arguments& args) { HandleScope scope; OpenccBinding* instance; try { if (args.Length() >= 1 && args[0]->IsString()) { string configFile = ToUtf8String(args[0]->ToString()); instance = new OpenccBinding(configFile); } else { instance = new OpenccBinding("s2t.json"); } } catch (opencc::Exception& e) { ThrowException(v8::Exception::Error( String::New(e.what()))); return scope.Close(Undefined()); } instance->Wrap(args.This()); return args.This(); } static Handle<Value> Convert(const Arguments& args) { HandleScope scope; if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsFunction()) { ThrowException(v8::Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } ConvertRequest* conv_data = new ConvertRequest; conv_data->instance = ObjectWrap::Unwrap<OpenccBinding>(args.This()); conv_data->input = ToUtf8String(args[0]->ToString()); conv_data->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); conv_data->ex = Optional<opencc::Exception>(); uv_work_t* req = new uv_work_t; req->data = conv_data; uv_queue_work(uv_default_loop(), req, DoConvert, (uv_after_work_cb)AfterConvert); return Undefined(); } static void DoConvert(uv_work_t* req) { ConvertRequest* conv_data = static_cast<ConvertRequest*>(req->data); OpenccBinding* instance = conv_data->instance; try { conv_data->output = instance->Convert(conv_data->input); } catch (opencc::Exception& e) { conv_data->ex = Optional<opencc::Exception>(e); } } static void AfterConvert(uv_work_t* req) { HandleScope scope; ConvertRequest* conv_data = static_cast<ConvertRequest*>(req->data); Local<Value> err = Local<Value>::New(Undefined()); Local<String> converted = String::New(conv_data->output.c_str()); if (!conv_data->ex.IsNull()) { err = String::New(conv_data->ex.Get().what()); } const unsigned argc = 2; Local<Value> argv[argc] = { err, Local<Value>::New(converted) }; conv_data->callback->Call(Context::GetCurrent()->Global(), argc, argv); conv_data->callback.Dispose(); delete conv_data; delete req; } static Handle<Value> ConvertSync(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !args[0]->IsString()) { ThrowException(v8::Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } OpenccBinding* instance = ObjectWrap::Unwrap<OpenccBinding>(args.This()); string input = ToUtf8String(args[0]->ToString()); string output; try { output = instance->Convert(input); } catch (opencc::Exception& e) { ThrowException(v8::Exception::Error( String::New(e.what()))); return scope.Close(Undefined()); } Local<String> converted = String::New(output.c_str()); return scope.Close(converted); } static void init(Handle<Object> target) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(OpenccBinding::New); tpl->SetClassName(String::NewSymbol("Opencc")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype tpl->PrototypeTemplate()->Set(String::NewSymbol("convert"), FunctionTemplate::New(Convert)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("convertSync"), FunctionTemplate::New(ConvertSync)->GetFunction()); // Constructor Persistent<Function> constructor = Persistent<Function>::New( tpl->GetFunction()); target->Set(String::NewSymbol("Opencc"), constructor); } }; void init(Handle<Object> target) { OpenccBinding::init(target); } NODE_MODULE(binding, init); <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CORE_FUTURE_UTIL_HH_ #define CORE_FUTURE_UTIL_HH_ #include "future.hh" #include "shared_ptr.hh" #include <tuple> // parallel_for_each - run tasks in parallel // // Given a range [@begin, @end) of objects, run func(*i) for each i in // the range, and return a future<> that resolves when all the functions // complete. @func should return a future<> that indicates when it is // complete. template <typename Iterator, typename Func> inline future<> parallel_for_each(Iterator begin, Iterator end, Func&& func) { auto ret = make_ready_future<>(); while (begin != end) { auto f = func(*begin++).then([ret = std::move(ret)] () mutable { return std::move(ret); }); ret = std::move(f); } return ret; } // The AsyncAction concept represents an action which can complete later than // the actual function invocation. It is represented by a function which // returns a future which resolves when the action is done. template<typename AsyncAction, typename StopCondition> static inline void do_until_continued(StopCondition&& stop_cond, AsyncAction&& action, promise<> p) { while (!stop_cond()) { auto&& f = action(); if (!f.available()) { f.then([action = std::forward<AsyncAction>(action), stop_cond = std::forward<StopCondition>(stop_cond), p = std::move(p)]() mutable { do_until_continued(stop_cond, action, std::move(p)); }); return; } if (f.failed()) { f.forward_to(std::move(p)); return; } } p.set_value(); } // Invokes given action until it fails or given condition evaluates to true. template<typename AsyncAction, typename StopCondition> static inline future<> do_until(StopCondition&& stop_cond, AsyncAction&& action) { promise<> p; auto f = p.get_future(); do_until_continued(std::forward<StopCondition>(stop_cond), std::forward<AsyncAction>(action), std::move(p)); return f; } // Invoke given action until it fails. template<typename AsyncAction> static inline future<> keep_doing(AsyncAction&& action) { while (task_quota) { auto f = action(); if (!f.available()) { return f.then([action = std::forward<AsyncAction>(action)] () mutable { return keep_doing(std::forward<AsyncAction>(action)); }); } if (f.failed()) { return std::move(f); } --task_quota; } promise<> p; auto f = p.get_future(); schedule(make_task([action = std::forward<AsyncAction>(action), p = std::move(p)] () mutable { keep_doing(std::forward<AsyncAction>(action)).forward_to(std::move(p)); })); return f; } template<typename Iterator, typename AsyncAction> static inline future<> do_for_each(Iterator begin, Iterator end, AsyncAction&& action) { while (begin != end) { auto f = action(*begin++); if (!f.available()) { return f.then([action = std::forward<AsyncAction>(action), begin = std::move(begin), end = std::move(end)] () mutable { return do_for_each(std::move(begin), std::move(end), std::forward<AsyncAction>(action)); }); } } return make_ready_future<>(); } template <typename... Future> future<std::tuple<Future...>> when_all(Future&&... fut); template <> inline future<std::tuple<>> when_all() { return make_ready_future<std::tuple<>>(); } // gcc can't capture a parameter pack, so we need to capture // a tuple and use apply. But apply cannot accept an overloaded // function pointer as its first parameter, so provide this instead. struct do_when_all { template <typename... Future> future<std::tuple<Future...>> operator()(Future&&... fut) const { return when_all(std::move(fut)...); } }; template <typename Future, typename... Rest> inline future<std::tuple<Future, Rest...>> when_all(Future&& fut, Rest&&... rest) { return std::move(fut).then_wrapped( [rest = std::make_tuple(std::move(rest)...)] (Future&& fut) mutable { return apply(do_when_all(), std::move(rest)).then_wrapped( [fut = std::move(fut)] (future<std::tuple<Rest...>>&& rest) mutable { return make_ready_future<std::tuple<Future, Rest...>>( std::tuple_cat(std::make_tuple(std::move(fut)), std::get<0>(rest.get()))); }); }); } template <typename T> struct reducer_with_get_traits { using result_type = decltype(std::declval<T>().get()); using future_type = future<result_type>; static future_type maybe_call_get(future<> f, shared_ptr<T> r) { return f.then([r = std::move(r)] () mutable { return make_ready_future<result_type>(std::move(*r).get()); }); } }; template <typename T, typename V = void> struct reducer_traits { using future_type = future<>; static future_type maybe_call_get(future<> f, shared_ptr<T> r) { return f.then([r = std::move(r)] {}); } }; template <typename T> struct reducer_traits<T, decltype(std::declval<T>().get(), void())> : public reducer_with_get_traits<T> {}; // @Mapper is a callable which transforms values from the iterator range // into a future<T>. @Reducer is an object which can be called with T as // parameter and yields a future<>. It may have a get() method which returns // a value of type U which holds the result of reduction. This value is wrapped // in a future and returned by this function. If the reducer has no get() method // then this function returns future<>. // // TODO: specialize for non-deferring reducer template <typename Iterator, typename Mapper, typename Reducer> inline auto map_reduce(Iterator begin, Iterator end, Mapper&& mapper, Reducer&& r) -> typename reducer_traits<Reducer>::future_type { auto r_ptr = make_shared(std::forward<Reducer>(r)); future<> ret = make_ready_future<>(); while (begin != end) { ret = mapper(*begin++).then([ret = std::move(ret), r_ptr] (auto value) mutable { return ret.then([value = std::move(value), r_ptr] () mutable { return (*r_ptr)(std::move(value)); }); }); } return reducer_traits<Reducer>::maybe_call_get(std::move(ret), r_ptr); } // Implements @Reducer concept. Calculates the result by // adding elements to the accumulator. template <typename Result, typename Addend = Result> class adder { private: Result _result; public: future<> operator()(const Addend& value) { _result += value; return make_ready_future<>(); } Result get() && { return std::move(_result); } }; #endif /* CORE_FUTURE_UTIL_HH_ */ <commit_msg>future-util.hh: add missing include<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CORE_FUTURE_UTIL_HH_ #define CORE_FUTURE_UTIL_HH_ #include "future.hh" #include "shared_ptr.hh" #include "reactor.hh" #include <tuple> // parallel_for_each - run tasks in parallel // // Given a range [@begin, @end) of objects, run func(*i) for each i in // the range, and return a future<> that resolves when all the functions // complete. @func should return a future<> that indicates when it is // complete. template <typename Iterator, typename Func> inline future<> parallel_for_each(Iterator begin, Iterator end, Func&& func) { auto ret = make_ready_future<>(); while (begin != end) { auto f = func(*begin++).then([ret = std::move(ret)] () mutable { return std::move(ret); }); ret = std::move(f); } return ret; } // The AsyncAction concept represents an action which can complete later than // the actual function invocation. It is represented by a function which // returns a future which resolves when the action is done. template<typename AsyncAction, typename StopCondition> static inline void do_until_continued(StopCondition&& stop_cond, AsyncAction&& action, promise<> p) { while (!stop_cond()) { auto&& f = action(); if (!f.available()) { f.then([action = std::forward<AsyncAction>(action), stop_cond = std::forward<StopCondition>(stop_cond), p = std::move(p)]() mutable { do_until_continued(stop_cond, action, std::move(p)); }); return; } if (f.failed()) { f.forward_to(std::move(p)); return; } } p.set_value(); } // Invokes given action until it fails or given condition evaluates to true. template<typename AsyncAction, typename StopCondition> static inline future<> do_until(StopCondition&& stop_cond, AsyncAction&& action) { promise<> p; auto f = p.get_future(); do_until_continued(std::forward<StopCondition>(stop_cond), std::forward<AsyncAction>(action), std::move(p)); return f; } // Invoke given action until it fails. template<typename AsyncAction> static inline future<> keep_doing(AsyncAction&& action) { while (task_quota) { auto f = action(); if (!f.available()) { return f.then([action = std::forward<AsyncAction>(action)] () mutable { return keep_doing(std::forward<AsyncAction>(action)); }); } if (f.failed()) { return std::move(f); } --task_quota; } promise<> p; auto f = p.get_future(); schedule(make_task([action = std::forward<AsyncAction>(action), p = std::move(p)] () mutable { keep_doing(std::forward<AsyncAction>(action)).forward_to(std::move(p)); })); return f; } template<typename Iterator, typename AsyncAction> static inline future<> do_for_each(Iterator begin, Iterator end, AsyncAction&& action) { while (begin != end) { auto f = action(*begin++); if (!f.available()) { return f.then([action = std::forward<AsyncAction>(action), begin = std::move(begin), end = std::move(end)] () mutable { return do_for_each(std::move(begin), std::move(end), std::forward<AsyncAction>(action)); }); } } return make_ready_future<>(); } template <typename... Future> future<std::tuple<Future...>> when_all(Future&&... fut); template <> inline future<std::tuple<>> when_all() { return make_ready_future<std::tuple<>>(); } // gcc can't capture a parameter pack, so we need to capture // a tuple and use apply. But apply cannot accept an overloaded // function pointer as its first parameter, so provide this instead. struct do_when_all { template <typename... Future> future<std::tuple<Future...>> operator()(Future&&... fut) const { return when_all(std::move(fut)...); } }; template <typename Future, typename... Rest> inline future<std::tuple<Future, Rest...>> when_all(Future&& fut, Rest&&... rest) { return std::move(fut).then_wrapped( [rest = std::make_tuple(std::move(rest)...)] (Future&& fut) mutable { return apply(do_when_all(), std::move(rest)).then_wrapped( [fut = std::move(fut)] (future<std::tuple<Rest...>>&& rest) mutable { return make_ready_future<std::tuple<Future, Rest...>>( std::tuple_cat(std::make_tuple(std::move(fut)), std::get<0>(rest.get()))); }); }); } template <typename T> struct reducer_with_get_traits { using result_type = decltype(std::declval<T>().get()); using future_type = future<result_type>; static future_type maybe_call_get(future<> f, shared_ptr<T> r) { return f.then([r = std::move(r)] () mutable { return make_ready_future<result_type>(std::move(*r).get()); }); } }; template <typename T, typename V = void> struct reducer_traits { using future_type = future<>; static future_type maybe_call_get(future<> f, shared_ptr<T> r) { return f.then([r = std::move(r)] {}); } }; template <typename T> struct reducer_traits<T, decltype(std::declval<T>().get(), void())> : public reducer_with_get_traits<T> {}; // @Mapper is a callable which transforms values from the iterator range // into a future<T>. @Reducer is an object which can be called with T as // parameter and yields a future<>. It may have a get() method which returns // a value of type U which holds the result of reduction. This value is wrapped // in a future and returned by this function. If the reducer has no get() method // then this function returns future<>. // // TODO: specialize for non-deferring reducer template <typename Iterator, typename Mapper, typename Reducer> inline auto map_reduce(Iterator begin, Iterator end, Mapper&& mapper, Reducer&& r) -> typename reducer_traits<Reducer>::future_type { auto r_ptr = make_shared(std::forward<Reducer>(r)); future<> ret = make_ready_future<>(); while (begin != end) { ret = mapper(*begin++).then([ret = std::move(ret), r_ptr] (auto value) mutable { return ret.then([value = std::move(value), r_ptr] () mutable { return (*r_ptr)(std::move(value)); }); }); } return reducer_traits<Reducer>::maybe_call_get(std::move(ret), r_ptr); } // Implements @Reducer concept. Calculates the result by // adding elements to the accumulator. template <typename Result, typename Addend = Result> class adder { private: Result _result; public: future<> operator()(const Addend& value) { _result += value; return make_ready_future<>(); } Result get() && { return std::move(_result); } }; #endif /* CORE_FUTURE_UTIL_HH_ */ <|endoftext|>
<commit_before>#include "ioloop.h" #include "socket.h" #include "gtest/gtest.h" using namespace share_me_utils; TEST(FooTest, HandleNoneZeroInput) { EXPECT_EQ(2, 2); EXPECT_EQ(6, 3 + 3); } #define SOCKET_CONTINER_CAPACITY 10 class SocketUnittest : public testing::Test { protected: virtual void SetUp() { m_io = NULL; memset(m_sockets, 0, sizeof(m_sockets)); } virtual void TearDown() { m_io->Release(); for (int i = 0; i < SOCKET_CONTINER_CAPACITY; ++i) { if (m_sockets[i]) { delete m_sockets[i]; m_sockets[i] = NULL; } delete m_sockets; } } IOLoop *m_io; Socket *m_sockets[SOCKET_CONTINER_CAPACITY]; }; TEST_F(SocketUnittest, OneEqual) { EXPECT_EQ(1, 1); } int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>test ok<commit_after>#include "ioloop.h" #include "socket.h" #include "gtest/gtest.h" #include <iostream> using namespace share_me_utils; TEST(FooTest, HandleNoneZeroInput) { EXPECT_EQ(2, 2); EXPECT_EQ(6, 3 + 3); } #define SOCKET_CONTINER_CAPACITY 10 class SocketUnittest : public testing::Test { protected: virtual void SetUp() { std::cout << "SocketUnittest SetUp ..." << std::endl; m_io = NULL; memset(m_sockets, 0, sizeof(m_sockets)); } virtual void TearDown() { std::cout << "SocketUnittest TearDown ..." << std::endl; m_io->Release(); for (int i = 0; i < SOCKET_CONTINER_CAPACITY; ++i) { if (m_sockets[i]) { delete m_sockets[i]; m_sockets[i] = NULL; } } } IOLoop *m_io; Socket *m_sockets[SOCKET_CONTINER_CAPACITY]; }; TEST_F(SocketUnittest, OneEqual) { EXPECT_EQ(1, 1); } TEST_F(SocketUnittest, IO_is_NULL) { EXPECT_EQ(NULL, m_io); } int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <smooth/core/json/Value.h> #include <smooth/core/util/make_unique.h> #include <smooth/core/logging/log.h> using namespace smooth::core::util; using namespace smooth::core::logging; namespace smooth { namespace core { namespace json { Value::Value(cJSON* src) { data = src; } Value::Value(const std::string& src) { data = cJSON_Parse(src.c_str()); } Value::Value(cJSON* parent, cJSON* object) : parent(parent), data(object) { } Value Value::operator[](const std::string& key) { cJSON* item = nullptr; if (cJSON_IsObject(data)) { item = cJSON_GetObjectItemCaseSensitive(data, key.c_str()); } if (item) { return Value(data, item); } else { auto new_item = cJSON_CreateObject(); cJSON_AddItemToObject(data, key.c_str(), new_item); return Value(data, new_item); } } Value Value::operator[](int index) { if (cJSON_IsArray(data)) { auto item = cJSON_GetArrayItem(data, index); if (item) { return Value(data, item); } else { return *this; } } else { return *this; } } Value& Value::operator=(const std::string& s) { auto new_data = cJSON_CreateString(s.c_str()); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = cJSON_CreateString(s.c_str()); } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::operator=(int value) { auto new_data = cJSON_CreateNumber(value); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = new_data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::operator=(double value) { auto new_data = cJSON_CreateNumber(value); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = new_data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::set(bool value) { auto new_data = cJSON_CreateBool(value ? cJSON_True : cJSON_False); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = new_data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::operator=(const Value& other) { if (this != &other) { if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = other.data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, other.data); } } return *this; } bool Value::operator==(const std::string& s) const { return cJSON_IsString(data) && s == data->valuestring; } bool Value::operator==(int value) const { return cJSON_IsNumber(data) && value == data->valueint; } bool Value::operator==(double value) const { return cJSON_IsNumber(data) && value == data->valuedouble; } Value::operator std::string() const { return cJSON_IsString(data) ? data->valuestring : ""; } std::string Value::get_string(const std::string& default_value) const { auto res = default_value; if (cJSON_IsString(data)) { res = data->valuestring; } return res; } int Value::get_int(int default_value) const { auto res = default_value; if (cJSON_IsNumber(data)) { res = data->valueint; } return res; } bool Value::get_bool(bool default_value) const { auto res = default_value; if (cJSON_IsBool(data)) { res = static_cast<bool>(cJSON_IsTrue(data)); } return res; } Value::operator int() const { return cJSON_IsNumber(data) ? data->valueint : 0; } Value::operator double() const { return cJSON_IsNumber(data) ? data->valuedouble : 0; } Value::operator bool() const { return cJSON_IsBool(data) && cJSON_IsTrue(data); } int Value::get_array_size() const { return cJSON_GetArraySize(data); } std::string Value::get_name() const { return data->string; } void Value::get_member_names(std::vector<std::string>& names) const { // Get names of this nodes child and its siblings cJSON* curr = data; if (curr != nullptr && curr->child != nullptr) { curr = curr->child; while (curr != nullptr && curr->string != nullptr) { names.emplace_back(curr->string); curr = curr->next; } } } } } } <commit_msg>More array tests<commit_after>#include <smooth/core/json/Value.h> #include <smooth/core/util/make_unique.h> #include <smooth/core/logging/log.h> using namespace smooth::core::util; using namespace smooth::core::logging; namespace smooth { namespace core { namespace json { Value::Value(cJSON* src) { data = src; } Value::Value(const std::string& src) { data = cJSON_Parse(src.c_str()); } Value::Value(cJSON* parent, cJSON* object) : parent(parent), data(object) { } Value Value::operator[](const std::string& key) { cJSON* item = nullptr; if (cJSON_IsObject(data)) { item = cJSON_GetObjectItemCaseSensitive(data, key.c_str()); } if (item) { return Value(data, item); } else { auto new_item = cJSON_CreateObject(); cJSON_AddItemToObject(data, key.c_str(), new_item); return Value(data, new_item); } } Value Value::operator[](int index) { if (cJSON_IsArray(data)) { auto item = cJSON_GetArrayItem(data, index); if (item) { return Value(data, item); } else { return *this; } } else { return *this; } } Value& Value::operator=(const std::string& s) { auto new_data = cJSON_CreateString(s.c_str()); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = cJSON_CreateString(s.c_str()); } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::operator=(int value) { auto new_data = cJSON_CreateNumber(value); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = new_data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::operator=(double value) { auto new_data = cJSON_CreateNumber(value); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = new_data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::set(bool value) { auto new_data = cJSON_CreateBool(value ? cJSON_True : cJSON_False); if (cJSON_IsArray(parent)) { cJSON_ReplaceItemViaPointer(parent, data, new_data); } else if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = new_data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, new_data); data = new_data; } return *this; } Value& Value::operator=(const Value& other) { if (this != &other) { if (parent == nullptr) { // We're the root, replace it all. cJSON_Delete(data); data = other.data; } else { cJSON_ReplaceItemInObjectCaseSensitive(parent, data->string, other.data); } } return *this; } bool Value::operator==(const std::string& s) const { return cJSON_IsString(data) && s == data->valuestring; } bool Value::operator==(int value) const { return cJSON_IsNumber(data) && value == data->valueint; } bool Value::operator==(double value) const { return cJSON_IsNumber(data) && value == data->valuedouble; } Value::operator std::string() const { return cJSON_IsString(data) ? data->valuestring : ""; } std::string Value::get_string(const std::string& default_value) const { auto res = default_value; if (cJSON_IsString(data)) { res = data->valuestring; } return res; } int Value::get_int(int default_value) const { auto res = default_value; if (cJSON_IsNumber(data)) { res = data->valueint; } return res; } bool Value::get_bool(bool default_value) const { auto res = default_value; if (cJSON_IsBool(data)) { res = static_cast<bool>(cJSON_IsTrue(data)); } return res; } Value::operator int() const { return cJSON_IsNumber(data) ? data->valueint : 0; } Value::operator double() const { return cJSON_IsNumber(data) ? data->valuedouble : 0; } Value::operator bool() const { return cJSON_IsBool(data) && cJSON_IsTrue(data); } int Value::get_array_size() const { return cJSON_GetArraySize(data); } std::string Value::get_name() const { return data->string == nullptr ? "" : data->string; } void Value::get_member_names(std::vector<std::string>& names) const { // Get names of this nodes child and its siblings cJSON* curr = data; if (curr != nullptr && curr->child != nullptr) { curr = curr->child; while (curr != nullptr && curr->string != nullptr) { names.emplace_back(curr->string); curr = curr->next; } } } } } } <|endoftext|>
<commit_before>#include "core/stringtable.h" #include "core/stringutils.h" #include <algorithm> namespace euphoria::core { Table<std::string> TableFromCsv(const std::string& data, const CsvParserOptions& options) { const auto AddRowToTable = [](Table<std::string>* table, const std::vector<std::string>& row) { if (row.empty()) { return; } table->NewRow(row); }; auto file = TextFileParser {data}; Table<std::string> table; std::vector<std::string> row; std::stringstream ss; bool inside_string = false; bool added = false; bool was_from_string = false; while (file.HasMore()) { const auto c = file.ReadChar(); if (inside_string) { if (c == options.str) { if (file.PeekChar() == options.str) { ss << c; file.ReadChar(); } else { inside_string = false; } } else { ss << c; } } else { if (c == options.str) { inside_string = true; was_from_string = true; added = true; } else if (c == options.delim) { auto data = ss.str(); if(!was_from_string && options.trim == CsvTrim::Trim) { data = Trim(data); } row.push_back(data); ss.str(""); added = false; was_from_string = false; } else if (c == '\n') { if (added) { auto data = ss.str(); if(!was_from_string && options.trim == CsvTrim::Trim) { data = Trim(data); } row.push_back(data); } ss.str(""); AddRowToTable(&table, row); row.resize(0); added = false; was_from_string = false; } else { if(was_from_string) { // skip // todo: error on non whitespace? } else { ss << c; added = true; } } } } if (added) { auto data = ss.str(); if(!was_from_string && options.trim == CsvTrim::Trim) { data = Trim(data); } row.push_back(data); } AddRowToTable(&table, row); return table; } int WidthOfString(const std::string& t) { int w = 0; for (auto c: t) { if (c == '\n') { w = 0; } else { w += 1; } } return w; } int ColumnWidth(const Table<std::string>& t, int c) { int width = 0; for (size_t y = 0; y < t.Height(); y += 1) { width = std::max<int>(width, WidthOfString(t.Value(c, y))); } return width; } std::vector<int> ColumnWidths(const Table<std::string>& table, int extra) { const auto number_of_cols = table.Width(); std::vector<int> sizes(number_of_cols); for (size_t i = 0; i < number_of_cols; ++i) { sizes[i] = ColumnWidth(table, i) + extra; } return sizes; } void PrintTableSimple(std::ostream& out, const Table<std::string>& table) { // todo: cleanup this function... const auto begin_str_padding = 1; const auto end_space_padding = 3; const auto begin_str = std::string(begin_str_padding, ' '); const auto end_str = std::string(end_space_padding, ' '); const auto number_of_cols = table.Width(); const auto number_of_rows = table.Height(); const std::vector<int> sizes = ColumnWidths(table, 1); const auto total_padding = begin_str_padding + end_space_padding; for (size_t row = 0; row < number_of_rows; ++row) { for (size_t col = 0; col < number_of_cols; ++col) { const auto cell = begin_str + table.Value(col, row); int line_length = 0; for (auto c: cell) { out << c; line_length += 1; if (c == '\n') { line_length = 0; for (int subcol = 0; subcol < col; subcol += 1) { out << begin_str; out << std::string(sizes[subcol], ' '); out << end_str; } } } if (col != number_of_cols - 1) { for (size_t i = line_length; i < sizes[col] + total_padding; ++i) { out << ' '; } } } out << '\n'; if (row == 0) { for (size_t col = 0; col < number_of_cols; ++col) { const auto row_text = std::string(sizes[col] + begin_str_padding, '-') + std::string(end_space_padding, ' '); out << row_text; } out << '\n'; } } } void PrintTableGrid(std::ostream& out, const Table<std::string>& table) { const std::vector<int> sizes = ColumnWidths(table, 0); constexpr auto internal_space = 1; auto some_space = [&out](int spaces, char c = ' ') { for (int i = 0; i < spaces; i += 1) { out << c; } }; auto horizontal_line = [internal_space, &some_space, &out, &sizes]() { out << '+'; for (auto s: sizes) { some_space(s + internal_space * 2, '-'); out << '+'; } out << '\n'; }; horizontal_line(); for (size_t y = 0; y < table.Height(); ++y) { out << "|"; for (size_t x = 0; x < table.Width(); ++x) { const auto cell = table.Value(x, y); some_space(internal_space); out << cell; some_space(sizes[x] - cell.length()); some_space(internal_space); out << '|'; } out << '\n'; if (y == 0) { horizontal_line(); } } horizontal_line(); } } // namespace euphoria::core <commit_msg>fixed tests<commit_after>#include "core/stringtable.h" #include "core/stringutils.h" #include <algorithm> namespace euphoria::core { Table<std::string> TableFromCsv(const std::string& data, const CsvParserOptions& options) { const auto AddRowToTable = [](Table<std::string>* table, const std::vector<std::string>& row) { if (row.empty()) { return; } table->NewRow(row); }; auto file = TextFileParser {data}; Table<std::string> table; std::vector<std::string> row; std::stringstream ss; bool inside_string = false; bool added = false; bool was_from_string = false; while (file.HasMore()) { const auto c = file.ReadChar(); if (inside_string) { if (c == options.str) { if (file.PeekChar() == options.str) { ss << c; file.ReadChar(); } else { inside_string = false; } } else { ss << c; } } else { if (c == options.str) { if(added) { // todo: generate error if string contains stuff other than whitespace ss.str(""); } inside_string = true; was_from_string = true; added = true; } else if (c == options.delim) { auto data = ss.str(); if(!was_from_string && options.trim == CsvTrim::Trim) { data = Trim(data); } row.push_back(data); ss.str(""); added = false; was_from_string = false; } else if (c == '\n') { if (added) { auto data = ss.str(); if(!was_from_string && options.trim == CsvTrim::Trim) { data = Trim(data); } row.push_back(data); } ss.str(""); AddRowToTable(&table, row); row.resize(0); added = false; was_from_string = false; } else { if(was_from_string) { // skip // todo: error on non whitespace? } else { ss << c; added = true; } } } } if (added) { auto data = ss.str(); if(!was_from_string && options.trim == CsvTrim::Trim) { data = Trim(data); } row.push_back(data); } AddRowToTable(&table, row); return table; } int WidthOfString(const std::string& t) { int w = 0; for (auto c: t) { if (c == '\n') { w = 0; } else { w += 1; } } return w; } int ColumnWidth(const Table<std::string>& t, int c) { int width = 0; for (size_t y = 0; y < t.Height(); y += 1) { width = std::max<int>(width, WidthOfString(t.Value(c, y))); } return width; } std::vector<int> ColumnWidths(const Table<std::string>& table, int extra) { const auto number_of_cols = table.Width(); std::vector<int> sizes(number_of_cols); for (size_t i = 0; i < number_of_cols; ++i) { sizes[i] = ColumnWidth(table, i) + extra; } return sizes; } void PrintTableSimple(std::ostream& out, const Table<std::string>& table) { // todo: cleanup this function... const auto begin_str_padding = 1; const auto end_space_padding = 3; const auto begin_str = std::string(begin_str_padding, ' '); const auto end_str = std::string(end_space_padding, ' '); const auto number_of_cols = table.Width(); const auto number_of_rows = table.Height(); const std::vector<int> sizes = ColumnWidths(table, 1); const auto total_padding = begin_str_padding + end_space_padding; for (size_t row = 0; row < number_of_rows; ++row) { for (size_t col = 0; col < number_of_cols; ++col) { const auto cell = begin_str + table.Value(col, row); int line_length = 0; for (auto c: cell) { out << c; line_length += 1; if (c == '\n') { line_length = 0; for (int subcol = 0; subcol < col; subcol += 1) { out << begin_str; out << std::string(sizes[subcol], ' '); out << end_str; } } } if (col != number_of_cols - 1) { for (size_t i = line_length; i < sizes[col] + total_padding; ++i) { out << ' '; } } } out << '\n'; if (row == 0) { for (size_t col = 0; col < number_of_cols; ++col) { const auto row_text = std::string(sizes[col] + begin_str_padding, '-') + std::string(end_space_padding, ' '); out << row_text; } out << '\n'; } } } void PrintTableGrid(std::ostream& out, const Table<std::string>& table) { const std::vector<int> sizes = ColumnWidths(table, 0); constexpr auto internal_space = 1; auto some_space = [&out](int spaces, char c = ' ') { for (int i = 0; i < spaces; i += 1) { out << c; } }; auto horizontal_line = [internal_space, &some_space, &out, &sizes]() { out << '+'; for (auto s: sizes) { some_space(s + internal_space * 2, '-'); out << '+'; } out << '\n'; }; horizontal_line(); for (size_t y = 0; y < table.Height(); ++y) { out << "|"; for (size_t x = 0; x < table.Width(); ++x) { const auto cell = table.Value(x, y); some_space(internal_space); out << cell; some_space(sizes[x] - cell.length()); some_space(internal_space); out << '|'; } out << '\n'; if (y == 0) { horizontal_line(); } } horizontal_line(); } } // namespace euphoria::core <|endoftext|>
<commit_before>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfields(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps) { while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfields(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } void ProcessRecord(MarcUtil::Record * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::string synonyms; if (record->extractSubfields(GetTag(*primary), GetSubfields(*primary), &primary_values)) { // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto synonym_map(synonym_maps[i]); synonyms = synonym_map.find(StringUtil::Join(primary_values, ','))->second; } // Second case: Look up synonyms in all categories else { for (auto sm : synonym_maps) synonyms += sm[StringUtil::Join(primary_values, ',')]; } if (synonyms.empty()) continue; // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfields(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); File marc_output(marc_output_filename, "w"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC("110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Update add_synonyms.cc<commit_after>/** \file add_synonyms.cc * \brief Generic version for augmenting title data with synonyms found in the authority data * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* We offer a list of tags and subfields where the primary data resides along with a list of tags and subfields where the synonym data is found and a list of unused fields in the title data where the synonyms can be stored */ #include <iostream> #include <map> #include <vector> #include <cstdlib> #include "Compiler.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static unsigned modified_count(0); static unsigned record_count(0); void Usage() { std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n"; std::exit(EXIT_FAILURE); } std::string GetTag(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(0, 3); } std::string GetSubfieldCodes(const std::string &tag_and_subfields_spec) { return tag_and_subfields_spec.substr(3); } void ExtractSynonyms(File * const norm_data_marc_input, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &synonym_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> * const synonym_maps) { while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(norm_data_marc_input)) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator synonym; unsigned int i(0); for (primary = primary_tags_and_subfield_codes.begin(), synonym = synonym_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++synonym, ++i) { // Fill maps with synonyms std::vector<std::string> primary_values; std::vector<std::string> synonym_values; if (record.extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values) and record.extractSubfields(GetTag(*synonym), GetSubfieldCodes(*synonym), &synonym_values)) (*synonym_maps)[i].emplace(StringUtil::Join(primary_values, ','), StringUtil::Join(synonym_values, ',')); } } } void ProcessRecord(MarcUtil::Record * const record, const std::vector<std::map<std::string, std::string>> &synonym_maps, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes) { std::set<std::string>::const_iterator primary; std::set<std::string>::const_iterator output; unsigned int i(0); if (primary_tags_and_subfield_codes.size() == output_tags_and_subfield_codes.size()) { for (primary = primary_tags_and_subfield_codes.begin(), output = output_tags_and_subfield_codes.begin(); primary != primary_tags_and_subfield_codes.end(); ++primary, ++output, ++i) { std::vector<std::string> primary_values; std::string synonyms; if (record->extractSubfields(GetTag(*primary), GetSubfieldCodes(*primary), &primary_values)) { // First case: Look up synonyms only in one category if (i < synonym_maps.size()) { const auto synonym_map(synonym_maps[i]); synonyms = synonym_map.find(StringUtil::Join(primary_values, ','))->second; } // Second case: Look up synonyms in all categories else { for (auto sm : synonym_maps) synonyms += sm[StringUtil::Join(primary_values, ',')]; } if (synonyms.empty()) continue; // Insert synonyms // Abort if field is already populated std::string tag(GetTag(*output)); if (record->getFieldIndex(tag) != -1) Error("Field with tag " + tag + " is not empty for PPN " + record->getControlNumber() + '\n'); std::string subfield_spec = GetSubfieldCodes(*output); if (subfield_spec.size() != 1) Error("We currently only support a single subfield and thus specifying " + subfield_spec + " as output subfield is not valid\n"); Subfields subfields(' ', ' '); // <- indicators must be set explicitly although empty subfields.addSubfield(subfield_spec.at(0), synonyms); if (not(record->insertField(tag, subfields.toString()))) Warning("Could not insert field " + tag + " for PPN " + record->getControlNumber() + '\n'); ++modified_count; } } } } void InsertSynonyms(File * const marc_input, File * marc_output, const std::set<std::string> &primary_tags_and_subfield_codes, const std::set<std::string> &output_tags_and_subfield_codes, std::vector<std::map<std::string, std::string>> &synonym_maps) { MarcXmlWriter xml_writer(marc_output); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_input)) { ProcessRecord(&record, synonym_maps, primary_tags_and_subfield_codes, output_tags_and_subfield_codes); record.write(&xml_writer); ++record_count; } std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n"; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 4) Usage(); const std::string marc_input_filename(argv[1]); std::unique_ptr<File> marc_input(FileUtil::OpenInputFileOrDie(marc_input_filename)); const std::string norm_data_marc_input_filename(argv[2]); std::unique_ptr<File> norm_data_marc_input(FileUtil::OpenInputFileOrDie(norm_data_marc_input_filename)); const std::string marc_output_filename(argv[3]); if (unlikely(marc_input_filename == marc_output_filename)) Error("Title data input file name equals output file name!"); if (unlikely(norm_data_marc_input_filename == marc_output_filename)) Error("Authority data input file name equals output file name!"); File marc_output(marc_output_filename, "w"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { // Determine possible mappings const std::string AUTHORITY_DATA_PRIMARY_SPEC("110abcd:111abcd:130abcd:150abcd:151abcd"); const std::string AUTHORITY_DATA_SYNONYM_SPEC("410abcd:411abcd:430abcd:450abcd:451abcd"); const std::string TITLE_DATA_PRIMARY_SPEC("610abcd:611abcd:630abcd:650abcd:651abcd:689abcd"); const std::string TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS("180a:181a:182a:183a:184a:185a"); // Determine fields to handle std::set<std::string> primary_tags_and_subfield_codes; std::set<std::string> synonym_tags_and_subfield_codes; std::set<std::string> input_tags_and_subfield_codes; std::set<std::string> output_tags_and_subfield_codes; if (unlikely(StringUtil::Split(AUTHORITY_DATA_PRIMARY_SPEC, ":", &primary_tags_and_subfield_codes) < 1)) Error("Need at least one primary field"); if (unlikely(StringUtil::Split(AUTHORITY_DATA_SYNONYM_SPEC, ":", &synonym_tags_and_subfield_codes) < 1)) Error("Need at least one synonym field"); if (unlikely(StringUtil::Split(TITLE_DATA_PRIMARY_SPEC, ":", &input_tags_and_subfield_codes) < 1)) Error("Need at least one input field"); if (unlikely(StringUtil::Split(TITLE_DATA_UNUSED_FIELDS_FOR_SYNONYMS, ":", &output_tags_and_subfield_codes) < 1)) Error("Need at least one output field"); unsigned num_of_authority_entries(primary_tags_and_subfield_codes.size()); if (synonym_tags_and_subfield_codes.size() != num_of_authority_entries) Error("Number of authority primary specs must match number of synonym specs"); if (input_tags_and_subfield_codes.size() != output_tags_and_subfield_codes.size()) Error("Number of fields title entry specs must match number of output specs"); std::vector<std::map<std::string, std::string>> synonym_maps(num_of_authority_entries, std::map<std::string, std::string>()); // Extract the synonyms from authority data ExtractSynonyms(norm_data_marc_input.get(), primary_tags_and_subfield_codes, synonym_tags_and_subfield_codes, &synonym_maps); // Iterate over the title data InsertSynonyms(marc_input.get(), &marc_output, input_tags_and_subfield_codes, output_tags_and_subfield_codes, synonym_maps); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/** \file Clean up the tags database * \brief Remove unreferenced tags and tag references from the database * \author Johannes Riedl */ /* Copyright (C) 2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" #include "VuFind.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--input-format=(marc-21|marc-xml)] marc_input\n"; std::exit(EXIT_FAILURE); } void ExtractAllRecordIDs(MARC::Reader * const marc_reader, std::unordered_set<std::string> * const all_record_ids) { while (const MARC::Record &record = marc_reader->read()) all_record_ids->emplace(record.getControlNumber()); } void GetUnreferencedPPNsFromDB(DbConnection * const db_connection, const std::unordered_set<std::string> &all_record_ids, std::vector<std::string> * const unreferenced_ppns) { // Get the ppn from the resources table db_connection->queryOrDie("SELECT DISTINCT record_id FROM resource"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) return; while (const auto &db_row = result_set.getNextRow()) { const std::string record_id(db_row["record_id"]); if (all_record_ids.find(record_id) == all_record_ids.cend()) unreferenced_ppns->push_back(record_id); } } auto FormatSQLValue = [](const std::string term) { return "('" + term + "')"; }; void CreateTemporaryUnreferencedPPNTable(DbConnection * const db_connection, const std::vector<std::string> &unreferenced_ppns) { db_connection->queryOrDie("CREATE TEMPORARY TABLE unreferenced_ppns (`record_id` varchar(255))"); const std::string INSERT_STATEMENT_START("INSERT IGNORE INTO unreferenced_ppns VALUES "); // Only transmit a limited number of values in a bunch const long MAX_ROW_COUNT(100); for (size_t row_count(0) ; row_count < unreferenced_ppns.size(); row_count+=MAX_ROW_COUNT) { std::vector<std::string> values; std::vector<std::string> formatted_values; const auto copy_start(unreferenced_ppns.cbegin() + std::min(row_count, unreferenced_ppns.size())); std::copy_n(copy_start, std::min(MAX_ROW_COUNT, std::distance(copy_start, unreferenced_ppns.cend())), std::back_inserter(values)); std::transform(values.begin(), values.end(), std::back_inserter(formatted_values), FormatSQLValue); db_connection->queryOrDie(INSERT_STATEMENT_START + StringUtil::Join(formatted_values, ",")); } } void RemoveUnreferencedEntries(DbConnection * const db_connection) { // Delete the unreferenced IDs from the resource tags; const std::string GET_UNREFERENCED_IDS_STATEMENT( "SELECT id FROM resource where record_id IN (SELECT * FROM unreferenced_ppns)"); const std::string DELETE_UNREFERENCED_RESOURCE_TAGS_ENTRIES( "DELETE FROM resource_tags WHERE resource_id IN (" + GET_UNREFERENCED_IDS_STATEMENT + ")"); db_connection->queryOrDie(DELETE_UNREFERENCED_RESOURCE_TAGS_ENTRIES); // Delete the unused tags const std::string DELETE_UNREFERENCED_TAG_ENTRIES( "DELETE FROM tags WHERE id NOT IN (SELECT DISTINCT tag_id FROM resource_tags)"); db_connection->queryOrDie(DELETE_UNREFERENCED_TAG_ENTRIES); // Delete the unused resources const std::string DELETE_UNREFERENCED_RESOURCES_ENTRIES( "DELETE FROM resource WHERE id NOT IN (SELECT resource_id FROM resource_tags) \ AND id NOT IN (SELECT resource_id FROM user_resource)"); db_connection->queryOrDie(DELETE_UNREFERENCED_RESOURCES_ENTRIES); } } // unnamed namespace int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 2 and argc != 3) Usage(); MARC::FileType reader_type(MARC::FileType::AUTO); if (argc == 3) { if (std::strcmp(argv[1], "--input-format=marc-21") == 0) reader_type = MARC::FileType::BINARY; else if (std::strcmp(argv[1], "--input-format=marc-xml") == 0) reader_type = MARC::FileType::XML; else Usage(); ++argv, --argc; } const std::string marc_input_filename(argv[1]); try { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, reader_type)); std::unordered_set<std::string> all_record_ids; ExtractAllRecordIDs(marc_reader.get(), &all_record_ids); std::vector<std::string> unreferenced_ppns; GetUnreferencedPPNsFromDB(&db_connection, all_record_ids, &unreferenced_ppns); CreateTemporaryUnreferencedPPNTable(&db_connection, unreferenced_ppns); RemoveUnreferencedEntries(&db_connection); std::cerr << "Removed superfluous references for " << unreferenced_ppns.size() << " PPN(s)\n"; } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <commit_msg>Slight improvements<commit_after>/** \file Clean up the tags database * \brief Remove unreferenced tags and tag references from the database * \author Johannes Riedl */ /* Copyright (C) 2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <cstdlib> #include "DbConnection.h" #include "DbResultSet.h" #include "MARC.h" #include "StringUtil.h" #include "util.h" #include "VuFind.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--input-format=(marc-21|marc-xml)] marc_input\n"; std::exit(EXIT_FAILURE); } void ExtractAllRecordIDs(MARC::Reader * const marc_reader, std::unordered_set<std::string> * const all_record_ids) { while (const MARC::Record &record = marc_reader->read()) all_record_ids->emplace(record.getControlNumber()); } void GetUnreferencedPPNsFromDB(DbConnection * const db_connection, const std::unordered_set<std::string> &all_record_ids, std::vector<std::string> * const unreferenced_ppns) { // Get the ppn from the resources table db_connection->queryOrDie("SELECT DISTINCT record_id FROM resource"); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) return; while (const auto &db_row = result_set.getNextRow()) { const std::string record_id(db_row["record_id"]); if (all_record_ids.find(record_id) == all_record_ids.cend()) unreferenced_ppns->push_back(record_id); } } auto FormatSQLValue = [](const std::string term) { return "('" + term + "')"; }; void CreateTemporaryUnreferencedPPNTable(DbConnection * const db_connection, const std::vector<std::string> &unreferenced_ppns) { db_connection->queryOrDie("CREATE TEMPORARY TABLE unreferenced_ppns (`record_id` varchar(255))"); const std::string INSERT_STATEMENT_START("INSERT IGNORE INTO unreferenced_ppns VALUES "); // Only transmit a limited number of values in a bunch const long MAX_ROW_COUNT(100); for (size_t row_count(0) ; row_count < unreferenced_ppns.size(); row_count+=MAX_ROW_COUNT) { std::vector<std::string> values; std::vector<std::string> formatted_values; const auto copy_start(unreferenced_ppns.cbegin() + std::min(row_count, unreferenced_ppns.size())); std::copy_n(copy_start, std::min(MAX_ROW_COUNT, std::distance(copy_start, unreferenced_ppns.cend())), std::back_inserter(values)); std::transform(values.begin(), values.end(), std::back_inserter(formatted_values), FormatSQLValue); db_connection->queryOrDie(INSERT_STATEMENT_START + StringUtil::Join(formatted_values, ",")); } } void RemoveUnreferencedEntries(DbConnection * const db_connection) { // Delete the unreferenced IDs from the resource tags; const std::string GET_UNREFERENCED_IDS_STATEMENT( "SELECT id FROM resource where record_id IN (SELECT * FROM unreferenced_ppns)"); const std::string DELETE_UNREFERENCED_RESOURCE_TAGS_ENTRIES( "DELETE FROM resource_tags WHERE resource_id IN (" + GET_UNREFERENCED_IDS_STATEMENT + ")"); db_connection->queryOrDie(DELETE_UNREFERENCED_RESOURCE_TAGS_ENTRIES); // Delete the unused tags const std::string DELETE_UNREFERENCED_TAG_ENTRIES( "DELETE FROM tags WHERE id NOT IN (SELECT DISTINCT tag_id FROM resource_tags)"); db_connection->queryOrDie(DELETE_UNREFERENCED_TAG_ENTRIES); // Delete the unused resources const std::string DELETE_UNREFERENCED_RESOURCES_ENTRIES( "DELETE FROM resource WHERE id NOT IN (SELECT resource_id FROM resource_tags) \ AND id NOT IN (SELECT resource_id FROM user_resource)"); db_connection->queryOrDie(DELETE_UNREFERENCED_RESOURCES_ENTRIES); } } // unnamed namespace int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 2 and argc != 3) Usage(); MARC::FileType reader_type(MARC::FileType::AUTO); if (argc == 3) { if (std::strcmp(argv[1], "--input-format=marc-21") == 0) reader_type = MARC::FileType::BINARY; else if (std::strcmp(argv[1], "--input-format=marc-xml") == 0) reader_type = MARC::FileType::XML; else Usage(); ++argv, --argc; } const std::string marc_input_filename(argv[1]); try { std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, reader_type)); std::unordered_set<std::string> all_record_ids; ExtractAllRecordIDs(marc_reader.get(), &all_record_ids); std::vector<std::string> unreferenced_ppns; GetUnreferencedPPNsFromDB(&db_connection, all_record_ids, &unreferenced_ppns); CreateTemporaryUnreferencedPPNTable(&db_connection, unreferenced_ppns); RemoveUnreferencedEntries(&db_connection); LOG_INFO("Removed superfluous references for " + std::to_string(unreferenced_ppns.size()) + " PPN(s)"); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <|endoftext|>