hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0d96c0af0d06aa404458f1a7df3bf3ee821b1e77
30,113
cc
C++
ash/shelf/shelf_drag_handle_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/shelf/shelf_drag_handle_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/shelf/shelf_drag_handle_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/app_list/test/app_list_test_helper.h" #include "ash/home_screen/drag_window_from_shelf_controller.h" #include "ash/home_screen/drag_window_from_shelf_controller_test_api.h" #include "ash/public/cpp/ash_features.h" #include "ash/session/session_controller_impl.h" #include "ash/shelf/contextual_tooltip.h" #include "ash/shelf/drag_handle.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shelf/test/shelf_layout_manager_test_base.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_clock.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" namespace ash { namespace { ShelfWidget* GetShelfWidget() { return AshTestBase::GetPrimaryShelf()->shelf_widget(); } ShelfLayoutManager* GetShelfLayoutManager() { return AshTestBase::GetPrimaryShelf()->shelf_layout_manager(); } } // namespace // Test base for unit test related to drag handle contextual nudges. class DragHandleContextualNudgeTest : public ShelfLayoutManagerTestBase { public: DragHandleContextualNudgeTest() { scoped_feature_list_.InitAndEnableFeature(ash::features::kContextualNudges); } ~DragHandleContextualNudgeTest() override = default; DragHandleContextualNudgeTest(const DragHandleContextualNudgeTest& other) = delete; DragHandleContextualNudgeTest& operator=( const DragHandleContextualNudgeTest& other) = delete; // ShelfLayoutManagerTestBase: void SetUp() override { ShelfLayoutManagerTestBase::SetUp(); test_clock_.Advance(base::TimeDelta::FromHours(2)); contextual_tooltip::OverrideClockForTesting(&test_clock_); } void TearDown() override { contextual_tooltip::ClearClockOverrideForTesting(); AshTestBase::TearDown(); } base::SimpleTestClock test_clock_; private: base::test::ScopedFeatureList scoped_feature_list_; }; TEST_F(DragHandleContextualNudgeTest, ShowDragHandleNudgeWithTimer) { // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); // The drag handle should be showing but the nudge should not. A timer to show // the nudge should be initialized. EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Firing the timer should show the drag handle nudge. GetShelfWidget()->GetDragHandle()->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); } TEST_F(DragHandleContextualNudgeTest, HideDragHandleNudgeHiddenOnMinimize) { // Creates a test window to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); // The drag handle and nudge should be showing after the timer fires. GetShelfWidget()->GetDragHandle()->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Minimizing the widget should hide the drag handle and nudge. widget->Minimize(); EXPECT_FALSE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); } // Tests that the drag handle nudge nudge is hidden when closing the widget and // setting the ShelfBackgroundType to kHomeLauncher. TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeHiddenOnClose) { // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); DragHandle* const drag_handle = GetShelfWidget()->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); // Close the widget. widget->CloseWithReason(views::Widget::ClosedReason::kCloseButtonClicked); EXPECT_FALSE(drag_handle->GetVisible()); EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); } // Checks that the shelf cannot be auto hidden while animating shelf drag handle // nudge. TEST_F(DragHandleContextualNudgeTest, HideDragHandleDoesNotInteruptShowNudgeAnimation) { GetPrimaryShelf()->SetAutoHideBehavior(ShelfAutoHideBehavior::kAlways); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); ui::ScopedAnimationDurationScaleMode normal_animation_duration( ui::ScopedAnimationDurationScaleMode::SLOW_DURATION); GetShelfWidget()->GetDragHandle()->MaybeShowDragHandleNudge(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->show_nudge_animation_in_progress()); GetShelfLayoutManager()->UpdateAutoHideState(); // Shelf auto hide should not interrupt animations to show drag handle nudge. // Showing the nudge while hiding the shelf is not intended behavior. EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->show_nudge_animation_in_progress()); } // Checks that the drag handle nudge is not shown when entering kInApp with // shelf autohide turned on. TEST_F(DragHandleContextualNudgeTest, DragHandleNotShownForAutoHideShelf) { GetPrimaryShelf()->SetAutoHideBehavior(ShelfAutoHideBehavior::kAlways); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->show_nudge_animation_in_progress()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); } TEST_F(DragHandleContextualNudgeTest, DoNotShowNudgeWithoutDragHandle) { // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); // Minimizing the widget should hide the drag handle and nudge. widget->Minimize(); EXPECT_FALSE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); } TEST_F(DragHandleContextualNudgeTest, ContinueShowingDragHandleNudgeOnActiveWidgetChanged) { // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); GetShelfWidget()->GetDragHandle()->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Maximizing and showing a different widget should not hide the drag handle // or nudge. views::Widget* new_widget = CreateTestWidget(); new_widget->Maximize(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); } TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeShownInAppShelf) { // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); // Drag handle and nudge should not be shown in clamshell mode. EXPECT_FALSE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Test that the first time a user transitions into tablet mode with a // maximized window will show the drag nudge immedietly. The drag handle nudge // should not be visible yet and the timer to show it should be set. TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); EXPECT_TRUE(GetShelfWidget() ->GetDragHandle() ->has_show_drag_handle_timer_for_testing()); // Firing the timer should show the nudge for the first time. The nudge should // remain visible until the shelf state changes so the timer to hide it should // not be set. GetShelfWidget()->GetDragHandle()->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); EXPECT_FALSE(GetShelfWidget() ->GetDragHandle() ->has_hide_drag_handle_timer_for_testing()); // Leaving tablet mode should hide the nudge. TabletModeControllerTestApi().LeaveTabletMode(); EXPECT_FALSE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Reentering tablet mode should show the drag handle but the nudge should // not. No timer should be set to show the nudge. TabletModeControllerTestApi().EnterTabletMode(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); EXPECT_FALSE(GetShelfWidget() ->GetDragHandle() ->has_show_drag_handle_timer_for_testing()); // Advance time for more than a day (which should enable the nudge again). test_clock_.Advance(base::TimeDelta::FromHours(25)); // Reentering tablet mode with a maximized widget should immedietly show the // drag handle and set a timer to show the nudge. TabletModeControllerTestApi().LeaveTabletMode(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Firing the timer should show the nudge. EXPECT_TRUE(GetShelfWidget() ->GetDragHandle() ->has_show_drag_handle_timer_for_testing()); GetShelfWidget()->GetDragHandle()->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); EXPECT_FALSE(GetShelfWidget() ->GetDragHandle() ->has_show_drag_handle_timer_for_testing()); // On subsequent shows, the nudge should be hidden after a timeout. EXPECT_TRUE(GetShelfWidget() ->GetDragHandle() ->has_hide_drag_handle_timer_for_testing()); } TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeShownOnTap) { // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_EQ(ShelfBackgroundType::kInApp, GetShelfWidget()->GetBackgroundType()); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); EXPECT_TRUE(GetShelfWidget() ->GetDragHandle() ->has_show_drag_handle_timer_for_testing()); GetShelfWidget()->GetDragHandle()->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Exiting and re-entering tablet should hide the nudge and put the shelf into // the default kInApp shelf state. TabletModeControllerTestApi().LeaveTabletMode(); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_FALSE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Tapping the drag handle should show the drag handle nudge immedietly and // the show nudge timer should be set. GetEventGenerator()->GestureTapAt( GetShelfWidget()->GetDragHandle()->GetBoundsInScreen().CenterPoint()); EXPECT_FALSE(GetShelfWidget() ->GetDragHandle() ->has_show_drag_handle_timer_for_testing()); EXPECT_TRUE(GetShelfWidget()->GetDragHandle()->GetVisible()); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); EXPECT_TRUE(GetShelfWidget() ->GetDragHandle() ->has_hide_drag_handle_timer_for_testing()); } TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeNotShownForHiddenShelf) { GetPrimaryShelf()->SetAutoHideBehavior(ShelfAutoHideBehavior::kAlways); TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); // The shelf is hidden, so the drag handle nudge should not be shown. EXPECT_TRUE(drag_handle->GetVisible()); EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); EXPECT_FALSE(drag_handle->has_show_drag_handle_timer_for_testing()); PrefService* const prefs = Shell::Get()->session_controller()->GetLastActiveUserPrefService(); // Back gesture nudge should be allowed if the shelf is hidden. EXPECT_TRUE(contextual_tooltip::ShouldShowNudge( prefs, contextual_tooltip::TooltipType::kBackGesture, nullptr)); // Swipe up to show the shelf - this should schedule the drag handle nudge. SwipeUpOnShelf(); // Back gesture nudge should be disallowed at this time, given that the drag // handle nudge can be shown. EXPECT_FALSE(contextual_tooltip::ShouldShowNudge( prefs, contextual_tooltip::TooltipType::kBackGesture, nullptr)); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); } // Tests that drag handle show is canceled when the shelf is hidden while the // drag handle is scheduled to be shown. TEST_F(DragHandleContextualNudgeTest, HidingShelfCancelsDragHandleShow) { GetPrimaryShelf()->SetAutoHideBehavior(ShelfAutoHideBehavior::kAlways); TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); // The shelf is hidden, so the drag handle nudge should not be shown. EXPECT_TRUE(drag_handle->GetVisible()); EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); EXPECT_FALSE(drag_handle->has_show_drag_handle_timer_for_testing()); // Swipe up to show the shelf - this should schedule the drag handle nudge. SwipeUpOnShelf(); EXPECT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); // Hide the shelf, and verify the drag handle show is canceled. SwipeDownOnShelf(); EXPECT_FALSE(drag_handle->has_show_drag_handle_timer_for_testing()); EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); PrefService* const prefs = Shell::Get()->session_controller()->GetLastActiveUserPrefService(); // Back gesture nudge should be allowed if the shelf is hidden. EXPECT_TRUE(contextual_tooltip::ShouldShowNudge( prefs, contextual_tooltip::TooltipType::kBackGesture, nullptr)); } // Tests that the drag handle nudge is not hidden when the user extends the // hotseat. TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeNotHiddenByExtendingHotseat) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); // Swipe up to extend the hotseat - verify that the drag handle remain // visible. SwipeUpOnShelf(); EXPECT_TRUE(drag_handle->GetVisible()); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); } // Tests that the drag handle nudge is horizontally centered in screen, and // drawn above the shelf drag handle, even after display bounds are updated. TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeBoundsInScreen) { UpdateDisplay("675x1200"); TabletModeControllerTestApi().EnterTabletMode(); views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); EXPECT_TRUE(drag_handle->GetVisible()); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); // Calculates absolute difference between horizontal margins of |inner| rect // within |outer| rect. auto margin_diff = [](const gfx::Rect& inner, const gfx::Rect& outer) -> int { const int left = inner.x() - outer.x(); EXPECT_GE(left, 0); const int right = outer.right() - inner.right(); EXPECT_GE(right, 0); return std::abs(left - right); }; // Verify that nudge widget is centered in shelf. gfx::Rect shelf_bounds = shelf_widget->GetWindowBoundsInScreen(); gfx::Rect nudge_bounds = drag_handle->drag_handle_nudge_for_testing() ->label() ->GetBoundsInScreen(); EXPECT_LE(margin_diff(nudge_bounds, shelf_bounds), 1); // Verify that the nudge vertical bounds - within the shelf bounds, and above // the drag handle. gfx::Rect drag_handle_bounds = drag_handle->GetBoundsInScreen(); EXPECT_LE(shelf_bounds.y(), nudge_bounds.y()); EXPECT_LE(nudge_bounds.bottom(), drag_handle_bounds.y()); // Change the display bounds, and verify the updated drag handle bounds. UpdateDisplay("1200x675"); EXPECT_TRUE( GetShelfWidget()->GetDragHandle()->gesture_nudge_target_visibility()); // Verify that nudge widget is centered in shelf. shelf_bounds = shelf_widget->GetWindowBoundsInScreen(); nudge_bounds = drag_handle->drag_handle_nudge_for_testing() ->label() ->GetBoundsInScreen(); EXPECT_LE(margin_diff(nudge_bounds, shelf_bounds), 1); // Verify that the nudge vertical bounds - within the shelf bounds, and above // the drag handle. drag_handle_bounds = drag_handle->GetBoundsInScreen(); EXPECT_LE(shelf_bounds.y(), nudge_bounds.y()); EXPECT_LE(nudge_bounds.bottom(), drag_handle_bounds.y()); } // Tests that drag handle does not hide during the window drag from shelf // gesture. TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeNotHiddenDuringWindowDragFromShelf) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); TabletModeControllerTestApi().LeaveTabletMode(); // Advance time for more than a day (which should enable the nudge again). test_clock_.Advance(base::TimeDelta::FromHours(25)); TabletModeControllerTestApi().EnterTabletMode(); EXPECT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->has_hide_drag_handle_timer_for_testing()); const gfx::Point start = drag_handle->GetBoundsInScreen().CenterPoint(); // Simulates window drag from shelf gesture, and verifies that the timer to // hide the drag handle nudge is canceled when the window drag from shelf // starts. GetEventGenerator()->GestureScrollSequenceWithCallback( start, start + gfx::Vector2d(0, -200), base::TimeDelta::FromMilliseconds(50), /*num_steps = */ 6, base::BindRepeating( [](DragHandle* drag_handle, ui::EventType type, const gfx::Vector2dF& offset) { DragWindowFromShelfController* window_drag_controller = GetShelfLayoutManager()->window_drag_controller_for_testing(); if (window_drag_controller && window_drag_controller->dragged_window()) { EXPECT_FALSE( drag_handle->has_hide_drag_handle_timer_for_testing()); } const bool scroll_end = type == ui::ET_GESTURE_SCROLL_END; EXPECT_EQ(!scroll_end, drag_handle->gesture_nudge_target_visibility()); }, drag_handle)); // The nudge should be hidden when the gesture completes. EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); } // Tests that window drag from shelf cancels drag handle contextual nudge from // showing. TEST_F(DragHandleContextualNudgeTest, DragHandleNudgeNotShownDuringWindowDragFromShelf) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); EXPECT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); const gfx::Point start = GetShelfWidget()->GetWindowBoundsInScreen().CenterPoint(); // Simulates window drag from shelf gesture, and verifies that the timer to // show the drag handle nudge is canceled when the window drag from shelf // starts. GetEventGenerator()->GestureScrollSequenceWithCallback( start, start + gfx::Vector2d(0, -200), base::TimeDelta::FromMilliseconds(50), /*num_steps = */ 6, base::BindRepeating( [](DragHandle* drag_handle, ui::EventType type, const gfx::Vector2dF& offset) { DragWindowFromShelfController* window_drag_controller = GetShelfLayoutManager()->window_drag_controller_for_testing(); if (window_drag_controller && window_drag_controller->dragged_window()) { EXPECT_FALSE( drag_handle->has_show_drag_handle_timer_for_testing()); // Attempt to schedule the nudge should fail. if (type != ui::ET_GESTURE_SCROLL_END) { drag_handle->ScheduleShowDragHandleNudge(); EXPECT_FALSE( drag_handle->has_show_drag_handle_timer_for_testing()); } } EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); }, drag_handle)); // The nudge should be hidden when the gesture completes. EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); } // Tests that drag handle nudge gets hidden when the user performs window drag // from shelf to home. TEST_F(DragHandleContextualNudgeTest, FlingFromShelfToHomeHidesTheNudge) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); const gfx::Point start = drag_handle->GetBoundsInScreen().CenterPoint(); // Simulates window drag from shelf gesture, and verifies that the timer to // hide the drag handle nudge is canceled when the window drag from shelf // starts. GetEventGenerator()->GestureScrollSequenceWithCallback( start, start + gfx::Vector2d(0, -300), base::TimeDelta::FromMilliseconds(10), /*num_steps = */ 6, base::BindRepeating( [](DragHandle* drag_handle, ui::EventType type, const gfx::Vector2dF& offset) { const bool scroll_end = type == ui::ET_GESTURE_SCROLL_END; EXPECT_EQ(!scroll_end, drag_handle->gesture_nudge_target_visibility()); }, drag_handle)); // The nudge should be hidden when the gesture completes. EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); GetAppListTestHelper()->CheckVisibility(true); } // Tests that drag handle nudge gets hidden when the user performs window drag // from shelf, even if the gesture does not end up going home. TEST_F(DragHandleContextualNudgeTest, DragFromShelfToHomeHidesTheNudge) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); const gfx::Point start = drag_handle->GetBoundsInScreen().CenterPoint(); // Simulates window drag from shelf gesture, and verifies that the timer to // hide the drag handle nudge is canceled when the window drag from shelf // starts. GetEventGenerator()->GestureScrollSequenceWithCallback( start, start + gfx::Vector2d(0, -150), base::TimeDelta::FromMilliseconds(500), /*num_steps = */ 20, base::BindRepeating( [](DragHandle* drag_handle, ui::EventType type, const gfx::Vector2dF& offset) { DragWindowFromShelfController* window_drag_controller = GetShelfLayoutManager()->window_drag_controller_for_testing(); if (window_drag_controller && window_drag_controller->dragged_window()) { DragWindowFromShelfControllerTestApi().WaitUntilOverviewIsShown( window_drag_controller); } const bool scroll_end = type == ui::ET_GESTURE_SCROLL_END; EXPECT_EQ(!scroll_end, drag_handle->gesture_nudge_target_visibility()); }, drag_handle)); // The nudge should be hidden when the gesture completes. EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); GetAppListTestHelper()->CheckVisibility(false); EXPECT_TRUE(Shell::Get()->overview_controller()->InOverviewSession()); } // Tests that scheduled drag handle nudge show is canceled when overview starts. TEST_F(DragHandleContextualNudgeTest, OverviewCancelsNudgeShow) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); Shell::Get()->overview_controller()->StartOverview(); ASSERT_FALSE(drag_handle->has_show_drag_handle_timer_for_testing()); } // Tests that tapping the drag handle can shown drag handle nudge in overview. TEST_F(DragHandleContextualNudgeTest, DragHandleTapShowNudgeInOverview) { TabletModeControllerTestApi().EnterTabletMode(); // Creates a widget to put shelf into in-app state. views::Widget* widget = CreateTestWidget(); widget->Maximize(); ShelfWidget* const shelf_widget = GetShelfWidget(); DragHandle* const drag_handle = shelf_widget->GetDragHandle(); ASSERT_TRUE(drag_handle->has_show_drag_handle_timer_for_testing()); drag_handle->fire_show_drag_handle_timer_for_testing(); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); TabletModeControllerTestApi().LeaveTabletMode(); TabletModeControllerTestApi().EnterTabletMode(); Shell::Get()->overview_controller()->StartOverview(); ASSERT_FALSE(drag_handle->has_show_drag_handle_timer_for_testing()); GetEventGenerator()->GestureTapAt( drag_handle->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(drag_handle->GetVisible()); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); EXPECT_TRUE(drag_handle->has_hide_drag_handle_timer_for_testing()); drag_handle->fire_hide_drag_handle_timer_for_testing(); EXPECT_FALSE(drag_handle->gesture_nudge_target_visibility()); // Tapping the drag handle again will show the nudge again. GetEventGenerator()->GestureTapAt( drag_handle->GetBoundsInScreen().CenterPoint()); EXPECT_TRUE(drag_handle->gesture_nudge_target_visibility()); } } // namespace ash
42.412676
80
0.745459
sarang-apps
0d98aabd50b6a9bbb935961018a67849b610b39d
10,763
cpp
C++
Bicycle.cpp
MKoi/BicycleAdventure
238464e1546edd332522e375e92c022ec0174dd9
[ "MIT" ]
null
null
null
Bicycle.cpp
MKoi/BicycleAdventure
238464e1546edd332522e375e92c022ec0174dd9
[ "MIT" ]
null
null
null
Bicycle.cpp
MKoi/BicycleAdventure
238464e1546edd332522e375e92c022ec0174dd9
[ "MIT" ]
null
null
null
#include "pch.h" #include "Bicycle.h" #include "GameArea.h" #include <vector> using namespace DirectX; using namespace std; using namespace Windows::Storage; Bicycle::Bicycle(b2World* world, const b2Vec2& pos, const Physics::Parameters& params, GameAudio* audio) : m_wheelRadius(0.5f), m_hubRadius(m_wheelRadius/3.0f), m_controls(this), m_fWheelCenter(2 * m_wheelRadius, 0.0f), m_rWheelCenter(-2 * m_wheelRadius, 0.0f), m_pedalOffset(m_hubRadius, 0.0f), m_frame(nullptr), m_frontWheel(nullptr), m_rearWheel(nullptr), m_pedals(nullptr), m_frontJoint(nullptr), m_rearJoint(nullptr), m_pedalJoint(nullptr), m_frameGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST), m_fWheelGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST), m_rWheelGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST), m_pedalsGfx(D3D_PRIMITIVE_TOPOLOGY::D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST), m_dirt(world), m_rearWheelContacts(0), m_frontWheelContacts(0), m_pedalAngle(0.0f), m_audio(audio) { b2Vec2 framePos = pos + b2Vec2(2 * m_wheelRadius, m_wheelRadius); m_vertices[e_hub].Set(-0.2f, 0.0f); m_vertices[e_handle].Set(0.8f, 1.0f); m_vertices[e_saddle].Set(-0.5f, 1.0f); // m_fWheelCenter.Set(2*m_wheelRadius, 0.0f); // m_rWheelCenter.Set(-2*m_wheelRadius, 0.0f); // m_pedalOffset.Set(m_hubRadius, 0.0f); m_frame = Physics::CreatePolygon(world, params, m_vertices, e_size, framePos); m_frontWheel = Physics::CreateCircle(world, params, m_wheelRadius, m_frame->GetWorldPoint(m_fWheelCenter)); m_rearWheel = Physics::CreateCircle(world, params, m_wheelRadius, m_frame->GetWorldPoint(m_rWheelCenter)); m_pedals = Physics::CreateCircle(world, params, m_hubRadius, m_frame->GetWorldPoint(m_vertices[e_hub])); CreateWheelJoints(); m_pedalJoint = Physics::CreateRevoluteJoint(m_frame, m_pedals, m_pedals->GetPosition()); CreateFrameGfx(); CreateWheelGfx(); CreatePedalsGfx(); AddPart(m_frontWheel, &m_fWheelGfx); AddPart(m_rearWheel, &m_rWheelGfx); AddPart(m_frame, &m_frameGfx); AddPart(m_pedals, &m_pedalsGfx); m_pedalAngle = m_pedals->GetAngle(); } void Bicycle::Reset(const b2Vec2& pos) { b2Vec2 framePos = pos + b2Vec2(2 * m_wheelRadius, m_wheelRadius); Physics::ResetBody(m_frame, framePos); Physics::ResetBody(m_frontWheel, m_frame->GetWorldPoint(m_fWheelCenter)); Physics::ResetBody(m_rearWheel, m_frame->GetWorldPoint(m_rWheelCenter)); Physics::ResetBody(m_pedals, m_frame->GetWorldPoint(m_vertices[e_hub])); CreateWheelJoints(); m_controls.Reset(); m_dirt.Clear(); Update(0.0f); m_rearWheelContacts = 0; m_frontWheelContacts = 0; } void Bicycle::StartSound() { if (OnGround()) { m_audio->Play(GameAudio::eRolling); } } void Bicycle::SaveState(Streams::DataWriter^ state) const { GameObject::SaveState(state); state->WriteInt32(m_rearWheelContacts); state->WriteInt32(m_frontWheelContacts); } void Bicycle::RestoreState(Streams::DataReader^ state) { GameObject::RestoreState(state); m_rearWheelContacts = state->ReadInt32(); m_frontWheelContacts = state->ReadInt32(); } /* void Bicycle::DrawDebugData(Graphics* draw) const { if (!RearWheelGround()) draw->DrawSolidCircle(m_rearWheel->GetPosition(), m_wheelRadius*1.2f, b2Vec2_zero, Graphics::red); if (!FrontWheelGround()) draw->DrawSolidCircle(m_frontWheel->GetPosition(), m_wheelRadius*1.2f, b2Vec2_zero, Graphics::red); } */ void Bicycle::Draw(Renderer^ renderBatch) const { m_dirt.Draw(renderBatch); GameObject::Draw(renderBatch); } void Bicycle::Update(float dt) { m_controls.Update(dt); GameObject::Update(dt); CheckJointForces(dt); m_dirt.Update(dt); EmitDirt(); PlayPedalSound(); PlayWheelSound(); } void Bicycle::BeginContact(b2Contact* c) { if (Physics::Touching(c, m_rearWheel, Physics::GroundCategory)) { m_rearWheelContacts++; } else if (Physics::Touching(c, m_rearWheel, Physics::WallCategory)) { m_rearWheelContacts++; } else if (Physics::Touching(c, m_frontWheel, Physics::GroundCategory)) { m_frontWheelContacts++; } else if (Physics::Touching(c, m_frontWheel, Physics::WallCategory)) { m_frontWheelContacts++; } } void Bicycle::EndContact(b2Contact* c) { if (Physics::Touching(c, m_rearWheel, Physics::GroundCategory)) { m_rearWheelContacts--; } else if (Physics::Touching(c, m_rearWheel, Physics::WallCategory)) { m_rearWheelContacts--; } else if (Physics::Touching(c, m_frontWheel, Physics::GroundCategory)) { m_frontWheelContacts--; } else if (Physics::Touching(c, m_frontWheel, Physics::WallCategory)) { m_frontWheelContacts--; } } void Bicycle::SetSpeed(float speed, bool rollFree) { const float pedalToWheelRatio = 5.0f; const float maxTorque = 20.0f; if (m_rearJoint != nullptr) { Physics::SetMotor(m_rearJoint, speed, maxTorque, !rollFree); } Physics::SetMotor(m_pedalJoint, speed/pedalToWheelRatio, maxTorque, true); } void Bicycle::CreateFrameGfx() { const float ratio = 0.06f; Graphics::CreateSolidLine(m_vertices[e_hub], m_vertices[e_handle], ratio, Graphics::red, m_frameGfx); Graphics::CreateSolidLine(m_vertices[e_handle], m_vertices[e_saddle], ratio, Graphics::red, m_frameGfx); Graphics::CreateSolidLine(m_vertices[e_saddle], m_vertices[e_hub], ratio, Graphics::red, m_frameGfx); Graphics::CreateSolidLine(m_vertices[e_saddle], m_rWheelCenter, ratio, Graphics::red, m_frameGfx); Graphics::CreateSolidLine(m_vertices[e_hub], m_rWheelCenter, ratio, Graphics::red, m_frameGfx); Graphics::CreateSolidLine(m_vertices[e_handle], m_fWheelCenter, ratio, Graphics::red, m_frameGfx); } void Bicycle::CreateWheelGfx() { const int spokeCount = 7; const float thicknessRatio = 0.02f; const float inner_r1 = 0.15f; const float inner_r2 = 0.2f; const float outer_r1 = 0.85f; const float outer_r2 = 0.9f; CreateSpokeGfx(outer_r1*m_wheelRadius, spokeCount, thicknessRatio, Graphics::black, m_fWheelGfx); //Graphics::CreateSolidCircle(b2Vec2_zero, m_wheelRadius * inner_r2, Graphics::black, m_wheelGfx); Graphics::CreateSolidCircle(b2Vec2_zero, m_wheelRadius * inner_r2, Graphics::grey, m_fWheelGfx); //Graphics::CreateSphere(b2Vec2_zero, m_wheelRadius * outer_r2, outer_r1/outer_r2, Graphics::grey, m_wheelGfx); Graphics::CreateSphere(b2Vec2_zero, m_wheelRadius, outer_r2, Graphics::black, m_fWheelGfx); m_rWheelGfx = m_fWheelGfx; } void Bicycle::CreatePedalsGfx() { const int spokeCount = 5; const float spokeThickness = 0.2f; const float pedalThickness = 0.2f; const float inner_r = 0.3f; const float outer_r = 0.6f; CreateSpokeGfx(outer_r*m_hubRadius, spokeCount, spokeThickness, Graphics::grey, m_pedalsGfx); Graphics::CreateSolidCircle(b2Vec2_zero, inner_r*m_hubRadius, Graphics::grey, m_pedalsGfx); Graphics::CreateSphere(b2Vec2_zero, m_hubRadius, outer_r, Graphics::grey, m_pedalsGfx); Graphics::CreateSolidLine(b2Vec2_zero, m_pedalOffset, pedalThickness, Graphics::darkGrey, m_pedalsGfx); } void Bicycle::CreateSpokeGfx(float radius, int spokeCount, float thicknessRatio, b2Color color, VerticeBatch& target) { XMMATRIX xf = Graphics::CircleTransform(b2Vec2_zero, spokeCount); XMVECTOR point = XMVectorSet(radius, 0.0f, 0.0f, 0.0f); b2Vec2 point2d; for (int i = 0; i < spokeCount; ++i) { point2d.Set(XMVectorGetX(point), XMVectorGetY(point)); Graphics::CreateSolidLine(b2Vec2_zero, point2d, thicknessRatio, Graphics::grey, target); point = XMVector2Transform(point, xf); } } void Bicycle::EmitDirt() { const unsigned int interval = 10; static unsigned int count = 0; b2Vec2 point; b2Vec2 normal; if (RearWheelGround()) { Physics::TouchingGround(m_rearWheel, point, normal); float angular = -m_rearWheel->GetAngularVelocity() * m_wheelRadius; b2Vec2 linear = m_rearWheel->GetLinearVelocity(); float diff = abs(angular - linear.Length()); bool lockedBreaks = angular < 1.0f && linear.Length() > 5.0f; bool spinningOnSpot = angular > 5.0f && linear.Length() < 2.0f; ++count; if (lockedBreaks || spinningOnSpot) { m_dirt.Emit(1, point - 0.2f * normal, -0.0001f * diff * normal); if (count % interval == 0) { m_audio->Play(GameAudio::eGravel, 0.7f); count = 0; } #if 0 char buf[64]; sprintf_s(buf, "dirt %d\n", (int)diff); OutputDebugStringA(buf); #endif } } } void Bicycle::PlayPedalSound() { float newAngle = m_pedals->GetAngle(); float a1 = DirectX::XMScalarModAngle(m_pedalAngle); float a2 = DirectX::XMScalarModAngle(newAngle); if (a1 > 0.0f && a2 < 0.0f) { m_audio->Play(GameAudio::ePedalUp, 0.7f); } if (a1 < 0.0f && a2 > 0.0f) { m_audio->Play(GameAudio::ePedalDown, 0.7f); } m_pedalAngle = newAngle; } void Bicycle::PlayWheelSound() { float v1 = (m_rearJoint && m_rearWheelContacts) ? abs(m_rearWheel->GetAngularVelocity()) : 0.0f; float v2 = (m_frontJoint && m_frontWheelContacts) ? abs(m_rearWheel->GetAngularVelocity()) : 0.0f; float v = max(v1, v2); float vol = 0.01f * v; m_audio->SetVolume(GameAudio::eRolling, vol); } void Bicycle::PlayBrakeSound() { int ipos = static_cast<int>(GetPosition().x); float vel = GetSpeed().Length(); float vol = min(1.0f, vel / 40.0f); m_audio->Play((vol >= 1.0) ? GameAudio::eBrakeLong : GameAudio::eBrakeShort, vol); } void Bicycle::CheckJointForces(float dt) { if (dt == 0.0f) { return; } const float maxForceSq = 1000000; if (m_rearJoint != nullptr) { b2Vec2 reactionForce = m_rearJoint->GetReactionForce(1.0f / dt); float forceModuleSq = reactionForce.LengthSquared(); if (forceModuleSq > maxForceSq) { m_frame->GetWorld()->DestroyJoint(m_rearJoint); m_rearJoint = nullptr; } } if (m_frontJoint != nullptr) { b2Vec2 reactionForce = m_frontJoint->GetReactionForce(1.0f / dt); float forceModuleSq = reactionForce.LengthSquared(); if (forceModuleSq > maxForceSq) { m_frame->GetWorld()->DestroyJoint(m_frontJoint); m_frontJoint = nullptr; } } } void Bicycle::CreateWheelJoints() { b2Vec2 axis = m_fWheelCenter - m_vertices[e_handle]; if (m_frontJoint == nullptr) { m_frontJoint = Physics::CreateWheelJoint(m_frame, m_frontWheel, m_frontWheel->GetPosition(), axis); } axis = m_rWheelCenter - m_vertices[e_saddle]; if (m_rearJoint == nullptr) { m_rearJoint = Physics::CreateWheelJoint(m_frame, m_rearWheel, m_rearWheel->GetPosition(), axis); } } void Bicycle::ApplyDamping(float damping) { m_frame->SetLinearDamping(damping); m_frontWheel->SetLinearDamping(damping); m_rearWheel->SetLinearDamping(damping); m_pedals->SetLinearDamping(damping); }
31.017291
118
0.720524
MKoi
0d98ab6daf849b0743bdc26a428e0712ecb22227
2,111
cpp
C++
src/implementation/backends/DirectX11/DirectX11_Renderer.cpp
LarsHagemann/OrbitEngine
33e01efaac617c53a701f01729581932fc81e8bf
[ "MIT" ]
null
null
null
src/implementation/backends/DirectX11/DirectX11_Renderer.cpp
LarsHagemann/OrbitEngine
33e01efaac617c53a701f01729581932fc81e8bf
[ "MIT" ]
2
2022-01-18T21:31:01.000Z
2022-01-20T21:02:09.000Z
src/implementation/backends/DirectX11/DirectX11_Renderer.cpp
LarsHagemann/OrbitEngine
33e01efaac617c53a701f01729581932fc81e8bf
[ "MIT" ]
null
null
null
#ifdef ORBIT_DIRECTX_11 #include "implementation/backends/DirectX11/DirectX11_Renderer.hpp" #include "implementation/engine/Engine.hpp" #include "implementation/backends/impl/PipelineStateImpl.hpp" #include "interfaces/rendering/Material.hpp" namespace orbit { void DirectX11Renderer::Draw(const Submesh& submesh, uint32_t instanceCount) const { if (submesh.pipelineStateId != m_currentPipelineState) { m_currentPipelineState = submesh.pipelineStateId; ENGINE->RMLoadResource<PipelineState>(submesh.pipelineStateId)->Bind(); } if (submesh.materialId != m_currentMaterial && submesh.materialId != 0) { m_currentMaterial = submesh.materialId; ENGINE->RMLoadResource<MaterialBase>(submesh.materialId)->Bind(1); } if (submesh.indexCount > 0) ENGINE->Context()->DrawIndexedInstanced(submesh.indexCount, instanceCount, submesh.startIndex, submesh.startVertex, 0); else ENGINE->Context()->DrawInstanced(submesh.vertexCount, instanceCount, submesh.startVertex, 0); } void DirectX11Renderer::BindTextureImpl(ResourceId id, uint32_t slot) const { ENGINE->RMLoadResource<Texture>(id)->Bind(slot); } void DirectX11Renderer::BindMaterialImpl(ResourceId id) const { ENGINE->RMLoadResource<MaterialBase>(id)->Bind(1); } void DirectX11Renderer::BindVertexShaderImpl(ResourceId id) const { ENGINE->RMLoadResource<VertexShader>(id)->Bind(); } void DirectX11Renderer::BindPixelShaderImpl(ResourceId id) const { ENGINE->RMLoadResource<PixelShader>(id)->Bind(); } void DirectX11Renderer::BindGeometryShaderImpl(ResourceId id) const { ENGINE->RMLoadResource<GeometryShader>(id)->Bind(); } void DirectX11Renderer::BindDomainShaderImpl(ResourceId id) const { ENGINE->RMLoadResource<DomainShader>(id)->Bind(); } void DirectX11Renderer::BindHullShaderImpl(ResourceId id) const { ENGINE->RMLoadResource<HullShader>(id)->Bind(); } } #endif
31.984848
131
0.690668
LarsHagemann
0d99559cc43104cf0ac5c62438a402e35ae4156f
278
hpp
C++
include/toy/parser/Export.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
4
2017-07-06T22:18:41.000Z
2021-05-24T21:28:37.000Z
include/toy/parser/Export.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
null
null
null
include/toy/parser/Export.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
1
2020-08-02T13:00:38.000Z
2020-08-02T13:00:38.000Z
#pragma once #include "toy/CompilerConfig.hpp" #if defined(TOY_WINDOWS) && TOY_OPTION_DYNAMIC_LIBRARY #ifdef TOY_EXPORT_PARSER #define TOY_API_PARSER __declspec(dllexport) #else #define TOY_API_PARSER __declspec(dllimport) #endif #else #define TOY_API_PARSER #endif
17.375
54
0.794964
ToyAuthor
0d9d85336096deb9daab6754a5cbf138af6dbb34
180
cpp
C++
bin/test-libsept/main.cpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
bin/test-libsept/main.cpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
bin/test-libsept/main.cpp
vdods/sept
08ee1faf1af4feb0dc440a3002eb8cc52681f946
[ "Apache-2.0" ]
null
null
null
// 2020.03.13 - Victor Dods #include <lvd/test.hpp> int main (int argc, char **argv) { return lvd::test::basic_test_main("septtest -- unit tests for libsept", argc, argv); }
22.5
88
0.666667
vdods
d3ffe19f4e5d73c8e68d7f80abde58c3135ea1df
4,875
cpp
C++
TopCoderSRM/SRM603/GraphWalkWithProbabilities.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
TopCoderSRM/SRM603/GraphWalkWithProbabilities.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
TopCoderSRM/SRM603/GraphWalkWithProbabilities.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
// BEGIN CUT HERE // END CUT HERE #line 5 "GraphWalkWithProbabilities.cpp" #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> using namespace std; typedef std::pair <int,int> scPair2i; typedef std::vector <int> scVeci; typedef std::vector <scPair2i> scVec2i; typedef std::stack <int> scStacki; typedef std::queue <int> scQueuei; typedef std::set <int> scSeti; typedef std::map<int,int> scMapii; typedef std::map<int,int>::iterator scMapiiIter; typedef std::map<int,int>::reverse_iterator scMapiiRevIter; #define tr(container,it) \ for (it=container.begin();it!=container.end();it++) #define trRev(container,it) \ for (it=container.rbegin();it!=container.rend();it++) #define scFor0(x,num) \ for (int x=0;x<num;x++) #define scFor1(x,start,num) \ for (int x=start;x<num;x++) int m,n; class GraphWalkWithProbabilities { public: double c[2][51]; double findprob(vector <string> graph, vector <int> winprob, vector <int> looseprob, int Start) { //$CARETPOSITION$ n=winprob.size(); scFor0(i,n){ c[0][i]=c[1][i]=0.0; } scVeci conProb; conProb.resize(n); scFor0(i,n){ conProb[i]=100-winprob[i]-looseprob[i]; } scFor0(t,10000){ scFor0(i,n){ c[1][i]=0.0; scFor0(j,n){ if (graph[i][j]=='1'){ double q=winprob[j]/100.0 + conProb[j]*c[0][j]/100.0; c[1][i]=max(c[1][i],q); } } } memcpy(c[0],c[1],sizeof(c[1])); } return c[0][Start]; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.5; verify_case(0, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); } void test_case_1() { string Arr0[] = {"11","11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {60,40}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {40,60}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.6; verify_case(1, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); } void test_case_2() { string Arr0[] = {"11","11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {3,4}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.4285714285714286; verify_case(2, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); } void test_case_3() { string Arr0[] = {"110","011","001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2,1,10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {20,20,10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; double Arg4 = 0.405; verify_case(3, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); } void test_case_4() { string Arr0[] = {"111","111","011"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100,1,1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {0,50,50}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; double Arg4 = 0.5; verify_case(4, Arg4, findprob(Arg0, Arg1, Arg2, Arg3)); } // END CUT HERE }; // BEGIN CUT HERE int main() { GraphWalkWithProbabilities ___test; ___test.run_test(-1); system("pause"); } // END CUT HERE
47.794118
400
0.59959
zombiecry
31050df677ea032ac1c4b7779ecc6c6aa402a152
1,290
cpp
C++
src/row.cpp
dashboardvision/aspose-php
e2931773cbb1f47ae4086d632faa3012bd952b99
[ "MIT" ]
null
null
null
src/row.cpp
dashboardvision/aspose-php
e2931773cbb1f47ae4086d632faa3012bd952b99
[ "MIT" ]
null
null
null
src/row.cpp
dashboardvision/aspose-php
e2931773cbb1f47ae4086d632faa3012bd952b99
[ "MIT" ]
1
2021-06-23T08:02:03.000Z
2021-06-23T08:02:03.000Z
#include "../include/aspose.h" #include "../include/collection.h" #include "../include/cell.h" #include "../include/row.h" #include <phpcpp.h> using namespace Aspose::Slides; using namespace System; using namespace std; using namespace Aspose::Slides; namespace AsposePhp { /** * @brief Desc. * * @throw System::ArgumentOutOfRangeException Index is invalid or does not exist * @return Php::Value */ Php::Value Row::idx_get(Php::Parameters &params) { int index = params[0].numericValue(); try { return Php::Object("AsposePhp\\Slides\\Cell", wrapObject<ICell, AsposePhp::Cell, &IRow::idx_get>(index)); } catch(System::ArgumentOutOfRangeException &e) { throw Php::Exception("Invalid index: " + to_string(index)); } } /** * @brief Returns the number of items in collection * * @return Php::Value */ Php::Value Row::get_Count() { return _asposeObj->get_Count(); } /** * @brief Sets the minimal possible height of a row. Write double * * @param params */ void Row::set_MinimalHeight(Php::Parameters &params) { double value = params[0].numericValue(); _asposeObj->set_MinimalHeight(value); } }
25.294118
117
0.608527
dashboardvision
3106157915875c6c69874101773a2a9c37d7ada2
3,713
cpp
C++
Examples/source/ManageAndOptimizeBarcodeRecognition/ReadMultipleMacroPdf417Barcodes.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
3
2018-12-07T18:39:59.000Z
2021-06-08T13:08:29.000Z
Examples/source/ManageAndOptimizeBarcodeRecognition/ReadMultipleMacroPdf417Barcodes.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
null
null
null
Examples/source/ManageAndOptimizeBarcodeRecognition/ReadMultipleMacroPdf417Barcodes.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
1
2018-07-13T14:22:11.000Z
2018-07-13T14:22:11.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using http://www.aspose.com/community/forums/default.aspx */ #include "ReadMultipleMacroPdf417Barcodes.h" #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <system/exceptions.h> #include <system/details/dispose_guard.h> #include <system/console.h> #include <system/array.h> #include <cstdint> #include <BarCodeRecognition/Recognition/RecognitionSession/DecodeTypes/SingleDecodeType.h> #include <BarCodeRecognition/Recognition/RecognitionSession/DecodeTypes/DecodeType.h> #include <BarCodeRecognition/Recognition/RecognitionSession/BarCodeReader.h> #include "RunExamples.h" using namespace Aspose::BarCode::BarCodeRecognition; namespace Aspose { namespace BarCode { namespace Examples { namespace CSharp { namespace ManageAndOptimizeBarCodeRecognition { RTTI_INFO_IMPL_HASH(631373512u, ::Aspose::BarCode::Examples::CSharp::ManageAndOptimizeBarCodeRecognition::ReadMultipleMacroPdf417Barcodes, ThisTypeBaseTypesInfo); void ReadMultipleMacroPdf417Barcodes::Run() { //ExStart:ReadMultipleMacroPdf417Barcodes try { // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir_ManageAndOptimizeBarcodeRecognition(); // Create array for storing multiple bar codes file names System::ArrayPtr<System::String> files = System::MakeArray<System::String>({ u"Barcodefrom.png", u"Barcode2.png" }); // Iiterate through the bar code image files for (int32_t i = 0; i < files->get_Length(); ++i) { // Create instance of BarCodeReader class and set symbology { System::SharedPtr<BarCodeReader> reader = System::MakeObject<BarCodeReader>(dataDir + files[i], DecodeType::MacroPdf417); // Clearing resources under 'using' statement System::Details::DisposeGuard<1> __dispose_guard_0({ reader }); // ------------------------------------------ try { if (reader->Read()) { // Get code text, file id, segment id and segment count System::Console::WriteLine(System::String(u"File Name: ") + files[i] + u" Code Text: " + reader->GetCodeText()); System::Console::WriteLine(System::String(u"FileID: ") + reader->GetMacroPdf417FileID()); System::Console::WriteLine(System::String(u"SegmentID: ") + reader->GetMacroPdf417SegmentID()); System::Console::WriteLine(System::String(u"Segment Count: ") + reader->GetMacroPdf417SegmentsCount()); } System::Console::WriteLine(); } catch (...) { __dispose_guard_0.SetCurrentException(std::current_exception()); } } } } catch (System::Exception& ex) { System::Console::WriteLine(ex->get_Message() + u"\nThis example will only work if you apply a valid Aspose BarCode License. You can purchase full license or get 30 day temporary license from http://wwww.aspose.com/purchase/default.aspx."); } //ExEnd:ReadMultipleMacroPdf417Barcodes } } // namespace ManageAndOptimizeBarCodeRecognition } // namespace CSharp } // namespace Examples } // namespace BarCode } // namespace Aspose
40.802198
246
0.692971
aspose-barcode
3108881f8519f2858e35516b7ccca51b0fc10e12
2,551
cpp
C++
SupportCode/src/Utils/GDraw.cpp
nitinkaveriappa/TIcTacToe
0f2dade44af25e9ebff66df9999e3f8b985de9dd
[ "MIT" ]
null
null
null
SupportCode/src/Utils/GDraw.cpp
nitinkaveriappa/TIcTacToe
0f2dade44af25e9ebff66df9999e3f8b985de9dd
[ "MIT" ]
null
null
null
SupportCode/src/Utils/GDraw.cpp
nitinkaveriappa/TIcTacToe
0f2dade44af25e9ebff66df9999e3f8b985de9dd
[ "MIT" ]
null
null
null
#include "Utils/GDraw.hpp" #include <cmath> struct GDrawData { GDrawData(void) { m_params[GDRAW_MINX] = -30; m_params[GDRAW_MINY] = -20; m_params[GDRAW_MAXX] = 30; m_params[GDRAW_MAXY] = 20; m_params[GDRAW_ORTHO_NEAR_PLANE] = -10; m_params[GDRAW_ORTHO_FAR_PLANE] = 10; } double m_params[GDRAW_NR_PARAMS]; }; //general GDrawData* GDrawGetData(void) { static GDrawData ddata; return &ddata; } double GDrawGetParam(const GDrawParam p) { return GDrawGetData()->m_params[p]; } void GDrawSetParam(const GDrawParam p, const double val) { GDrawGetData()->m_params[p] = val; } void GDrawWireframe(const bool val) { if(val) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } void GDrawColor(const double r, const double g, const double b) { glColor3d(r, g, b); } void GDrawLineWidth(const double w) { glLineWidth(w); } void GDrawString2D(const char s[], const double x, const double y) { if(s) { glRasterPos2d(x, y); for(int i = 0; s[i] != '\0'; ++i) glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, s[i]); } } void GDrawSegment2D(const double x1, const double y1, const double x2, const double y2) { glBegin(GL_LINES); glVertex3d(x1, y1, 0); glVertex3d(x2, y2, 0); glEnd(); } void GDrawSegment2D(const double p1[], const double p2[]) { GDrawSegment2D(p1[0], p1[1], p2[0], p2[1]); } void GDrawSegment2D(const double p1p2[]) { GDrawSegment2D(p1p2[0], p1p2[1], p1p2[2], p1p2[3]); } void GDrawAABox2D(const double minx, const double miny, const double maxx, const double maxy) { glNormal3d(0, 0, 1); glBegin(GL_QUADS); glVertex2d(minx, miny); glVertex2d(maxx, miny); glVertex2d(maxx, maxy); glVertex2d(minx, maxy); glEnd(); } void GDrawAABox2D(const double min[], const double max[]) { GDrawAABox2D(min[0], min[1], max[0], max[1]); } void GDrawAABox2D(const double minmax[]) { GDrawAABox2D(minmax[0], minmax[1], minmax[2], minmax[3]); } void GDrawGrid2D(const double xmin, const double ymin, const double xmax, const double ymax, const int xNrDims, const int yNrDims) { const double xunit = (xmax - xmin) / xNrDims; const double yunit = (ymax - ymin) / yNrDims; for(int i = 0; i <= xNrDims; ++i) GDrawSegment2D(xmin + i * xunit, ymin, xmin + i * xunit, ymax); for(int i = 0; i <= yNrDims; ++i) GDrawSegment2D(xmin, ymin + i * yunit, xmax, ymin + i * yunit); }
18.620438
66
0.643277
nitinkaveriappa
310a0721b4f1babad3b580d662ee60138e02bbe8
4,085
cc
C++
sample/src/Program.cc
pengrui2009/aliyun-oss-cpp-sdk-windows
db3b42fb949d38c577876bcc8d65cd67e31d6dcd
[ "Apache-2.0" ]
null
null
null
sample/src/Program.cc
pengrui2009/aliyun-oss-cpp-sdk-windows
db3b42fb949d38c577876bcc8d65cd67e31d6dcd
[ "Apache-2.0" ]
null
null
null
sample/src/Program.cc
pengrui2009/aliyun-oss-cpp-sdk-windows
db3b42fb949d38c577876bcc8d65cd67e31d6dcd
[ "Apache-2.0" ]
null
null
null
#include <alibabacloud/oss/OssClient.h> #include <iostream> #include "Config.h" #if !defined(OSS_DISABLE_BUCKET) #include "service/ServiceSample.h" #include "bucket/BucketSample.h" #endif #include "object/ObjectSample.h" #include "presignedurl/PresignedUrlSample.h" #if !defined(OSS_DISABLE_LIVECHANNEL) #include "LiveChannel/LiveChannelSample.h" #endif #if !defined(OSS_DISABLE_ENCRYPTION) #include "encryption/EncryptionSample.h" #endif using namespace AlibabaCloud::OSS; void LogCallbackFunc(LogLevel level, const std::string &stream) { if (level == LogLevel::LogOff) return; std::cout << stream; } int main(void) { std::cout << "oss-cpp-sdk samples" << std::endl; std::string bucketName = "<YourBucketName>"; InitializeSdk(); SetLogLevel(LogLevel::LogDebug); SetLogCallback(LogCallbackFunc); #if !defined(OSS_DISABLE_BUCKET) ServiceSample serviceSample; serviceSample.ListBuckets(); serviceSample.ListBucketsWithMarker(); serviceSample.ListBucketsWithPrefix(); BucketSample bucketSample(bucketName); bucketSample.InvalidBucketName(); bucketSample.CreateAndDeleteBucket(); bucketSample.SetBucketAcl(); bucketSample.SetBucketLogging(); bucketSample.SetBucketWebsite(); bucketSample.SetBucketReferer(); bucketSample.SetBucketLifecycle(); bucketSample.SetBucketCors(); bucketSample.GetBucketCors(); bucketSample.DeleteBucketLogging(); bucketSample.DeleteBucketWebsite(); bucketSample.DeleteBucketLifecycle(); bucketSample.DeleteBucketCors(); bucketSample.GetBucketAcl(); bucketSample.GetBucketLocation(); bucketSample.GetBucketLogging(); bucketSample.GetBucketWebsite(); bucketSample.GetBucketReferer(); bucketSample.GetBucketStat(); bucketSample.GetBucketLifecycle(); //bucketSample.DeleteBucketsByPrefix(); #endif ObjectSample objectSample(bucketName); objectSample.PutObjectFromBuffer(); objectSample.PutObjectFromFile(); objectSample.GetObjectToBuffer(); objectSample.GetObjectToFile(); objectSample.DeleteObject(); objectSample.DeleteObjects(); objectSample.HeadObject(); objectSample.GetObjectMeta(); objectSample.AppendObject(); objectSample.PutObjectProgress(); objectSample.GetObjectProgress(); objectSample.PutObjectCallable(); objectSample.GetObjectCallable(); objectSample.CopyObject(); //objectSample.RestoreArchiveObject("your-archive", "oss_archive_object.PNG", 1); objectSample.ListObjects(); objectSample.ListObjectWithMarker(); objectSample.ListObjectWithEncodeType(); #if !defined(OSS_DISABLE_RESUAMABLE) objectSample.UploadObjectProgress(); objectSample.MultiCopyObjectProcess(); objectSample.DownloadObjectProcess(); #endif PresignedUrlSample signedUrlSample(bucketName); signedUrlSample.GenGetPresignedUrl(); signedUrlSample.PutObjectByUrlFromBuffer(); signedUrlSample.PutObjectByUrlFromFile(); signedUrlSample.GetObjectByUrlToBuffer(); signedUrlSample.GetObjectByUrlToFile(); #if !defined(OSS_DISABLE_LIVECHANNEL) // LiveChannel LiveChannelSample liveChannelSample(bucketName, "test_channel"); liveChannelSample.PutLiveChannel(); liveChannelSample.GetLiveChannelInfo(); liveChannelSample.GetLiveChannelStat(); liveChannelSample.ListLiveChannel(); liveChannelSample.GetLiveChannelHistory(); liveChannelSample.PostVodPlayList(); liveChannelSample.GetVodPlayList(); liveChannelSample.PutLiveChannelStatus(); liveChannelSample.DeleteLiveChannel(); #endif #if !defined(OSS_DISABLE_ENCRYPTION) // Encryption EncryptionSample encryptionSample(bucketName); encryptionSample.PutObjectFromBuffer(); encryptionSample.PutObjectFromFile(); encryptionSample.GetObjectToBuffer(); encryptionSample.GetObjectToFile(); #if !defined(DISABLE_RESUAMABLE) encryptionSample.UploadObjectProgress(); encryptionSample.DownloadObjectProcess(); encryptionSample.MultipartUploadObject(); #endif #endif ShutdownSdk(); return 0; }
29.388489
85
0.761812
pengrui2009
310d40b2fa9336c32c12b3962ecc8dc38036cdaa
595
cpp
C++
src/Bubblewrap/Render/BgfxFont.cpp
bubblewrap-engine/bubblewrap_bfxr
dd41c8f2f43ce79c25ede39c3376292e83257d21
[ "MIT" ]
null
null
null
src/Bubblewrap/Render/BgfxFont.cpp
bubblewrap-engine/bubblewrap_bfxr
dd41c8f2f43ce79c25ede39c3376292e83257d21
[ "MIT" ]
null
null
null
src/Bubblewrap/Render/BgfxFont.cpp
bubblewrap-engine/bubblewrap_bfxr
dd41c8f2f43ce79c25ede39c3376292e83257d21
[ "MIT" ]
null
null
null
#include "Bubblewrap/Render/BgfxFont.hpp" #include "Bubblewrap/Base/Entity.hpp" #include "Bubblewrap/Base/Base.hpp" #include "Bubblewrap/Base/BgfxPhysFsInputStream.hpp" namespace Bubblewrap { namespace Render { BgfxFont::BgfxFont() { } void BgfxFont::Initialise( Json::Value Params ) { Font::Initialise( Params ); Stream_.open( Params[ "fontFile" ].asString().c_str() ); // TODO } void BgfxFont::Copy( BgfxFont* Target, BgfxFont* Base ) { Font::Copy( Target, Base ); } void BgfxFont::OnAttach() { } void BgfxFont::Update( float dt ) { } } }
15.25641
59
0.657143
bubblewrap-engine
310e6d46935b569640730afeb553dbc4f447fcd2
5,316
hxx
C++
Modules/Search/binary_log.hxx
Hurna/Hurna-Lib
61c267fc6ccf617e92560a84800f6a719cc5c6c8
[ "MIT" ]
2
2019-03-29T21:23:02.000Z
2019-04-02T19:13:32.000Z
Modules/Search/binary_log.hxx
Hurna/Hurna-Lib
61c267fc6ccf617e92560a84800f6a719cc5c6c8
[ "MIT" ]
null
null
null
Modules/Search/binary_log.hxx
Hurna/Hurna-Lib
61c267fc6ccf617e92560a84800f6a719cc5c6c8
[ "MIT" ]
null
null
null
/*=========================================================================================================== * * HUL - Hurna Lib * * Copyright (c) Michael Jeulin-Lagarrigue * * Licensed under the MIT License, you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/Hurna/Hurna-Lib/blob/master/LICENSE * * 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. * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * *=========================================================================================================*/ #ifndef MODULE_SEARCH_BINARY_LOG_HXX #define MODULE_SEARCH_BINARY_LOG_HXX #include <Logger/algorithm.hxx> #include <Logger/vector.hxx> namespace hul { namespace search { /// @class Binary /// template <typename IT, typename Equal = std::equal_to<typename std::iterator_traits<IT>::value_type>> class Binary { typedef typename std::iterator_traits<IT>::value_type T; public: static const String GetName() { return "Binary Search"; } static const String GetVersion() { return "1.0.0"; } static const String GetType() { return "algorithm"; } /// static Ostream& Build(Ostream& os, const IT& begin, const IT& end, const T& key) { auto builder = std::unique_ptr<Binary>(new Binary(os)); builder->Write(begin, end, key); return os; } /// static IT Build(Logger& logger, const IT& begin, const IT& end, const T& key) { return Write(logger, begin, end, key); } private: Binary(Ostream& os) : logger(std::unique_ptr<Logger>(new Logger(os))) {} Binary operator=(Binary&) {} // Not Implemented IT Write(const IT& begin, const IT& end, const T& key) { return Write(*this->logger, begin, end, key); } /// static IT Write(Logger& logger, const IT& begin, const IT& end, const T& key) { logger.Start(); // Start Logging Procedure Algo_Traits<Binary>::Build(logger); // Write description WriteParameters(logger, begin, end, key); // Write parameters auto it = WriteComputation(logger, begin, end, key); // Write computation logger.End(); // Close Logging Procedure return it; } /// static void WriteParameters(Logger& logger, const IT& begin, const IT& end, const T& key) { logger.StartArray("parameters"); if (logger.GetCurrentLevel() > 0) // Only iterators { logger.AddObject(begin, true); logger.AddObject(end, true); logger.AddValue("key", key); } else // All data { logger.AddDataDetails(begin, end, true); logger.AddValue("key", key); } logger.EndArray(); } /// static IT WriteComputation(Logger& logger, const IT& begin, const IT& end, const T& key) { const auto size = static_cast<const int>(std::distance(begin, end)); if (size < 2) { if (logger.GetCurrentLevel() == 0) { logger.Comment("Sequence too small to be procesed: already sorted."); logger.Return("void"); } return end; } // Locals logger.StartArray("locals"); bool found = false; auto lowIt = begin; auto highIt = end; auto curIt = IT(end, "current", true); logger.EndArray(); // Computation logger.StartArray("logs"); logger.StartLoop(); while (lowIt < highIt) { curIt = lowIt + (highIt.GetIndex() - lowIt.GetIndex()) / 2; logger.Comment("Select middle element: " + curIt.String()); if (Equal()(key, *curIt)) { found = true; logger.Comment("Key {" + ToString(key) + "} Found at index [" + ToString(curIt.GetIndex()) + "]"); break; } else if (key > *curIt) { lowIt = curIt + 1; logger.Comment("Key{" + ToString(key) + "} > " + curIt.String() + ": search in upper sequence."); } else { highIt = curIt; logger.Comment("Key{" + ToString(key) + "} < " + curIt.String() + ": search in lower sequence."); } // Notify new search space logger.SetRange(std::make_pair(lowIt.GetIndex(), highIt.GetIndex())); } logger.EndLoop(); if (!found) logger.Comment("Key {" + ToString(key) + "} was not found."); logger.Return((found) ? curIt.String() : end.String()); logger.EndArray(); // Statistics if (logger.GetCurrentLevel() == 0) { logger.StartArray("stats"); logger.AddStats(curIt, true); logger.EndArray(); } return (found) ? curIt : end; } // Unique as created only at execution as a RAII ressource std::unique_ptr<Logger> logger; // Logger used to fill the stream }; } } #endif // MODULE_SEARCH_BINARY_LOG_HXX
31.832335
109
0.571482
Hurna
31125abc4fb8d5845287c0c3750e9053c61bd4b7
4,869
cpp
C++
Lib-ZeroG/src/ZeroG/metal/MetalCommandList.cpp
PetorSFZ/ZeroG
0e3330c2877c3dd840f2a7864b5767d53a92b97d
[ "Zlib" ]
null
null
null
Lib-ZeroG/src/ZeroG/metal/MetalCommandList.cpp
PetorSFZ/ZeroG
0e3330c2877c3dd840f2a7864b5767d53a92b97d
[ "Zlib" ]
null
null
null
Lib-ZeroG/src/ZeroG/metal/MetalCommandList.cpp
PetorSFZ/ZeroG
0e3330c2877c3dd840f2a7864b5767d53a92b97d
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #include "ZeroG/metal/MetalCommandList.hpp" #include "ZeroG/util/Assert.hpp" namespace zg { // MetalCommandList: Virtual methods // ------------------------------------------------------------------------------------------------ ZgResult MetalCommandList::memcpyBufferToBuffer( ZgBuffer* dstBuffer, uint64_t dstBufferOffsetBytes, ZgBuffer* srcBuffer, uint64_t srcBufferOffsetBytes, uint64_t numBytes) noexcept { (void)dstBuffer; (void)dstBufferOffsetBytes; (void)srcBuffer; (void)srcBufferOffsetBytes; (void)numBytes; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::memcpyToTexture( ZgTexture2D* dstTexture, uint32_t dstTextureMipLevel, const ZgImageViewConstCpu& srcImageCpu, ZgBuffer* tempUploadBuffer) noexcept { (void)dstTexture; (void)dstTextureMipLevel; (void)srcImageCpu; (void)tempUploadBuffer; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::enableQueueTransitionBuffer(ZgBuffer* buffer) noexcept { (void)buffer; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::enableQueueTransitionTexture(ZgTexture2D* texture) noexcept { (void)texture; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setPushConstant( uint32_t shaderRegister, const void* data, uint32_t dataSizeInBytes) noexcept { (void)shaderRegister; (void)data; (void)dataSizeInBytes; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setPipelineBindings( const ZgPipelineBindings& bindings) noexcept { (void)bindings; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setPipelineRender( ZgPipelineRender* pipeline) noexcept { (void)pipeline; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setFramebuffer( ZgFramebuffer* framebuffer, const ZgFramebufferRect* optionalViewport, const ZgFramebufferRect* optionalScissor) noexcept { (void)optionalViewport; (void)optionalScissor; mFramebuffer = static_cast<MetalFramebuffer*>(framebuffer); return ZG_SUCCESS; } ZgResult MetalCommandList::setFramebufferViewport( const ZgFramebufferRect& viewport) noexcept { (void)viewport; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setFramebufferScissor( const ZgFramebufferRect& scissor) noexcept { (void)scissor; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::clearFramebufferOptimal() noexcept { return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::clearRenderTargets( float red, float green, float blue, float alpha) noexcept { ZG_ASSERT(mFramebuffer != nullptr); mtlpp::ClearColor clearColor = mtlpp::ClearColor(red, green, blue, alpha); mtlpp::RenderPassDescriptor pass; pass.GetColorAttachments()[0].SetClearColor(clearColor); pass.GetColorAttachments()[0].SetLoadAction(mtlpp::LoadAction::Clear); pass.GetColorAttachments()[0].SetStoreAction(mtlpp::StoreAction::Store); pass.GetColorAttachments()[0].SetTexture(mFramebuffer->texture); #warning "This is a huge hack" mtlpp::RenderCommandEncoder encoder = cmdBuffer.RenderCommandEncoder(pass); encoder.EndEncoding(); return ZG_SUCCESS; } ZgResult MetalCommandList::clearDepthBuffer( float depth) noexcept { (void)depth; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setIndexBuffer( ZgBuffer* indexBuffer, ZgIndexBufferType type) noexcept { (void)indexBuffer; (void)type; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::setVertexBuffer( uint32_t vertexBufferSlot, ZgBuffer* vertexBuffer) noexcept { (void)vertexBufferSlot; (void)vertexBuffer; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::drawTriangles( uint32_t startVertexIndex, uint32_t numVertices) noexcept { (void)startVertexIndex; (void)numVertices; return ZG_WARNING_UNIMPLEMENTED; } ZgResult MetalCommandList::drawTrianglesIndexed( uint32_t startIndex, uint32_t numTriangles) noexcept { (void)startIndex; (void)numTriangles; return ZG_WARNING_UNIMPLEMENTED; } } // namespace zg
25.761905
99
0.783528
PetorSFZ
3112732b8811a4eeae7b5b91902208b0d3af7c6f
1,933
cpp
C++
listas_PO/lista_1_1/src/Data.cpp
Tassany/Pesquisa_Operacional
93890fef63dfd48a0e7867bf681ec01e05560fdc
[ "MIT" ]
null
null
null
listas_PO/lista_1_1/src/Data.cpp
Tassany/Pesquisa_Operacional
93890fef63dfd48a0e7867bf681ec01e05560fdc
[ "MIT" ]
null
null
null
listas_PO/lista_1_1/src/Data.cpp
Tassany/Pesquisa_Operacional
93890fef63dfd48a0e7867bf681ec01e05560fdc
[ "MIT" ]
null
null
null
#include "../include/Data.hpp" #include <stdlib.h> #include <stdio.h> #include <iostream> Data::Data(char* filePath) { FILE* f = fopen(filePath,"r"); if(fscanf(f, "%d", &numCulturas) != 1) { printf("Problem while reading instance.1\n"); //exit(1); } //lendo limite do armazem if(fscanf(f, "%lf", &limiteArm) != 1) { printf("Problem while reading instance.2\n"); // exit(1); } //lendo area cultivavel if(fscanf(f, "%lf", &areaCultivavel) != 1) { printf("Problem while reading instance.3\n"); // exit(1); } //lendo produtividade por cultura prodCultura = std::vector<double>(numCulturas); for(int i = 0; i <numCulturas; i++){ if(fscanf(f, "%lf", &prodCultura[i]) != 1) { printf("Problem while reading instance.4\n"); //exit(1); } } //lendo lucro por cultura lucroCultura = std::vector<double>(numCulturas); for(int i = 0; i < numCulturas; i++) { if(fscanf(f, "%lf", &lucroCultura[i]) != 1) { printf("Problem while reading instance.5\n"); // exit(1); } } //lendo semanda por cultura demandaCultura = std::vector<double>(numCulturas); for(int i = 0; i < numCulturas; i++) { if(fscanf(f, "%lf", &demandaCultura[i]) != 1) { printf("Problem while reading instance.6\n"); //exit(1); } } fclose(f); } int Data::getNumCulturas() { return numCulturas; } double Data::getLimiteArm() { return limiteArm; } double Data::getAreaCultivavel() { return areaCultivavel; } double Data::getProdCultura(int cultura) { return prodCultura[cultura]; } double Data::getLucroCultura(int cultura) { return lucroCultura[cultura]; } double Data::getDemandaCultura(int cultura) { return demandaCultura[cultura]; }
19.72449
57
0.561304
Tassany
3113c3e5f164969cbf8a0db598b70c326f61d0e8
946
cpp
C++
src/homework/tic_tac_toe/main.cpp
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
0c544a3fa189dec5da827efe70fccb9f395cbe7d
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/main.cpp
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
0c544a3fa189dec5da827efe70fccb9f395cbe7d
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/main.cpp
acc-cosc-1337-fall-2019/acc-cosc-1337-fall-2019-LeytonLL
0c544a3fa189dec5da827efe70fccb9f395cbe7d
[ "MIT" ]
null
null
null
#include "tic_tac_toe_manager.h" #include <tic_tac_toe_3.h> #include <tic_tac_toe_4.h> #include<iostream> #include<string> using std::cout; using std::cin; using std::string; int main() //tic TacToe3 { auto response = 'y'; unique_ptr<TicTacToeManager> manager = std::make_unique<TicTacToeManager>(); string player = ""; int game_type; do { cout << "Play win by 3 or 4: "; cin >> game_type; unique_ptr<TicTacToe> game; if(game_type == 3) { game = std::make_unique<TicTacToe3>(); } else { game = std::make_unique<TicTacToe4>(); } cout << "Enter X or O"; cin >> player; game->start_game(player); while (game->game_over() == false) { cin >> *game; cout << *game; } manager->save_game(game); cout << "Game over: \n"; cout << "Continue y or n "; cin >> response; } while (response == 'y' || response == 'Y'); cout << "History: \n"; cout << *manager; return 0; }
14.119403
77
0.602537
acc-cosc-1337-fall-2019
31144e77e5c551f0eb8ee46b48f92b7aeeb39097
844
hpp
C++
search/intersection_result.hpp
Dushistov/omim
e366dd2f7508dea305922d7bd91deea076fc4a58
[ "Apache-2.0" ]
null
null
null
search/intersection_result.hpp
Dushistov/omim
e366dd2f7508dea305922d7bd91deea076fc4a58
[ "Apache-2.0" ]
null
null
null
search/intersection_result.hpp
Dushistov/omim
e366dd2f7508dea305922d7bd91deea076fc4a58
[ "Apache-2.0" ]
null
null
null
#pragma once #include "search/model.hpp" #include "std/cstdint.hpp" #include "std/string.hpp" namespace search { // This class holds higher-level features for an intersection result, // i.e. BUILDING and STREET for POI or STREET for BUILDING. struct IntersectionResult { static uint32_t const kInvalidId; IntersectionResult(); void Set(SearchModel::SearchType type, uint32_t id); // Returns the first valid feature among the [POI, BUILDING, // STREET]. uint32_t InnermostResult() const; // Returns true when at least one valid feature exists. inline bool IsValid() const { return InnermostResult() != kInvalidId; } // Clears all fields to an invalid state. void Clear(); uint32_t m_poi; uint32_t m_building; uint32_t m_street; }; string DebugPrint(IntersectionResult const & result); } // namespace search
22.210526
73
0.735782
Dushistov
311bf9b19e24a8ed6bd79eebcea947eabb5ad94f
4,237
cpp
C++
src/prim/hldr.cpp
311Volt/axxegro
61d7a1fb48f9bb581e0f4171d58499cf8c543728
[ "MIT" ]
null
null
null
src/prim/hldr.cpp
311Volt/axxegro
61d7a1fb48f9bb581e0f4171d58499cf8c543728
[ "MIT" ]
null
null
null
src/prim/hldr.cpp
311Volt/axxegro
61d7a1fb48f9bb581e0f4171d58499cf8c543728
[ "MIT" ]
null
null
null
#include <axxegro/prim/hldr.hpp> #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> void al::DrawLine( const al::Coord<>& a, const al::Coord<>& b, const Color& color, float thickness ) { al_draw_line(a.x, a.y, b.x, b.y, color, thickness); } void al::DrawTriangle( const al::Coord<>& a, const al::Coord<>& b, const al::Coord<>& c, const Color& color, float thickness ) { al_draw_triangle(a.x, a.y, b.x, b.y, c.x, c.y, color, thickness); } void al::DrawFilledTriangle( const al::Coord<>& a, const al::Coord<>& b, const al::Coord<>& c, const Color& color ) { al_draw_filled_triangle(a.x, a.y, b.x, b.y, c.x, c.y, color); } void al::DrawRectangle( const Rect<>& r, const Color& color, float thickness ) { al_draw_rectangle(r.a.x, r.a.y, r.b.x, r.b.y, color, thickness); } void al::DrawFilledRectangle( const Rect<>& rect, const Color& color ) { al_draw_filled_rectangle(rect.a.x, rect.a.y, rect.b.x, rect.b.y, color); } void al::DrawRoundRect( const Rect<>& rect, const Vec2<>& radius, const Color& color, float thickness ) { al_draw_rounded_rectangle( rect.a.x, rect.a.y, rect.b.x, rect.b.y, radius.x, radius.y, color, thickness ); } void al::DrawFilledRoundRect( const Rect<>& rect, const Vec2<>& radius, const Color& color ) { al_draw_filled_rounded_rectangle( rect.a.x, rect.a.y, rect.b.x, rect.b.y, radius.x, radius.y, color ); } void al::DrawPieslice( const al::Coord<>& center, float radius, float startTheta, float deltaTheta, const Color& color, float thickness ) { al_draw_pieslice( center.x, center.y, radius, startTheta, deltaTheta, color, thickness ); } void al::DrawFilledPieslice( const al::Coord<>& center, float radius, float startTheta, float deltaTheta, const Color& color ) { al_draw_filled_pieslice( center.x, center.y, radius, startTheta, deltaTheta, color ); } void al::DrawEllipse( const al::Coord<>& center, const Vec2<>& radius, const Color& color, float thickness ) { al_draw_ellipse( center.x, center.y, radius.x, radius.y, color, thickness ); } void al::DrawFilledEllipse( const al::Coord<>& center, const Vec2<>& radius, const Color& color ) { al_draw_filled_ellipse( center.x, center.y, radius.x, radius.y, color ); } void al::DrawCircle( const al::Coord<>& center, float radius, const Color& color, float thickness ) { al_draw_circle( center.x, center.y, radius, color, thickness ); } void al::DrawFilledCircle( const al::Coord<>& center, float radius, const Color& color ) { al_draw_filled_circle( center.x, center.y, radius, color ); } void al::DrawArc( const al::Coord<>& center, float radius, float startTheta, float deltaTheta, const Color& color, float thickness ) { al_draw_arc( center.x, center.y, radius, startTheta, deltaTheta, color, thickness ); } void al::DrawEllipticalArc( const al::Coord<>& center, const Vec2<>& radius, float startTheta, float deltaTheta, const Color& color, float thickness ) { al_draw_elliptical_arc( center.x, center.y, radius.x, radius.y, startTheta, deltaTheta, color, thickness ); } void al::DrawSpline( const std::array<al::Coord<>, 4>& points, const Color& color, float thickness ) { std::vector<float> pts(8); for(unsigned i=0; i<points.size(); i++) { pts[i*2 + 0] = points[i].x; pts[i*2 + 1] = points[i].y; } al_draw_spline(pts.data(), color, thickness); } std::vector<al::Coord<>> al::CalculateArc( const al::Coord<>& center, const al::Coord<>& radius, float startTheta, float deltaTheta, float thickness, unsigned numPoints ) { std::vector<float> outData(2*numPoints*(1 + !!(thickness>0))); al_calculate_arc( outData.data(), 2*sizeof(outData[0]), center.x, center.y, radius.x, radius.y, startTheta, deltaTheta, thickness, numPoints ); std::vector<Coord<>> ret(outData.size() / 2); for(unsigned i=0; i<ret.size(); i++) { ret[i] = {outData[i*2 + 0], outData[i*2 + 1]}; } return ret; }
17.654167
74
0.631579
311Volt
311e8c41219d13fb2e697ba612e1d2f2a0d29ef6
13,683
cpp
C++
CS202/asmt01/asmt01.cpp
T-R0D/Past-Courses
0edc83a7bf09515f0d01d23a26df2ff90c0f458a
[ "MIT" ]
7
2017-03-13T17:32:26.000Z
2021-09-27T16:51:22.000Z
CS202/asmt01/asmt01.cpp
T-R0D/Past-Courses
0edc83a7bf09515f0d01d23a26df2ff90c0f458a
[ "MIT" ]
1
2021-05-29T19:54:02.000Z
2021-05-29T19:54:52.000Z
CS202/asmt01/asmt01.cpp
T-R0D/Past-Courses
0edc83a7bf09515f0d01d23a26df2ff90c0f458a
[ "MIT" ]
25
2016-10-18T03:31:44.000Z
2020-12-29T13:23:10.000Z
///////////////////////////////////////////////////////////////////////////////// // // Title: asmt01: Sequence Processor // Created By: Terence Henriod // Course: CS 202 // // This program processes a range of numbers using a conditional math sequence // and outputs relevant data to .txt and .csv files. // ///////////////////////////////////////////////////////////////////////////////// /// Header Files///////////////////////////////////////////////////////////////// #include <iostream> #include <conio.h> #include <fstream> #include <assert.h> using namespace std; /// Global Constant Definitions////////////////////////////////////////////////// // string lengths const int NAME_LEN = 20; // max sequence length const int MAXSEQLEN = 1000; // doubles as the maximum range to prevent a gross amount of memory usage for this project // the base case const int BASE = 1; // 1 is not only the assigned base case, but likely the most appropriate // data array specific constants const int MAX_LEN = 2; // defines the two columns needed for the maximum numbers reached and the sequence lengths const int MAX_ELE = 0; // the column containing maximum number reached const int LENGTH = 1; // the column containing sequence lengths // file names const char CSVOUTP[NAME_LEN] = "asmt01.csv"; const char TXTOUTP[NAME_LEN] = "asmt01.txt"; // exit codes const int EXIT_BADMENU = 1; const int EXIT_BADNUM = 2; const int EXIT_BADORDER = 3; /// Global Function Prototypes/////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // // Function Name: exit_function // Summary: Exits the program after displaying an error message appropriate // to the situation. // Parameters: // Returns: void // ///////////////////////////////////////////////////////////////////////////////// void exit_function( int code ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: menu // Summary: Exits the program after displaying an error message appropriate // to the situation. // Parameters: // Returns: The number of the selection // ///////////////////////////////////////////////////////////////////////////////// int menu(); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: getRange // Summary: Prompts the user for a range of positive integers. Numbers must // be in order of least to greatest. // Parameters: // Returns: void // ///////////////////////////////////////////////////////////////////////////////// void getRange( int &startNum, int &endNum ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: processRange // Summary: Takes the range and applies the conditional function, gathers // relevant data. Stops after a maximum number of iterations to // prevent "infinite" looping, or if the base case of 1 has been // reached. // Parameters: // Returns: Returns an integer to end the function. // ///////////////////////////////////////////////////////////////////////////////// int processRange( int startNum, int endNum, int &minNum, int &minLen, int minSeq[], int &maxNum, int &maxLen, int maxSeq[], int max_len_data[MAXSEQLEN][MAX_LEN] ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: clrArr // Summary: Fills all elements of an integer array with 1; an attempt to // model the practicality of a C-string, but with integers // Parameters: // Returns: void // ///////////////////////////////////////////////////////////////////////////////// void clrArr( int arr[MAXSEQLEN] ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: mathFunction // Summary: Applies the conditional function: // if x is odd f(x) = 3x + 1 // if x is even f(x) = x / 2 // Parameters: // Returns: The integer outcome of the application of the function. // ///////////////////////////////////////////////////////////////////////////////// int mathFunction( int number ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: copySeq // Summary: Copies the contents of one array into another, but the array // attempting to mimic the functionality of a C-string, using 1 as // the null terminator. // Parameters: // Returns: void // ///////////////////////////////////////////////////////////////////////////////// void copySeq( int original[], int replacement[] ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: writeCSV // Summary: Creates a .csv file that contains every range element processed, // the maximum number, and length of the respective sequences. // Parameters: // Returns: void // ///////////////////////////////////////////////////////////////////////////////// void writeCSV( int startNum, int endNum, int max_len_data[MAXSEQLEN][MAX_LEN] ); ///////////////////////////////////////////////////////////////////////////////// // // Function Name: menu // Summary: Writes a text file containing the elements of the range that // produced the shortest and longest sequences, as well as the // entirety of their respective sequences. // Parameters: // Returns: void // ///////////////////////////////////////////////////////////////////////////////// void writeTXT( int startNum, int endNum, int minNum, int minLen, int minSeq[], int maxNum, int maxLen, int maxSeq[] ); /// Main Program Definition////////////////////////////////////////////////////// int main() { // vars int menuSel = 0; // range values int startNum = 0; int endNum = 0; // important numbers within the range int minNum = 0; // These indicate the numbers that will produce the shortest/longest sequences int maxNum = 0; // // the important sequences and their attributes int minSeq[MAXSEQLEN]; int maxSeq[MAXSEQLEN]; int minLen; int maxLen; int max_len_data[MAXSEQLEN][MAX_LEN]; // implement menu menuSel = menu(); // end program if selected by user if( menuSel == 2 ) { return 0; } // execute sequence processing, if selected if( menuSel == 1 ) { // collect range definition getRange( startNum, endNum ); // execute processing processRange( startNum, endNum, minNum, minLen, minSeq, maxNum, maxLen, maxSeq, max_len_data ); // create necessary files writeCSV( startNum, endNum, max_len_data ); writeTXT( startNum, endNum, minNum, minLen, minSeq, maxNum, maxLen, maxSeq ); } // end program return 0; } /// Supporting function implementations////////////////////////////////////////// void exit_function( int code ) { // vars int n = 0; // clear the screen while( n < 100 ) { cout << endl; n ++; } // display approriate message switch( code ) { case 1: { cout << "Invalid menu input entered. Please enter an appropriate option." << endl; } break; case 2: { cout << "Invalid range entries entered. Please enter only positive integers." << endl; } case 3: { cout << "First entry must be less than or equal to the second entry." << endl << "Please ensure that positive integers are entered in the appropriate order." << endl; } } cout << endl << "Program will now terminate." << endl << endl << endl << endl; // hold the program for the user cout << " Press any key to continue..."; for( n = 0; n < 15; n ++ ) { cout << endl; } while( ! _kbhit() ) { // do nothing until user hits a key } // end the program exit( code ); // no return - void plus exit() should have already terminated the prog } int menu() { // vars int selection = 0; // initialize menu cout << endl << endl << endl << endl << endl << endl; cout << "MAIN MENU" << endl << endl; cout << "What would you like to do?" << endl << endl; cout << "1. Compute Sequences" << endl << "2. Quit" << endl << endl; // prompt for selection cin >> selection; cout << endl << endl; // test selection for bad input if( (selection != 1) && (selection != 2) ) { exit_function( EXIT_BADMENU ); } // return signal of action to be taken return selection; } void getRange( int &startNum, int &endNum ) { // prompt for beginning of a range cout << "Enter the starting number: "; cin >> startNum; cout << endl << endl; // prompt for end of range cout << "Enter the ending number: "; cin >> endNum; cout << endl << endl; // check for valid input if( (startNum <= 0) || (endNum <= 0) ) { exit_function( EXIT_BADNUM ); } if( endNum < startNum ) { exit_function( EXIT_BADORDER); } // no return - void } int processRange( int startNum, int endNum, int &minNum, int &minLen, int minSeq[], int &maxNum, int &maxLen, int maxSeq[], int max_len_data[MAXSEQLEN][MAX_LEN] ) { // vars int currVal = startNum; int element = -888; int ndx = 0; int rndx = 0; int buffer[MAXSEQLEN]; // prep reference vars clrArr( minSeq ); clrArr( maxSeq ); minLen = 1000; maxLen = 0; // process the sequence for every number in the range for( rndx = 0; (rndx < MAXSEQLEN) && (currVal <= endNum ); currVal ++, rndx ++ ) { ndx = 0; clrArr( buffer ); element = currVal; // get starting number in sequence buffer[ndx] = element; max_len_data[rndx][MAX_ELE] = element; ndx ++; while( (element != BASE) && (ndx < MAXSEQLEN) ) // gather the rest of the sequence { element = mathFunction( element ); buffer[ndx] = element; if( element > max_len_data[rndx][MAX_ELE] ) // store the maximum number in the sequence { max_len_data[rndx][MAX_ELE] = element; } ndx ++; } // manage shortest/longest sequence info max_len_data[rndx][LENGTH] = ndx; if( ndx < minLen ) // these utilize the numbers that begin the respective sequence types { minLen = ndx; minNum = currVal; copySeq( minSeq, buffer ); } if( ndx > maxLen ) { maxLen = ndx; maxNum = currVal; copySeq( maxSeq, buffer ); } } // return 0 to end function return 0; } void clrArr( int arr[MAXSEQLEN] ) { // vars int ndx; //clear the array, using 1s to indicate the end of a sequence for( ndx = 0; ndx < MAXSEQLEN; ndx ++ ) { arr[ndx] = BASE; } // no return - void } int mathFunction( int number ) { // vars int result; // implement f(x) if( number == BASE ) { return BASE; } if( (number % 2) == 1) // if x is odd, f(x) = 3x + 1 { result = ((3 * number) + 1); } if( (number % 2) == 0) // if x is even, f(x) = x/2 { result = ( number / 2 ); } return result; } void copySeq( int original[], int replacement[] ) { // vars int ndx = 0; clrArr( original ); while( replacement[ndx] != 1 ) { original[ndx] = replacement[ndx]; ndx ++; } // no return - void } void writeCSV( int startNum, int endNum, int max_len_data[MAXSEQLEN][MAX_LEN] ) { // vars int rndx = 0; int currVal = startNum; char delim = ','; char f_header[MAXSEQLEN] = "Starting Number,Maximum Number,Length"; ofstream fout; // clear and open fout.clear(); fout.open( CSVOUTP ); // write file fout << f_header << endl; while( currVal <= endNum ) { fout << currVal << delim << max_len_data[rndx][MAX_ELE] << delim << max_len_data[rndx][LENGTH] << endl; currVal ++, rndx ++; } // no return - void } void writeTXT( int startNum, int endNum, int minNum, int minLen, int minSeq[], int maxNum, int maxLen, int maxSeq[] ) { // vars int ndx = 0; ofstream fout; // clear and open fout.clear(); fout.open( TXTOUTP ); // write the file fout << "Beginning of the range: " << startNum << endl << endl; fout << "End of Range: " << endNum << endl << endl; fout << "Starting number for the sequence with minimum length: " << minNum << endl << "The minimum length: " << minLen << endl << endl; fout << "Starting number for the sequence with maximum length: " << maxNum << endl << "The maximum length: " << maxLen << endl << endl; fout << "Sequence with minimum length: "; for(ndx = 0; ndx < minLen; ndx ++ ) { fout << minSeq[ndx] << endl << " "; } fout << endl << endl; fout << "Sequence with maximum length: "; for(ndx = 0; ndx < maxLen; ndx ++ ) { fout << maxSeq[ndx] << endl << " "; } // close fout.close(); // no return - void }
27.311377
120
0.497186
T-R0D
311f77ac5a87b6e4a5958b9324f13d2d3fd0905e
3,768
hpp
C++
include/gl/tone_mapping/segmentation_tmo_approx.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/gl/tone_mapping/segmentation_tmo_approx.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/gl/tone_mapping/segmentation_tmo_approx.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_GL_TONE_MAPPING_SEGMENTATION_TMO_APPROX_HPP #define PIC_GL_TONE_MAPPING_SEGMENTATION_TMO_APPROX_HPP #include "../../gl/filtering/filter_luminance.hpp" #include "../../gl/filtering/filter_remove_nuked.hpp" #include "../../gl/filtering/filter_iterative.hpp" #include "../../gl/filtering/filter_bilateral_2ds.hpp" #include "../../gl/filtering/filter_op.hpp" namespace pic { /** * @brief The SegmentationGL class */ class SegmentationGL { protected: FilterGLLuminance *flt_lum; FilterGLRemoveNuked *flt_nuked; FilterGLIterative *flt_it; FilterGLBilateral2DS *flt_bil; FilterGLOp *flt_seg; ImageGL *L, *imgIn_flt; float perCent, nLayer; int iterations; public: ImageGLVec stack; float minVal, maxVal; /** * @brief SegmentationGL */ SegmentationGL() { flt_nuked = NULL; flt_lum = NULL; flt_bil = NULL; flt_it = NULL; flt_seg = NULL; nLayer = 0.0f; iterations = 0; L = NULL; imgIn_flt = NULL; maxVal = FLT_MAX; minVal = 0.0f; perCent = 0.005f; } ~SegmentationGL() { if(imgIn_flt != NULL) { delete imgIn_flt; imgIn_flt = NULL; } if(L != NULL) { delete L; L = NULL; } delete flt_it; delete flt_bil; delete flt_seg; delete flt_nuked; } /** * @brief computeStatistics * @param imgIn */ void computeStatistics(Image *imgIn) { float nLevels, area; nLevels = log10f(maxVal) - log10f(minVal) + 1.0f; nLayer = ((maxVal - minVal) / nLevels) / 4.0f; area = imgIn->widthf * imgIn->heightf * perCent; iterations = MAX(int(sqrtf(area)) / 8, 1); } /** * @brief execute * @param imgIn * @param imgOut * @return */ ImageGL *execute(ImageGL *imgIn, ImageGL *imgOut) { if(imgIn == NULL) { return imgOut; } if(!imgIn->isValid()) { return imgOut; } if(imgOut == NULL) { imgOut = new ImageGL(1, imgIn->width, imgIn->height, 1, IMG_GPU, GL_TEXTURE_2D); } //compute luminance if(flt_lum == NULL) { flt_lum = new FilterGLLuminance(); } L = flt_lum->Process(SingleGL(imgIn), L); L->getMinVal(&minVal); L->getMaxVal(&maxVal); //iterative bilateral filtering if(flt_it == NULL) { flt_bil = new FilterGLBilateral2DS(1.0f, nLayer); flt_it = new FilterGLIterative(flt_bil, iterations); } imgIn_flt = flt_it->Process(SingleGL(imgIn), imgIn_flt); L = flt_lum->Process(SingleGL(imgIn_flt), L); //threshold if(flt_seg == NULL) { flt_seg = FilterGLOp::CreateOpSegmentation(false, floor(log10f(minVal))); } flt_seg->Process(SingleGL(L), L); //remove nuked pixels if(flt_nuked == NULL) { flt_nuked = new FilterGLRemoveNuked(0.9f); } flt_nuked->Process(SingleGL(L), imgOut); return imgOut; } }; } // end namespace pic #endif /* PIC_GL_TONE_MAPPING_SEGMENTATION_TMO_APPROX_HPP */
22.97561
92
0.568737
ecarpita93
3120a5fd12929fd16cd8a0b29840088e4c5070a4
5,544
hpp
C++
libcore/src/network/ASIOConnectAndHandshake.hpp
ericruth/sirikata
9b4cad53b9bef46d318d52581d489d691b6f9e58
[ "BSD-3-Clause" ]
1
2016-05-09T11:45:31.000Z
2016-05-09T11:45:31.000Z
libcore/src/network/ASIOConnectAndHandshake.hpp
mullwaden/sirikata
bedcf22c97f733d82bffcd787f21c25b4e6710ed
[ "BSD-3-Clause" ]
null
null
null
libcore/src/network/ASIOConnectAndHandshake.hpp
mullwaden/sirikata
bedcf22c97f733d82bffcd787f21c25b4e6710ed
[ "BSD-3-Clause" ]
null
null
null
/* Sirikata Network Utilities * ASIOConnectAndHandshake.hpp * * Copyright (c) 2009, Daniel Reiter Horn * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sirikata 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. */ namespace Sirikata { namespace Network { class ASIOConnectAndHandshake{ boost::asio::ip::tcp::resolver mResolver; std::tr1::weak_ptr<MultiplexedSocket> mConnection; ///num positive checks remaining (or -n for n sockets of which at least 1 failed) int mFinishedCheckCount; UUID mHeaderUUID; Array<uint8,TCPStream::TcpSstHeaderSize> mFirstReceivedHeader; typedef boost::system::error_code ErrorCode; /** * This function checks a particular sockets initial handshake header. * If this is the first header read, it will save it for comparison * If this is the nth header read and everythign is successful it will decrement the first header check integer * If anything goes wrong and it is the first time, it will decrement the first header check integer below zero to indiate error and call connectionFailed * If anything goes wrong and the first header check integer is already below zero it will decline to take action * The buffer passed in will be deleted by this function */ void checkHeaderContents(unsigned int whichSocket, Array<uint8,TCPStream::TcpSstHeaderSize>* buffer, const ErrorCode&error, std::size_t bytes_received); /** * This function simply wraps checkHeaderContents having been passed a shared_ptr from an asio_callback */ static void checkHeader(const std::tr1::shared_ptr<ASIOConnectAndHandshake>&thus, unsigned int whichSocket, Array<uint8,TCPStream::TcpSstHeaderSize>* buffer, const ErrorCode&error, std::size_t bytes_received) { thus->checkHeaderContents(whichSocket,buffer,error,bytes_received); } /** * This function checks if a particular sockets has connected to its destination IP address * If everything is successful it will decrement the first header check integer * If the last resolver fails and it is the first time, it will decrement the first header check integer below zero to indiate error and call connectionFailed * If anything goes wrong and the first header check integer is already below zero it will decline to take action * The buffer passed in will be deleted by this function */ static void connectToIPAddress(const std::tr1::shared_ptr<ASIOConnectAndHandshake>&thus, unsigned int whichSocket, const boost::asio::ip::tcp::resolver::iterator &it, const ErrorCode &error); /** * This function is a callback from the async_resolve call from ASIO initialized from the public interface connect * It may get an error if the host was not found or otherwise a valid iterator to a number of ip addresses */ static void handleResolve(const std::tr1::shared_ptr<ASIOConnectAndHandshake>&thus, const boost::system::error_code &error, boost::asio::ip::tcp::resolver::iterator it); public: /** * This function transforms the member mConnection from the PRECONNECTION socket phase to the CONNECTED socket phase * It first performs a resolution on the address and handles the callback in handleResolve. * If the header checks out and matches with the other live sockets to the same sockets * - MultiplexedSocket::connectedCallback() is called * - An ASIOReadBuffer is created for handling future reads */ static void connect(const std::tr1::shared_ptr<ASIOConnectAndHandshake> &thus, const Address&address); ASIOConnectAndHandshake(const std::tr1::shared_ptr<MultiplexedSocket> &connection, const UUID&sharedUuid); }; } }
56.571429
161
0.696789
ericruth
3120b4168fba48e658841be45de6c8c54eaaa1f9
733
cpp
C++
code-examples/lab_k28c_15_09_20_oop.cpp
kzhereb/knu-ips-ooop-2020-2021
777b4a847a537510048fd582eda0816ce05db4b5
[ "MIT" ]
null
null
null
code-examples/lab_k28c_15_09_20_oop.cpp
kzhereb/knu-ips-ooop-2020-2021
777b4a847a537510048fd582eda0816ce05db4b5
[ "MIT" ]
34
2021-03-25T08:28:26.000Z
2021-05-20T13:12:48.000Z
code-examples/lab_k28c_15_09_20_oop.cpp
kzhereb/knu-ips-ooop-2020-2021
777b4a847a537510048fd582eda0816ce05db4b5
[ "MIT" ]
1
2020-09-28T12:58:26.000Z
2020-09-28T12:58:26.000Z
/* * lab_k28c_15_09_20_oop.cpp * * Created on: Sep 15, 2020 * Author: KZ */ #include "doctest.h" #include <string> class Human { private: double height; // in cm double weight; // in kg std::string name; public: Human(double height, double weight, std::string name): height{height}, weight{weight}, name{name} { } double get_height() { return this->height;} bool is_tankist() { return height <= 170; } }; TEST_CASE("creating human and accessing properties") { Human someone(170, 50, "Yehor"); CHECK(someone.get_height() == 170); CHECK(someone.is_tankist()); Human someone2(171, 50, "Andrii"); CHECK(someone2.get_height() == 171); CHECK_FALSE(someone2.is_tankist()); }
20.942857
103
0.645293
kzhereb
3123d0de4593afdd3f0fc78caa3d17a61514359a
2,788
cc
C++
gutil/barrier_cpp11.cc
mfkiwl/cvkit
38dce78aa32a2607577973fe7af8d9d0e3ef0923
[ "BSD-3-Clause" ]
230
2017-03-08T04:47:16.000Z
2022-03-04T16:35:10.000Z
gutil/barrier_cpp11.cc
mfkiwl/cvkit
38dce78aa32a2607577973fe7af8d9d0e3ef0923
[ "BSD-3-Clause" ]
18
2017-11-21T21:56:11.000Z
2021-12-14T06:05:03.000Z
gutil/barrier_cpp11.cc
mfkiwl/cvkit
38dce78aa32a2607577973fe7af8d9d0e3ef0923
[ "BSD-3-Clause" ]
61
2017-03-12T19:32:23.000Z
2022-03-01T07:38:39.000Z
/* * This file is part of the Computer Vision Toolkit (cvkit). * * Author: Heiko Hirschmueller * * Copyright (c) 2020 Roboception GmbH * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "barrier.h" #include "thread.h" #include <mutex> #include <condition_variable> namespace gutil { struct BarrierData { int generation; int init_count; int count; std::mutex mtx; std::condition_variable cv; }; Barrier::Barrier(int c) { p=new BarrierData(); p->generation=0; p->init_count=c; if (p->init_count < 1) { p->init_count=Thread::getMaxThreads(); } p->count=p->init_count; } Barrier::~Barrier() { delete p; } void Barrier::reinit(int c) { std::unique_lock<std::mutex> lck(p->mtx); p->init_count=c; if (p->init_count < 1) { p->init_count=Thread::getMaxThreads(); } p->generation++; p->count=p->init_count; p->cv.notify_all(); } int Barrier::getCount() { return p->init_count; } void Barrier::wait() { std::unique_lock<std::mutex> lck(p->mtx); int gen=p->generation; p->count--; if (p->count == 0) { p->generation++; p->count=p->init_count; p->cv.notify_all(); return; } while (gen == p->generation) { p->cv.wait(lck); } } }
24.243478
80
0.689742
mfkiwl
3124ad00a21443fa67c5c606c398bfe5cd9d957c
7,321
cpp
C++
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_WaveformDisplay.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_WaveformDisplay.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/jura_framework/gui/panels/jura_WaveformDisplay.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
//------------------------------------------------------------------------------------------------- // construction/destruction: WaveformDisplay::WaveformDisplay(AudioFileBuffer *newBuffer) : InteractiveCoordinateSystem("WaveformDisplay"), AudioFileBufferUser(newBuffer) { ScopedLock pointerLock(audioFileBufferPointerLock); Component::setName(String("WaveformDisplay")); firstChannelToPlot = 0; lastChannelToPlot = 7; // restrict plot to 8 channels by default //setValueFieldPopup(false); if( bufferToUse != NULL ) { double maxTime = jmax(bufferToUse->getLengthInSeconds(), 0.0001); // 1/10 ms minimum range setMaximumRangeX(0.0, maxTime); setCurrentRangeX(0.0, maxTime); minVisibleTime = 0.0; maxVisibleTime = maxTime; //numChannels = bufferToUse->getNumChannels(); //numSamples = bufferToUse->getNumSamples(); //sampleRate = bufferToUse->getFileSampleRate(); // mmmhh. could be used directly in plot... } else { // use some fallback-values when we got a NULL pointer setMaximumRange(0.0, 0.001, -1.0, +1.0); setCurrentRange(0.0, 0.001, -1.0, +1.0); minVisibleTime = 0.0; maxVisibleTime = 0.001; //numChannels = 0; //numSamples = 0; //sampleRate = 44100.0; } } //------------------------------------------------------------------------------------------------- // setup: void WaveformDisplay::assignAudioFileBuffer(AudioFileBuffer *newBuffer) { ScopedLock pointerLock(audioFileBufferPointerLock); if( newBuffer != bufferToUse ) { AudioFileBufferUser::assignAudioFileBuffer(newBuffer); setRangeToBufferLength(); /* if( bufferToUse != NULL ) { double maxTime = jmax(bufferToUse->getLengthInSeconds(), 0.0001); // 1/10 ms minimum range setMaximumRangeX(0.0, maxTime); setCurrentRangeX(0.0, maxTime); minVisibleTime = 0.0; maxVisibleTime = maxTime; //numChannels = bufferToUse->getNumChannels(); //numSamples = bufferToUse->getNumSamples(); //sampleRate = bufferToUse->getFileSampleRate(); // mmmhh. could be used directly in plot... } */ } } void WaveformDisplay::setRangeToBufferLength() { ScopedLock pointerLock(audioFileBufferPointerLock); if( bufferToUse != NULL ) { double maxTime = jmax(bufferToUse->getLengthInSeconds(), 0.0001); // 1/10 ms minimum range setMaximumRangeX(0.0, maxTime); setCurrentRangeX(0.0, maxTime); minVisibleTime = 0.0; maxVisibleTime = maxTime; } } /* void WaveformDisplay::setSampleRate(double newSampleRate) { jassert(newSampleRate > 0.0); // zero or negative sample-rates are not supported ;-) if( newSampleRate > 0.0 ) sampleRate = newSampleRate; repaint(); } */ void WaveformDisplay::setFirstChannelToPlot(int newFirstChannelIndex) { jassert(newFirstChannelIndex >= 0); // negative channel-index? no! counting starts at 0 if( newFirstChannelIndex >= 0 ) firstChannelToPlot = newFirstChannelIndex; } void WaveformDisplay::setLastChannelToPlot(int newLastChannelIndex) { jassert(newLastChannelIndex >= 0); // negative channel-index? no! counting starts at 0 if( newLastChannelIndex >= 0 ) lastChannelToPlot = newLastChannelIndex; } void WaveformDisplay::plotOnlyOneChannel(int channelToPlotIndex) { setFirstChannelToPlot(channelToPlotIndex); setLastChannelToPlot(channelToPlotIndex); } void WaveformDisplay::setVisibleTimeRange(double newMinTimeInSeconds, double newMaxTimeInSeconds) { minVisibleTime = newMinTimeInSeconds; maxVisibleTime = newMaxTimeInSeconds; } //------------------------------------------------------------------------------------------------- // others: /* void WaveformDisplay::resized() { Panel::resized(); ThreadedDrawingComponent::resized(); } void WaveformDisplay::setDirty(bool shouldBeSetToDirty) { Panel::setDirty(shouldBeSetToDirty); ThreadedDrawingComponent::setDirty(shouldBeSetToDirty); } */ //------------------------------------------------------------------------------------------------- // drawing: void WaveformDisplay::drawComponent(Image* imageToDrawOnto) { Graphics g(*imageToDrawOnto); drawCoordinateSystem(g, imageToDrawOnto); //g.fillAll(Colours::white); // preliminary - call CoordinateSystem background drawing stuff here plotWaveform(imageToDrawOnto); g.drawRect(0, 0, imageToDrawOnto->getWidth(), imageToDrawOnto->getHeight(), 1); } void WaveformDisplay::plotWaveform(Image *targetImage) { if( targetImage == NULL ) return; Graphics g(*targetImage); // make sure that the pointer to the bufferToUse is not modified during this function: bool pointerLockAcquired = audioFileBufferPointerLock.tryEnter(); if( pointerLockAcquired == false ) return; // check if we have a valid buffer - if not, return - we don't need to aquire the readlock for // the data here, because we use getMinMaxSamples to retrieve the data which in itself aquires // the read-lock: if( bufferToUse == NULL ) { audioFileBufferPointerLock.exit(); return; } //ScopedReadLock dataLock(bufferToUse->audioDataReadWriteLock); bufferToUse->acquireReadLock(); // we have our read-lock - do the work: int numChannels = bufferToUse->getNumChannels(); int numSamples = bufferToUse->getNumSamples(); double sampleRate = bufferToUse->getFileSampleRate(); double pixelWidth = (double) getWidth(); if( targetImage != NULL ) pixelWidth = (double) targetImage->getWidth(); double tSecMin = currentRange.getMinX(); // min-time in seconds double tSecMax = currentRange.getMaxX(); // max-time in seconds double tSecInc = (tSecMax-tSecMin) / pixelWidth; // increment per pixel double tSmpMin = tSecMin * sampleRate; // min-time in samples double tSmpMax = tSecMax * sampleRate; // max-time in samples double tSmpInc = (tSmpMax-tSmpMin) / pixelWidth; // increment per pixel int cMin = jmax(0, firstChannelToPlot); int cMax = jmin(numChannels-1, lastChannelToPlot); //int curveDrawn = 0; //float dotRadius = 3.f; // outer loop over the channels: double tSec, tSmp; double x1, x2, y1, y2; int nMin, nMax; g.setColour(Colours::blue); for(int c=cMin ; c<=cMax; c++) { // inner loop over pixels: tSec = tSecMin; tSmp = tSmpMin; while( tSmp <= tSmpMax ) { nMin = jlimit(0, numSamples-1, (int) floor(tSmp) ); nMax = jlimit(0, numSamples-1, (int) ceil( tSmp+tSmpInc) ); x1 = (float) tSec; x2 = (float) (tSec+tSecInc); //bufferToUse->getMinMaxSamples(c, nMin, nMax-nMin+1, y1, y2); bufferToUse->getMinMaxSamplesWithoutLock(c, nMin, nMax-nMin+1, y1, y2); toPixelCoordinates(x1, y1); toPixelCoordinates(x2, y2); g.drawLine((float)x1, (float)y1, (float)x2, (float)y2); tSec += tSecInc; tSmp += tSmpInc; } } bufferToUse->releaseReadLock(); audioFileBufferPointerLock.exit(); } void WaveformDisplay::restrictToVisibleSection(double &tMin, double &tMax, double marginInPercent) const { double marginAbsolute = 0.01*marginInPercent*(maxVisibleTime-minVisibleTime); tMin = jmax(tMin, minVisibleTime-marginAbsolute); tMax = jmin(tMax, maxVisibleTime+marginAbsolute); }
31.692641
102
0.657014
RobinSchmidt
3124b9703540d2b0d976ae3e7c1f2238c0a049d9
630
cpp
C++
LeetCode/1000/812.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/1000/812.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/1000/812.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
class Solution { public: int cross(int x1, int y1, int x2, int y2) { return x1 * y2 - x2 * y1; } double largestTriangleArea(vector<vector<int>>& points) { double res = 0; for (int i = 0; i < points.size(); i++) { for (int j = i + 1; j < points.size(); j++) { for (int k = j + 1; k < points.size(); k++) { int x1 = points[j][0] - points[i][0]; int y1 = points[j][1] - points[i][1]; int x2 = points[k][0] - points[i][0]; int y2 = points[k][1] - points[i][1]; res = max(res, abs(cross(x1, y1, x2, y2) / 2.0)); } } } return res; } };
33.157895
73
0.474603
K-ona
3125fd3d0369289349e3de0ea4dde1efd2eac79b
15,526
cpp
C++
Source/Lib/Uncompressed/WAV/WAV.cpp
g-maxime/RAWCooked
6b2ef51208a6b23822560112b024bdc2d3f595b0
[ "BSD-2-Clause" ]
null
null
null
Source/Lib/Uncompressed/WAV/WAV.cpp
g-maxime/RAWCooked
6b2ef51208a6b23822560112b024bdc2d3f595b0
[ "BSD-2-Clause" ]
null
null
null
Source/Lib/Uncompressed/WAV/WAV.cpp
g-maxime/RAWCooked
6b2ef51208a6b23822560112b024bdc2d3f595b0
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- #include "Lib/Uncompressed/WAV/WAV.h" #include "Lib/Compressed/RAWcooked/RAWcooked.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Errors namespace wav_issue { namespace undecodable { static const char* MessageText[] = { "file smaller than expected", "RIFF chunk size", "fmt chunk size", "truncated chunk", }; enum code : uint8_t { BufferOverflow, RIFF_ChunkSize, fmt__ChunkSize, TruncatedChunk, Max }; namespace undecodable { static_assert(Max == sizeof(MessageText) / sizeof(const char*), IncoherencyMessage); } } // unparsable namespace unsupported { static const char* MessageText[] = { // Unsupported "RF64 (4GB+ WAV)", "fmt FormatTag not WAVE_FORMAT_PCM 1", "fmt AvgBytesPerSec", "fmt BlockAlign", "fmt extension", "fmt cbSize", "fmt ValidBitsPerSample", "fmt ChannelMask", "fmt SubFormat not KSDATAFORMAT_SUBTYPE_PCM 00000001-0000-0010-8000-00AA00389B71", "fmt chunk not before data chunk", "Flavor (SamplesPerSec / BitDepth / Channels / Endianness combination)", "data chunk size is not a multiple of BlockAlign", }; enum code : uint8_t { RF64, fmt__FormatTag, fmt__AvgBytesPerSec, fmt__BlockAlign, fmt__extension, fmt__cbSize, fmt__ValidBitsPerSample, fmt__ChannelMask, fmt__SubFormat, fmt__Location, Flavor, data_Size, Max }; namespace undecodable { static_assert(Max == sizeof(MessageText) / sizeof(const char*), IncoherencyMessage); } } // unsupported const char** ErrorTexts[] = { undecodable::MessageText, unsupported::MessageText, nullptr, nullptr, }; static_assert(error::type_Max == sizeof(ErrorTexts) / sizeof(const char**), IncoherencyMessage); } // wav_issue using namespace wav_issue; //--------------------------------------------------------------------------- // Enums enum class sample_per_sec_code : uint8_t { _44100, _48000, _96000, }; //--------------------------------------------------------------------------- // Tested cases struct wav_tested { sample_per_sec_code SamplesPerSecCode; uint8_t BitDepth; uint8_t Channels; bool operator == (const wav_tested& Value) const { return SamplesPerSecCode == Value.SamplesPerSecCode && BitDepth == Value.BitDepth && Channels == Value.Channels ; } }; struct wav_tested WAV_Tested[] = { { sample_per_sec_code::_44100, 8, 1 }, { sample_per_sec_code::_44100, 8, 2 }, { sample_per_sec_code::_44100, 8, 6 }, { sample_per_sec_code::_44100, 16, 1 }, { sample_per_sec_code::_44100, 16, 2 }, { sample_per_sec_code::_44100, 16, 6 }, { sample_per_sec_code::_44100, 24, 1 }, { sample_per_sec_code::_44100, 24, 2 }, { sample_per_sec_code::_44100, 24, 6 }, { sample_per_sec_code::_48000, 8, 1 }, { sample_per_sec_code::_48000, 8, 2 }, { sample_per_sec_code::_48000, 8, 6 }, { sample_per_sec_code::_48000, 16, 1 }, { sample_per_sec_code::_48000, 16, 2 }, { sample_per_sec_code::_48000, 16, 6 }, { sample_per_sec_code::_48000, 24, 1 }, { sample_per_sec_code::_48000, 24, 2 }, { sample_per_sec_code::_48000, 24, 6 }, { sample_per_sec_code::_96000, 8, 1 }, { sample_per_sec_code::_96000, 8, 2 }, { sample_per_sec_code::_96000, 8, 6 }, { sample_per_sec_code::_96000, 16, 1 }, { sample_per_sec_code::_96000, 16, 2 }, { sample_per_sec_code::_96000, 16, 6 }, { sample_per_sec_code::_96000, 24, 1 }, { sample_per_sec_code::_96000, 24, 2 }, { sample_per_sec_code::_96000, 24, 6 }, }; static_assert(wav::flavor_Max == sizeof(WAV_Tested) / sizeof(wav_tested), IncoherencyMessage); //--------------------------------------------------------------------------- #define ELEMENT_BEGIN(_VALUE) \ wav::call wav::SubElements_##_VALUE(uint64_t Name) \ { \ switch (Name) \ { \ #define ELEMENT_CASE(_VALUE,_NAME) \ case 0x##_VALUE: Levels[Level].SubElements = &wav::SubElements_##_NAME; return &wav::_NAME; #define ELEMENT_VOID(_VALUE,_NAME) \ case 0x##_VALUE: Levels[Level].SubElements = &wav::SubElements_Void; return &wav::_NAME; #define ELEMENT_END() \ default: return SubElements_Void(Name); \ } \ } \ ELEMENT_BEGIN(_) ELEMENT_CASE(5249464657415645LL, WAVE) ELEMENT_END() ELEMENT_BEGIN(WAVE) ELEMENT_VOID(64617461, WAVE_data) ELEMENT_VOID(666D7420, WAVE_fmt_) ELEMENT_END() //--------------------------------------------------------------------------- wav::call wav::SubElements_Void(uint64_t /*Name*/) { Levels[Level].SubElements = &wav::SubElements_Void; return &wav::Void; } //*************************************************************************** // WAV //*************************************************************************** //--------------------------------------------------------------------------- wav::wav(errors* Errors_Source) : input_base_uncompressed_audio(Errors_Source, Parser_WAV) { } //--------------------------------------------------------------------------- void wav::ParseBuffer() { if (Buffer.Size() < 12) return; if (Buffer[8] != 'W' || Buffer[9] != 'A' || Buffer[10] != 'V' || Buffer[11] != 'E') return; if (Buffer[0] == 'R' && Buffer[1] == 'F' && Buffer[2] == '6' && Buffer[3] == '4') { Unsupported(unsupported::RF64); return; } if (Buffer[0] != 'R' || Buffer[1] != 'I' || Buffer[2] != 'F' || Buffer[3] != 'F') return; SetDetected(); Flavor = flavor_Max; // Used for detected if fmt chunk is parsed Buffer_Offset = 0; Levels[0].Offset_End = Buffer.Size(); Levels[0].SubElements = &wav::SubElements__; Level=1; while (Buffer_Offset < Buffer.Size()) { // Find the current nesting level while (Buffer_Offset >= Levels[Level - 1].Offset_End) { Levels[Level].SubElements = NULL; Level--; } uint64_t End = Levels[Level - 1].Offset_End; // Parse the chunk header uint64_t Name; uint64_t Size; if (Buffer_Offset + 8 > End) { Undecodable(undecodable::TruncatedChunk); return; } Name = Get_B4(); Size = Get_L4(); if (Name == 0x52494646) // "RIFF" { if (Size < 4 || Buffer_Offset + 4 > End) { Undecodable(undecodable::RIFF_ChunkSize); return; } Name <<= 32; Name |= Get_B4(); Size -= 4; } if (Buffer_Offset + Size > End) { if (!Actions[Action_AcceptTruncated]) { Undecodable(undecodable::TruncatedChunk); return; } Size = Levels[Level - 1].Offset_End - Buffer_Offset; } // Parse the chunk content Levels[Level].Offset_End = Buffer_Offset + Size; call Call = (this->*Levels[Level - 1].SubElements)(Name); IsList = false; (this->*Call)(); if (!IsList) { Buffer_Offset = Levels[Level].Offset_End; // Padding byte if (Buffer_Offset % 2 && Buffer_Offset < Buffer.Size() && !Buffer[Buffer_Offset]) { Buffer_Offset++; Levels[Level].Offset_End = Buffer_Offset; } } // Next chunk (or sub-chunk) if (Buffer_Offset < Levels[Level].Offset_End) Level++; } } //--------------------------------------------------------------------------- void wav::Void() { } //--------------------------------------------------------------------------- void wav::WAVE() { IsList = true; } //--------------------------------------------------------------------------- void wav::WAVE_data() { // Test if fmt chunk was parsed if (!HasErrors() && Flavor == flavor_Max) Unsupported(unsupported::fmt__Location); // Coherency test if (BlockAlign) { uint64_t Size = Levels[Level].Offset_End - Buffer_Offset; if (Size % BlockAlign) Unsupported(unsupported::data_Size); if (InputInfo && !InputInfo->SampleCount) InputInfo->SampleCount = Size / BlockAlign; } // Can we compress? if (!HasErrors()) SetSupported(); // Write RAWcooked file if (IsSupported() && RAWcooked) { RAWcooked->Unique = true; RAWcooked->BeforeData = Buffer.Data(); RAWcooked->BeforeData_Size = Buffer_Offset; RAWcooked->AfterData = Buffer.Data() + Levels[Level].Offset_End; RAWcooked->AfterData_Size = Buffer.Size() - Levels[Level].Offset_End; RAWcooked->InData = nullptr; RAWcooked->InData_Size = 0; RAWcooked->FileSize = (uint64_t)-1; if (Actions[Action_Hash]) { Hash(); RAWcooked->HashValue = &HashValue; } else RAWcooked->HashValue = nullptr; RAWcooked->IsAttachment = false; RAWcooked->Parse(); } } //--------------------------------------------------------------------------- void wav::WAVE_fmt_() { if (Levels[Level].Offset_End - Buffer_Offset < 16) { Undecodable(undecodable::fmt__ChunkSize); return; } uint16_t FormatTag = Get_L2(); if (FormatTag != 1 && FormatTag != 0xFFFE) Unsupported(unsupported::fmt__FormatTag); wav_tested Info; uint16_t Channels = Get_L2(); uint32_t SamplesPerSec = Get_L4(); uint32_t AvgBytesPerSec = Get_L4(); BlockAlign = Get_L2(); uint16_t BitDepth = Get_L2(); if (AvgBytesPerSec * 8 != Channels * BitDepth * SamplesPerSec) Unsupported(unsupported::fmt__AvgBytesPerSec); if (BlockAlign * 8 != Channels * BitDepth) Unsupported(unsupported::fmt__BlockAlign); if (FormatTag == 1) { // Some files have zeroes after actual fmt content, it does not hurt so we accept them while (Buffer_Offset + 2 <= Levels[Level].Offset_End) { uint16_t Padding0 = Get_L2(); if (Padding0) { Unsupported(unsupported::fmt__extension); return; } } if (Levels[Level].Offset_End - Buffer_Offset) { Unsupported(unsupported::fmt__extension); return; } } if (FormatTag == 0xFFFE) { if (Levels[Level].Offset_End - Buffer_Offset != 24) { Unsupported(unsupported::fmt__extension); return; } uint16_t cbSize = Get_L2(); if (cbSize != 22) { Unsupported(unsupported::fmt__cbSize); return; } uint16_t ValidBitsPerSample = Get_L2(); if (ValidBitsPerSample != BitDepth) Unsupported(unsupported::fmt__ValidBitsPerSample); uint32_t ChannelMask = Get_L4(); if ((Channels != 1 || (ChannelMask != 0x00000000 && ChannelMask != 0x00000004)) && (Channels != 2 || (ChannelMask != 0x00000000 && ChannelMask != 0x00000003)) && (Channels != 6 || (ChannelMask != 0x00000000 && ChannelMask != 0x0000003F && ChannelMask != 0x0000060F))) Unsupported(unsupported::fmt__ChannelMask); uint32_t SubFormat1 = Get_L4(); uint32_t SubFormat2 = Get_L4(); uint32_t SubFormat3 = Get_B4(); uint64_t SubFormat4 = Get_B4(); if (SubFormat1 != 0x00000001 || SubFormat2 != 0x00100000 || SubFormat3 != 0x800000aa || SubFormat4 != 0x00389b71) Unsupported(unsupported::fmt__SubFormat); } // Supported? if (BitDepth > (decltype(wav_tested::BitDepth))-1 || Channels > (decltype(wav_tested::Channels))-1) { Unsupported(unsupported::Flavor); return; } switch (SamplesPerSec) { case 44100: Info.SamplesPerSecCode = sample_per_sec_code::_44100; break; case 48000: Info.SamplesPerSecCode = sample_per_sec_code::_48000; break; case 96000: Info.SamplesPerSecCode = sample_per_sec_code::_96000; break; default : Info.SamplesPerSecCode = (decltype(Info.SamplesPerSecCode))-1; } Info.BitDepth = (decltype(wav_tested::BitDepth))BitDepth; Info.Channels = (decltype(wav_tested::Channels))Channels; for (const auto& WAV_Tested_Item : WAV_Tested) { if (WAV_Tested_Item == Info) { Flavor = (decltype(Flavor))(&WAV_Tested_Item - WAV_Tested); break; } } if (Flavor == (decltype(Flavor))-1) Unsupported(unsupported::Flavor); if (HasErrors()) return; if (InputInfo && !InputInfo->SampleRate) InputInfo->SampleRate = SamplesPerSec; } //--------------------------------------------------------------------------- void wav::BufferOverflow() { Undecodable(undecodable::BufferOverflow); } //--------------------------------------------------------------------------- string wav::Flavor_String() { return WAV_Flavor_String(Flavor); } //--------------------------------------------------------------------------- uint8_t wav::BitDepth() { return WAV_Tested[Flavor].BitDepth; } //--------------------------------------------------------------------------- endianness wav::Endianness() { return endianness::LE; } //--------------------------------------------------------------------------- static const char* SamplesPerSec_String(wav::flavor Flavor) { switch (WAV_Tested[(size_t)Flavor].SamplesPerSecCode) { case sample_per_sec_code::_44100: return "44"; case sample_per_sec_code::_48000: return "48"; case sample_per_sec_code::_96000: return "96"; } return nullptr; } //--------------------------------------------------------------------------- static string BitDepth_String(wav::flavor Flavor) { return to_string(WAV_Tested[(size_t)Flavor].BitDepth); } //--------------------------------------------------------------------------- static string Channels_String(wav::flavor Flavor) { return to_string(WAV_Tested[(size_t)Flavor].Channels); } //--------------------------------------------------------------------------- string WAV_Flavor_String(uint8_t Flavor) { string ToReturn("WAV/PCM/"); ToReturn += SamplesPerSec_String((wav::flavor)Flavor); ToReturn += "kHz/"; ToReturn += BitDepth_String((wav::flavor)Flavor); ToReturn += "bit/"; ToReturn += Channels_String((wav::flavor)Flavor); ToReturn += "ch/LE"; return ToReturn; }
30.265107
118
0.51797
g-maxime
312791034812c6809945ca4b7f033363c0df0ae7
2,756
cpp
C++
18_lab/main.cpp
TimmiJK/2021-spring-polytech-cpp
1e957a2619e5c61f1dc1b7941ffae5d70b86870c
[ "MIT" ]
6
2021-02-08T15:26:20.000Z
2021-03-22T10:19:07.000Z
18_lab/main.cpp
TimmiJK/2021-spring-polytech-cpp
1e957a2619e5c61f1dc1b7941ffae5d70b86870c
[ "MIT" ]
11
2021-02-09T06:41:50.000Z
2021-04-18T08:36:32.000Z
18_lab/main.cpp
TimmiJK/2021-spring-polytech-cpp
1e957a2619e5c61f1dc1b7941ffae5d70b86870c
[ "MIT" ]
48
2021-02-03T18:28:55.000Z
2021-05-24T18:54:14.000Z
// Напишите программу, используя технику TDD. Реализуйте калькулятор, // поддерживающий операции: +, -, *, /. Проверьте тестами свойства операций // и законы элементарной алгебры. #include <cassert> enum class Command { Add, Sub, Mul, Div }; double calc(enum class Command operation, double x, double y) { double result; switch (operation) { case Command::Add: result = x + y; break; case Command::Sub: result = x - y; break; case Command::Mul: result = x * y; break; case Command::Div: if (y != 0) { result = x / y; } break; default: result = 0; break; } return result; } int main() { // Операции с нулями assert(calc(Command::Add, 0.0, 0.0) == 0.0); assert(calc(Command::Sub, 0.0, 0.0) == 0.0); assert(calc(Command::Mul, 0.0, 0.0) == 0.0); assert(calc(Command::Div, 0.0, 5.0) == 0.0); // Коммутативность сложения assert(calc(Command::Add, 2.0, 1.0) == calc(Command::Add, 1.0, 2.0)); // Ассоциативность сложения assert(calc(Command::Add, calc(Command::Add, 2.0, 3.0), 5.0) == calc(Command::Add, calc(Command::Add, 5.0, 3.0), 2.0)); // Коммутативность умножения assert(calc(Command::Mul, 2.0, 8.0) == calc(Command::Mul, 8.0, 2.0)); // Ассоциативность умножения assert(calc(Command::Mul, calc(Command::Mul, 3.0, 4.0), 2.0) == calc(Command::Mul, calc(Command::Mul, 2.0, 4.0), 3.0)); // Дистрибутивность умножения assert(calc(Command::Mul, calc(Command::Add, 3.0, 4.0), 5.0) == calc(Command::Add, calc(Command::Mul, 3.0, 5.0), calc(Command::Mul, 4.0, 5.0))); // Операции с проверкой знаков // + + // - - // - + // + - // Сложение assert(calc(Command::Add, 3.0, 5.0) == 8.0); assert(calc(Command::Add, -3.0, -5.0) == -8.0); assert(calc(Command::Add, -3.0, 5.0) == 2.0); assert(calc(Command::Add, 3.0, -5.0) == -2.0); // Вычитание assert(calc(Command::Sub, 2.0, 1.0) == 1.0); assert(calc(Command::Sub, -2.0, -1.0) == -1.0); assert(calc(Command::Sub, 2.0, -1.0) == 3.0); assert(calc(Command::Sub, -2.0, 1.0) == -3.0); // Умножение assert(calc(Command::Mul, 5.0, 5.0) == 25.0); assert(calc(Command::Mul, -5.0, -5.0) == 25.0); assert(calc(Command::Mul, 5.0, -5.0) == -25.0); assert(calc(Command::Mul, -5.0, 5.0) == -25.0); // Деление assert(calc(Command::Div, 10.0, 5.0) == 2.0); assert(calc(Command::Div, -10.0, -5.0) == 2.0); assert(calc(Command::Div, 10.0, -5.0) == -2.0); assert(calc(Command::Div, -10.0, 5.0) == -2.0); return 0; }
30.285714
91
0.527213
TimmiJK
3129be97eea2a7d5b651ef849823a159f0d5711b
5,935
cpp
C++
SourceFile/SearchSystem.cpp
hsu0602/oop_final_project
53feacddaf7c5abb0b09c83ba9390f047b8fb5c8
[ "MIT" ]
null
null
null
SourceFile/SearchSystem.cpp
hsu0602/oop_final_project
53feacddaf7c5abb0b09c83ba9390f047b8fb5c8
[ "MIT" ]
null
null
null
SourceFile/SearchSystem.cpp
hsu0602/oop_final_project
53feacddaf7c5abb0b09c83ba9390f047b8fb5c8
[ "MIT" ]
null
null
null
#include <iostream> #include "../HeaderFile/SearchSystem.h" #include "../HeaderFile/FileConnector.h" #include "../HeaderFile/ConvertorOfTimeAndString.h" //return the goodInventory of tech input id GoodInventory SearchSystem::findInventoryById(int input_id){ FileConnector file("Inventory.csv"); file.search("id", std::to_string(input_id)); return tableToInventories(file.getResult())[0]; } GoodInventory SearchSystem::findInventoryByName(std::string input_name){ FileConnector file("Inventory.csv"); file.search("name", input_name); return tableToInventories(file.getResult())[0]; } // Find the good of input id and set the quantity to input_quantity for reciept. GoodInventory SearchSystem::findInventoryByIdAndSetQuantity(int input_id, int input_quantity){ GoodInventory tmp = findInventoryById(input_id); return GoodInventory(tmp.getId(), tmp.getCategory(), tmp.getName(), tmp.getPrice(), input_quantity); } // return all goodInvantory of the input category std::vector<GoodInventory> SearchSystem::findInventoriesByCategory(std::string input_category){ FileConnector file("Inventory.csv"); file.search("category", input_category); return tableToInventories(file.getResult()); } // use id search the quantity of that good int SearchSystem::findQuantityOfGood(int input_id){ return findInventoryById(input_id).getQuantity(); } // put the reciept to database for processing void SearchSystem::purchaseConfirm(std::vector<GoodInventory> the_reciept){ FileConnector inventory_file("Inventory.csv"); for(int i=0; i<the_reciept.size(); i++){ std::string target_id = std::to_string(the_reciept[i].getId()); inventory_file.search("id", target_id); std::vector<std::string> result = inventory_file.getResult()[0]; inventory_file.update("id", target_id, "quantity", std::to_string(stoi(result[4]) - the_reciept[i].getQuantity())); } //file.close(): FileConnector activity_file("Activity.csv"); for(GoodInventory i : the_reciept){ activity_file.append(addActivity(i, "purchase")); } //file.close(); } void SearchSystem::supplyConfirm(std::vector<GoodInventory> old_reciept, std::vector<GoodInventory> new_reciept){ std::cout << "opening Inventory.cvs" << std::endl; FileConnector inventory_file("Inventory.csv"); std::cout << "Inserting old good into Inventory..." << std::endl; for(int i=0; i<old_reciept.size(); i++){ std::string target_id = std::to_string(old_reciept[i].getId()); inventory_file.search("id", target_id); std::vector<std::string> result = inventory_file.getResult()[0]; inventory_file.update("id", target_id, "quantity", std::to_string(stoi(result[4]) + old_reciept[i].getQuantity())); } std::cout << "Appending new good into Inventory..." << std::endl; for(int i=0; i<new_reciept.size(); i++){ std::cout << "Inventory size is " << inventory_file.getResult().size() << std::endl; std::string id = std::to_string(inventory_file.getResult().size()) , category = new_reciept[i].getCategory() , name = new_reciept[i].getName() , price = std::to_string(new_reciept[i].getPrice()) , quantity = std::to_string(new_reciept[i].getQuantity()); inventory_file.append( {id, category, name, price, quantity} ); } //file.close(); std::cout << "Appending new activity..." << std::endl; FileConnector activity_file("Activity.csv"); for(GoodInventory i : old_reciept){ activity_file.append(addActivity(i, "supply")); } for(GoodInventory i : new_reciept){ activity_file.append(addActivity(i, "supply")); } //file.close(); } std::vector<std::string> SearchSystem::addActivity(GoodInventory input_good, std::string input_type){ std::vector<std::string> tmp; tmp.push_back( getTimeString() ); tmp.push_back( input_type ); tmp.push_back( input_good.getCategory() ); tmp.push_back( input_good.getName() ); tmp.push_back( std::to_string(input_good.getPrice()) ); tmp.push_back( std::to_string(input_good.getQuantity()) ); return tmp; } std::vector<Good> SearchSystem::tableToGoods(std::vector<std::vector<std::string> > input){ std::vector<Good> tmp; for(int i=0; i<input.size(); i++){ // id(int), name(string), category(string), price(int) tmp.push_back( Good(stoi(input[i][0]), input[i][1], input[i][2], stoi(input[i][3])) ); } if(tmp.size()) return tmp; else { std::cout << "empty search!" << std::endl; tmp.push_back(Good(-1, "-1", "-1", -1)); return tmp; } } std::vector<GoodInventory> SearchSystem::tableToInventories(std::vector<std::vector<std::string> > input){ std::vector<GoodInventory> tmp; for(int i=0; i<input.size(); i++){ // id(int), name(string), category(string), price(int) tmp.push_back( GoodInventory(stoi(input[i][0]), input[i][1], input[i][2], stoi(input[i][3]), stoi(input[i][4])) ); } if(tmp.size()) return tmp; else { std::cout << "empty search!" << std::endl; tmp.push_back(GoodInventory(-1, "-1", "-1", -1, -1)); return tmp; } } std::vector<GoodActivity> SearchSystem::tableToActivities(std::vector<std::vector<std::string> > input){ std::vector<GoodActivity> tmp; for(int i=0; i<input.size(); i++){ // id(int), name(string), category(string), price(int) tmp.push_back( GoodActivity(stoi(input[i][0]), input[i][1], input[i][2], stoi(input[i][3]), stoi(input[i][4]), StringToDatetime(input[i][5])) ); } if(tmp.size()) return tmp; else { std::cout << "empty search!" << std::endl; tmp.push_back(GoodActivity(-1, "-1", "-1", -1, -1, StringToDatetime(getTimeString()))); return tmp; } }
35.327381
152
0.648526
hsu0602
312a3aa1d9be22370491ec2085c1fd6baa85b9df
1,019
cpp
C++
Paladin/Templates/Sample HaikuFortune/App.cpp
humdingerb/Paladin
ef42b060656833f2887241c809690b263ddf2852
[ "MIT" ]
45
2018-10-05T21:50:17.000Z
2022-01-31T11:52:59.000Z
Paladin/Templates/Sample HaikuFortune/App.cpp
humdingerb/Paladin
ef42b060656833f2887241c809690b263ddf2852
[ "MIT" ]
163
2018-10-01T23:52:12.000Z
2022-02-15T18:05:58.000Z
Paladin/Templates/Sample HaikuFortune/App.cpp
humdingerb/Paladin
ef42b060656833f2887241c809690b263ddf2852
[ "MIT" ]
9
2018-10-01T23:48:02.000Z
2022-01-23T21:28:52.000Z
#include "App.h" #include <FindDirectory.h> #include <OS.h> #include <Path.h> #include <stdlib.h> #include "FortuneFunctions.h" #include "MainWindow.h" App::App(void) : BApplication("application/x-vnd.test-HaikuFortune") { BPath path; // We have to use an #ifdef here because the fortune files under R5 // and Zeta are in the system/etc/ directory, but in Haiku they're // kept in the system/data directory. #ifdef __HAIKU__ find_directory(B_SYSTEM_DATA_DIRECTORY,&path); #else find_directory(B_BEOS_ETC_DIRECTORY,&path); #endif path.Append("fortunes"); gFortunePath = path.Path(); // If we want the rand() function to actually be pretty close to random // we will need to seed the random number generator with the time. If we // don't, we will get the same "random" numbers each time the program is // run. srand(system_time()); MainWindow *win = new MainWindow(); win->Show(); } int main(void) { srand(system_time()); App *app = new App(); app->Run(); delete app; return 0; }
20.795918
73
0.701668
humdingerb
312b59b41269d179c28f1161a79d007df5d067aa
710
hpp
C++
external/boost_1_60_0/qsboost/config/abi_prefix.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/config/abi_prefix.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/config/abi_prefix.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
// abi_prefix header -------------------------------------------------------// // (c) Copyright John Maddock 2003 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #ifndef QSBOOST_CONFIG_ABI_PREFIX_HPP # define QSBOOST_CONFIG_ABI_PREFIX_HPP #else # error double inclusion of header qsboost/config/abi_prefix.hpp is an error #endif #include <qsboost/config.hpp> // this must occur after all other includes and before any code appears: #ifdef QSBOOST_HAS_ABI_HEADERS # include QSBOOST_ABI_PREFIX #endif #if defined( __BORLANDC__ ) #pragma nopushoptwarn #endif
27.307692
80
0.71831
wouterboomsma
312b616126ca8b4a9c023a4b2f9327f3db395ce7
1,775
cpp
C++
boj/gold/1753.cpp
pseudowasabi/Resolucion-de-problemas
47164c106d666aa07a48b8c2909a3d81f26d3dc9
[ "MIT" ]
null
null
null
boj/gold/1753.cpp
pseudowasabi/Resolucion-de-problemas
47164c106d666aa07a48b8c2909a3d81f26d3dc9
[ "MIT" ]
null
null
null
boj/gold/1753.cpp
pseudowasabi/Resolucion-de-problemas
47164c106d666aa07a48b8c2909a3d81f26d3dc9
[ "MIT" ]
1
2020-03-14T10:58:54.000Z
2020-03-14T10:58:54.000Z
// basic dijkstra algorithm #include <iostream> #include <queue> #include <cstring> #include <utility> using namespace std; int v, e; int stp; class Edge { public: Edge *next_one; int from, to, weight; bool checked; Edge() { next_one = nullptr; from = to = weight = 0; checked = false; } }; Edge *graph[20001]; typedef pair<int, int> ipair; auto cmp = [](const ipair& left, const ipair& right) { return left.second > right.second; }; priority_queue<ipair, vector<ipair>, decltype(cmp)> dijk(cmp); int cost[20001]; const int inf = 0x7fffffff; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> v >> e; cin >> stp; for(int i=1;i<=v;++i) { graph[i] = new Edge; cost[i] = inf; } for(int i=0;i<e;++i) { int u, v, w; cin >> u >> v >> w; Edge *new_edge = new Edge; new_edge->from = u; new_edge->to = v; new_edge->weight = w; new_edge->next_one = graph[u]->next_one; graph[u]->next_one = new_edge; } dijk.push({stp, 0}); while(!dijk.empty()) { ipair now = dijk.top(); dijk.pop(); if(cost[now.first] <= now.second) { // 같은 경우에도 pass continue; } cost[now.first] = now.second; // idea: 모든 edge를 다 보는 경우(=worst case) for(Edge *it=graph[now.first]->next_one;it != nullptr;it = it->next_one) { if(!(it->checked)) { dijk.push({it->to, it->weight + now.second}); it->checked = true; } } } for(int i=1;i<=v;++i) { if(cost[i] != inf) { cout << cost[i] << '\n'; } else { cout << "INF\n"; } } return 0; }
22.1875
82
0.502535
pseudowasabi
312c1a31a41e87631e38e0111c20f9c1c2f82adb
1,876
hpp
C++
cpp-learn3d/Render.hpp
robotjunkyard/cl-learn3d
040207b06117f7a6a9d5bd5f120c6209aa1157f5
[ "MIT" ]
null
null
null
cpp-learn3d/Render.hpp
robotjunkyard/cl-learn3d
040207b06117f7a6a9d5bd5f120c6209aa1157f5
[ "MIT" ]
null
null
null
cpp-learn3d/Render.hpp
robotjunkyard/cl-learn3d
040207b06117f7a6a9d5bd5f120c6209aa1157f5
[ "MIT" ]
null
null
null
#pragma once #include "Camera.hpp" #include "CanvasDef.hpp" #include "Mat.hpp" #include "Mesh.hpp" #include "Vec.hpp" class Render { public: static void drawFlat3DTriangle(Canvas& canvas, const Camera& camera, byte color, const Vec3& v1, const Vec3& v2, const Vec3& v3, const Mat& tmat, bool cullBackfaces); static void drawMeshFlat(Canvas& canvas, const Camera& camera, const Mesh& mesh); // flat-shaded debug mesh draw static void drawMeshTextured(Canvas& canvas, const Camera& camera, const Mesh& mesh); // textured mesh draw static float drawSubtriangleTextured(Canvas& canvas, float start_sx0, float start_sx1, float dsx0, // dupper, // dsx0 float dsx1, // dlong, // dsx1 int yi_start, // yi_start int yi_end, // std::min(midy, h), // yi_end const Bitmap& bitmap, const Triangle2& screenTri, const Triangle2& uvtri); static void drawMeshTriangleTextured (Canvas& canvas, const Mesh& mesh, const Triangle2& uvtri, int x1, int y1, int x2, int y2, int x3, int y3); static void drawTexturedMeshFace(Canvas& canvas, const Mesh& mesh, const Camera& camera, const Mat& tmat, unsigned short facenum, const Triangle3& faceTri, const Triangle2& uvTri, bool cullBackfaces); };
50.702703
120
0.471748
robotjunkyard
312cf02700c3c23390d3f7831f61df23645de5c8
3,303
cpp
C++
WebCore/Source/WTF/wtf/win/MemoryPressureHandlerWin.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
WebLayoutCore/Source/WTF/wtf/win/MemoryPressureHandlerWin.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
null
null
null
WebLayoutCore/Source/WTF/wtf/win/MemoryPressureHandlerWin.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2018-07-10T10:53:18.000Z
2018-07-10T10:53:18.000Z
/* * Copyright (C) 2015 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. 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 "config.h" #include "MemoryPressureHandler.h" #include <psapi.h> #include <wtf/NeverDestroyed.h> namespace WTF { void MemoryPressureHandler::platformInitialize() { m_lowMemoryHandle = CreateMemoryResourceNotification(LowMemoryResourceNotification); } void MemoryPressureHandler::windowsMeasurementTimerFired() { setUnderMemoryPressure(false); BOOL memoryLow; if (QueryMemoryResourceNotification(m_lowMemoryHandle.get(), &memoryLow) && memoryLow) { setUnderMemoryPressure(true); releaseMemory(Critical::Yes); return; } #if CPU(X86) PROCESS_MEMORY_COUNTERS_EX counters; if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&counters), sizeof(counters))) return; // On Windows, 32-bit processes have 2GB of memory available, where some is used by the system. // Debugging has shown that allocations might fail and cause crashes when memory usage is > ~1GB. // We should start releasing memory before we reach 1GB. const int maxMemoryUsageBytes = 0.9 * 1024 * 1024 * 1024; if (counters.PrivateUsage > maxMemoryUsageBytes) { setUnderMemoryPressure(true); releaseMemory(Critical::Yes); } #endif } void MemoryPressureHandler::platformReleaseMemory(Critical) { } void MemoryPressureHandler::install() { m_installed = true; m_windowsMeasurementTimer.startRepeating(60.0); } void MemoryPressureHandler::uninstall() { if (!m_installed) return; m_windowsMeasurementTimer.stop(); m_installed = false; } void MemoryPressureHandler::holdOff(unsigned seconds) { } void MemoryPressureHandler::respondToMemoryPressure(Critical critical, Synchronous synchronous) { uninstall(); releaseMemory(critical, synchronous); } std::optional<MemoryPressureHandler::ReliefLogger::MemoryUsage> MemoryPressureHandler::ReliefLogger::platformMemoryUsage() { return std::nullopt; } } // namespace WTF
31.457143
124
0.749924
gubaojian
3130dec63c6ed3ea7d09939c4155147cab0423dc
339
hpp
C++
include/kaphein/RangeException.hpp
Hydrawisk793/karbonator-cplusplus
78c39ff5a126ad3aa90da55b3d595d66ec12e002
[ "MIT" ]
1
2017-12-26T03:00:40.000Z
2017-12-26T03:00:40.000Z
include/kaphein/RangeException.hpp
Hydrawisk793/kaphein-cplusplus
78c39ff5a126ad3aa90da55b3d595d66ec12e002
[ "MIT" ]
null
null
null
include/kaphein/RangeException.hpp
Hydrawisk793/kaphein-cplusplus
78c39ff5a126ad3aa90da55b3d595d66ec12e002
[ "MIT" ]
null
null
null
#ifndef KAPHEIN_RANGEEXCEPTION_HPP #define KAPHEIN_RANGEEXCEPTION_HPP #include "pp/basic.hpp" #include "Exception.hpp" namespace kaphein { /** * @since 2014-03-23 */ class KAPHEIN_ATTRIBUTE_DLL_API RangeException : public Exception { public: virtual ~RangeException(); }; } #endif
14.73913
34
0.648968
Hydrawisk793
31311eea9a0ba1c9b6fa1cfb3556a44ce0190460
664
cpp
C++
kevald/communication/buffer_deserializer.cpp
SilverTuxedo/keval
73e2ccd5cbdf0cc7fc167711cde60be783e8dfe7
[ "MIT" ]
34
2021-09-17T16:17:58.000Z
2022-03-11T06:23:21.000Z
kevald/communication/buffer_deserializer.cpp
fengjixuchui/keval
73e2ccd5cbdf0cc7fc167711cde60be783e8dfe7
[ "MIT" ]
null
null
null
kevald/communication/buffer_deserializer.cpp
fengjixuchui/keval
73e2ccd5cbdf0cc7fc167711cde60be783e8dfe7
[ "MIT" ]
4
2021-09-17T19:39:29.000Z
2022-03-10T07:06:43.000Z
#include "buffer_deserializer.h" namespace keval::communication { BufferDeserializer::BufferDeserializer(const std::span<std::byte>& source, size_t startPosition) : m_position(source.data() + startPosition) , m_end(source.data() + source.size_bytes()) {} void BufferDeserializer::ignore(size_t count) { auto* newPosition = m_position + count; if (newPosition > m_end) { throw DeserializeException(); } m_position = newPosition; } std::byte* BufferDeserializer::getPosition() const { return m_position; } size_t BufferDeserializer::bytesLeft() const { return m_end - m_position; } } // namespace keval::communication
21.419355
96
0.713855
SilverTuxedo
3132fc26d8801af1baa8b3ae4d13f42bed8d8cbe
34,407
cpp
C++
src/Ligg.SeqExec/main.cpp
Liggin2019/Ligg.SeqExec
f4d770a6ed50aa0874b6aa410d54074cd1251fa5
[ "Apache-2.0" ]
2
2019-10-29T05:15:03.000Z
2019-11-01T18:18:02.000Z
src/Ligg.SeqExec/main.cpp
ligg2018/Ligg.SeqExec
677d4bcca3b809443b9100cfa9bdf8cb49f96777
[ "Apache-2.0" ]
null
null
null
src/Ligg.SeqExec/main.cpp
ligg2018/Ligg.SeqExec
677d4bcca3b809443b9100cfa9bdf8cb49f96777
[ "Apache-2.0" ]
1
2019-11-01T18:18:03.000Z
2019-11-01T18:18:03.000Z
// includes #include <windows.h> //for _ASSERTE #include <crtdbg.h> #include <tchar.h> #include <stdio.h> #include "lm.h" #include "CSingleInstance.hxx" // CSingleInstance implementation #include "CError.h" // CError definition #include "resource.h" // string defines #include "SetupCodes.h" // setup-related error codes #include "CSettings.h" // ini-based app globals/setting #include "main.h" #include "..\Share\Encrpt\EncryptHelper.h" #include "..\Share\CommonDefine.h" #include "..\Share\ProcessHelper.h" #include "..\Share\StringHelper.h" CSettings settings; DWORD threadNoDw = 0; HANDLE threadHandle = NULL; TCHAR windowsDir[512]; TCHAR windowsSystemDir[512]; TCHAR message[255]; HWND billBoard; int windowCount = 0; TCHAR curDlgCaption[64]; TCHAR curDlgMsg[255]; ProcessHelper processHelper; StringHelper stringHelper; // ========================================================================== // WinMain(): application entry point // ========================================================================== int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { UINT uRetCode = 0; // bootstrapper return code BOOL isFxReboot = FALSE; // reboot indicated due to fx install BOOL isAppReboot = FALSE; // reboot indicated after host app install BOOL isAppInstallSucceeded = TRUE; //##for testing /*if(ip != NULL) { MessageBox(NULL, "test11", "Test", MB_OK | MB_ICONINFORMATION); }*/ TCHAR mutexName[MAX_PATH+1]; GetModuleFileName(settings.GetHInstance(), mutexName, LENGTH(mutexName)); for(int i = 0;i < LENGTH(mutexName);++i) { if(mutexName[i]==':') { mutexName[i]='-'; } else if(mutexName[i]=='\\') { mutexName[i]='-'; } } CSingleInstance si(mutexName); // initialize hInstance in global settings settings.SetHInstance(hInstance); try { // validate single instance if we are not alone, throw an error if( !si.IsUnique() ) { CError se( 0, ERR_NOT_SINGLE_INSTANCE, MB_ICONERROR, COR_NOT_SINGLE_INSTANCE ); throw( se ); } // if there was a problem creating mutex, throw an error else if( !si.IsHandleOK() ) { CError se(0,ERR_SINGLE_INSTANCE_FAIL, MB_ICONERROR, COR_SINGLE_INSTANCE_FAIL ); //throw( se ); se.ShowMessage(); } if (!GetWindowsDirectory(windowsDir, LENGTH(windowsDir))) { HandleResult(GetLastError()); } if (!GetSystemDirectory(windowsSystemDir, LENGTH(windowsSystemDir))) { HandleResult(GetLastError()); } SetWorkingDir(); RemoveRegistryRun(); //put ourselves in install mode, if running on Terminal Server. SetTSInInstallMode(); settings.Parse(); if(_tcsicmp(settings.StartPolicy,"1") ==0) { //input password bool b=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_PASSWORDVERIFICATION), NULL, ProcDlgPasswordVerification); if(!b) { return 0; } } if(!settings.IsDefaultMode) { bool ifClickNext=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_MAIN), NULL, ProcDlgMain); if(!ifClickNext) return 0; } WCHAR domain_w[MAX_INI_DECRPTED_STR_LEN+1]; swprintf(domain_w,L"%S",settings.Domain); WCHAR id_w[MAX_INI_DECRPTED_STR_LEN+1]; swprintf(id_w,L"%S",settings.Id); WCHAR password_w[MAX_INI_DECRPTED_STR_LEN+1]; swprintf(password_w,L"%S",(settings.Password)); bool isProcessRunByAdmin=false; if(settings.IsProcessRunByAdmin) { isProcessRunByAdmin=true; } //======================================================================= //** begin to do sequencing Exec //======================================================================= int i; DWORD resultDw; int resultInt= 0; for(i = 0;i < settings.StepNo;++i) { char stepNo[3]; sprintf(stepNo,"%d",i); char step[8]; sprintf(step,"%s%s","Step-",stepNo); _sntprintf(settings.CurStepDes, LENGTH(settings.CurStepDes)-1, _T("%s"), step); _sntprintf(settings.CurMsgCaptionText, LENGTH(settings.CurMsgCaptionText)-1, _T("%s %s"), settings.CurStepDes,"Error"); if(!settings.IsQuietMode&&!settings.IsUnselected[i]) { ShowBillboard(&threadNoDw, &threadHandle); TCHAR billBdMsg[MAX_INI_BILLBOARD_MSG_STR_LEN]; if(!_tcsicmp(settings.BillboardMsg[i],_T("")) ==0) { _sntprintf(billBdMsg, LENGTH(billBdMsg)-1,"%s",settings.BillboardMsg[i]); } else { TCHAR plzWait[15]; ::LoadString(settings.GetHInstance(), MSG_PLZ_WAIT, plzWait, LENGTH(plzWait) ) ; _sntprintf(billBdMsg, LENGTH(billBdMsg)-1,"%s..., %s!",settings.StepDes[i],plzWait); } SetBillBoardText(settings.BillboardTitle,billBdMsg); } if((_tcsicmp(settings.RunType[i],_T("Run")) == 0)&&(!settings.IsUnselected[i])) { TCHAR cmdLine[MAX_PATH+MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+5+1]; _sntprintf(cmdLine, LENGTH(cmdLine)-1,"%s %s %s",settings.FilePath[i],settings.RunOption[i],settings.Args[i]); if(settings.RunByAdmin[i]) { if(isProcessRunByAdmin) { resultDw = processHelper.Run(false,cmdLine); } else { WCHAR cmdLine_w[MAX_PATH+MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+5+1]; swprintf(cmdLine_w,L"%S",cmdLine); resultDw = processHelper.RunAsUser(false,cmdLine_w,domain_w,id_w,password_w); } } else { resultDw = processHelper.Run(false,cmdLine); } } else if((_tcsicmp(settings.RunType[i],_T("ExecCmd")) == 0)&&(!settings.IsUnselected[i])) { TCHAR cmdLine[MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+1+1]; char* runOption=settings.RunOption[i]; if(_tcsicmp(settings.RunOption[i],_T("")) ==0) { sprintf(runOption,"%s","/c"); } _sntprintf(cmdLine, LENGTH(cmdLine)-1,"%s %s",runOption,settings.Args[i]); if(settings.RunByAdmin[i]) { if(isProcessRunByAdmin) { ///resultDw = ExecCmd(cmdLine); resultDw =processHelper.Run(true,cmdLine); } else { WCHAR cmdLine_w[MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+3+1]; swprintf(cmdLine_w,L"%S",cmdLine); resultDw = processHelper.RunAsUser(true,cmdLine_w,domain_w,id_w,password_w); } } else { resultDw =processHelper.Run(true,cmdLine); } } else if((_tcsicmp(settings.RunType[i],_T("RunCmd")) == 0)&&(!settings.IsUnselected[i])) { char* runOption=settings.RunOption[i]; if(_tcsicmp(settings.RunOption[i],_T("")) ==0) { sprintf(runOption,"%s","/c"); } TCHAR cmdLine[MAX_PATH+MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+3+1]; _sntprintf(cmdLine, LENGTH(cmdLine)-1,"%s %s %s",runOption,settings.AbsoluteFilePath[i],settings.Args[i]); if(settings.RunByAdmin[i]) { if(isProcessRunByAdmin) { resultDw =processHelper.Run(true,cmdLine); } else { WCHAR cmdLine_w[MAX_INI_STEP_RUN_OPTION_STR_LEN+MAX_INI_STEP_ARGS_STR_LEN+3+1]; swprintf(cmdLine_w,L"%S",cmdLine); resultDw = processHelper.RunAsUser(true,cmdLine_w,domain_w,id_w,password_w); } } else { resultDw =processHelper.Run(true,cmdLine); } } else if((_tcsicmp(settings.RunType[i],_T("GetDesEncryptCode")) == 0)&&(!settings.IsUnselected[i])) { bool b=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_ENCRPT), NULL, ProcDlgEncrpt); } else if((_tcsicmp(settings.RunType[i],_T("CheckAdmin")) == 0)&&(!settings.IsUnselected[i])) { if(!isProcessRunByAdmin) { CError se(0,ERR_INSUFFICIENT_PRIVILEGES, MB_ICONERROR, COR_SINGLE_INSTANCE_FAIL ); throw( se ); } } else if((_tcsicmp(settings.RunType[i],_T("InstallMsi")) == 0)&&(!settings.IsUnselected[i])) { TCHAR msiCmdLine[50] = _T("Msiexec.exe"); _sntprintf(msiCmdLine, LENGTH(msiCmdLine)-1,"%s %s",msiCmdLine,settings.RunOption[i]); TCHAR msiInstallCmd[MAX_PATH + LENGTH(msiCmdLine) + 2]; _sntprintf(msiInstallCmd, LENGTH(msiInstallCmd)-1,"%s\\%s %s %s",windowsSystemDir,msiCmdLine,settings.FilePath[i],settings.Args[i]); if(settings.RunByAdmin[i]) { if(isProcessRunByAdmin) { resultDw = processHelper.Run(false,msiInstallCmd); } else { WCHAR cmdLine_w[MAX_PATH + LENGTH(msiCmdLine) + 2]; swprintf(cmdLine_w,L"%S",msiInstallCmd); resultDw = processHelper.RunAsUser(false,cmdLine_w,domain_w,id_w,password_w); } } else { resultDw = processHelper.Run(false,msiInstallCmd); } if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw ||ERROR_SUCCESS == resultDw ) { isAppReboot = (resultDw == ERROR_SUCCESS_REBOOT_REQUIRED) ? true : isAppReboot; } else if ( resultDw == ERROR_INSTALL_USEREXIT) { isAppInstallSucceeded = FALSE; } else { // we display the error msg here and do not rethrow this is because we need to continue with a system reboot in the event //that fx was installed successfully before msi-install failure CError se( 0,ERR_FILE_HAS_PROBLEM, MB_ICONERROR, resultDw ); se.ShowMessage(); isAppInstallSucceeded = FALSE; } } else if((_tcsicmp(settings.RunType[i],_T("ShowNetFxDownloadUrl")) == 0)&&(!settings.IsUnselected[i])) { char * runOptionString=settings.RunOption[i]; char * runOptionStringArry[16]; int returnCount = 0; stringHelper.Split(runOptionString,"^",runOptionStringArry,&returnCount); if(returnCount==1) { runOptionStringArry[1]=new char[1]; runOptionStringArry[2]=new char[1]; sprintf(runOptionStringArry[1],"%s",""); sprintf(runOptionStringArry[2],"%s",""); } else if(returnCount==2) { runOptionStringArry[2]=new char[1]; sprintf(runOptionStringArry[2],"%s",""); } if (IfNeedToInstallNetFx(runOptionStringArry[0],runOptionStringArry[1],runOptionStringArry[2]) ==true) { _sntprintf(curDlgCaption, LENGTH(curDlgCaption)-1, _T("%s %s %s"), ".Net Framework",runOptionStringArry[0], "was needed to install to run this app! "); _sntprintf(curDlgMsg, LENGTH(curDlgMsg)-1, _T("%s"), settings.Args[i]); bool b=DialogBox(hInstance, MAKEINTRESOURCE(DIALOG_MSG), NULL, ProcDlgMsg); } /*}*/ } else if((_tcsicmp(settings.RunType[i],_T("InstallNetFx")) == 0)&&(!settings.IsUnselected[i])) { char * argsString=settings.Args[i]; char * argsStringArry[16]; int returnCount = 0; stringHelper.Split(argsString,"^",argsStringArry,&returnCount); if(returnCount==1) { argsStringArry[1]=new char[1]; argsStringArry[2]=new char[1]; sprintf(argsStringArry[1],"%s",""); sprintf(argsStringArry[2],"%s",""); } else if(returnCount==2) { argsStringArry[2]=new char[1]; sprintf(argsStringArry[2],"%s",""); } if (IfNeedToInstallNetFx(argsStringArry[0],argsStringArry[1],argsStringArry[2]) ==true) { TCHAR* fxInstallerPath=settings.AbsoluteFilePath[i]; // 2 add'l chars for zero-term and space embedded between app name & cmd-line TCHAR fxInstallCmd[MAX_PATH + LENGTH(settings.AbsoluteFilePath[i]) + LENGTH(settings.RunOption[i])+ 5]; if(strstr(settings.RunOption[i], "^") != NULL) { char * runOptionString=settings.RunOption[i]; char * runOptionStringArry[16]; int returnCount = 0; stringHelper.Split(runOptionString,"^",runOptionStringArry,&returnCount); _sntprintf(fxInstallCmd, LENGTH(fxInstallCmd)-1, _T("%s %s"), _T("/c"), runOptionStringArry[1]); } else { // build fully-qualified path to dotnetfx.exe _sntprintf(fxInstallCmd, LENGTH(fxInstallCmd)-1, _T("%s %s %s"), _T("/c"), settings.AbsoluteFilePath[i], settings.RunOption[i]); } if(isProcessRunByAdmin) { resultDw = processHelper.Run(true,fxInstallCmd); } else { WCHAR cmdLine_w[MAX_PATH + LENGTH(settings.AbsoluteFilePath[i]) + LENGTH(settings.RunOption[i])+ 2]; swprintf(cmdLine_w,L"%S",fxInstallCmd); resultDw = processHelper.RunAsUser(true,cmdLine_w,domain_w,id_w,password_w); } if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw ||ERROR_SUCCESS == resultDw ) { isFxReboot = true; } else { switch(resultDw) { case 8192: // Reboot isFxReboot = true; break; case 4096: { CError se(0, ERR_ERROR1, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4097: { CError se( 0, ERR_ERROR2, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4098: { CError se( 0, ERR_ERROR3, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4099: { CError se( 0, ERR_ERROR4, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4100: { CError se( 0, ERR_ERROR5,MB_ICONERROR,resultDw ); throw ( se ); break ; } case 4101: { CError se( 0, ERR_ERROR6, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4104: { CError se(0, ERR_ERROR7,MB_ICONERROR,resultDw ); throw ( se ); break ; } case 4111: { CError se( 0, ERR_ERROR8, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4113: { CError se(0, ERR_ERROR9, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 4114: { CError se( 0, ERR_ERROR10, MB_ICONERROR, resultDw ); throw ( se ); break ; } case 8191: { CError se( 0, ERR_ERROR5, MB_ICONERROR, resultDw ); throw ( se ); break ; } default : { break ; } } } } } //end else if settings.RunType[i]==_T("InstallNetFx") // Are we running in quiet mode? if(!settings.IsQuietMode) { TeardownBillboard(threadNoDw, threadHandle); } }//end for //now handle the reboot if (isFxReboot || isAppReboot) { CError se(MSG_REBOOT_QUERY, 0, MB_YESNO); resultInt = se.ShowMessage(); //if (resultInt == IDYES) if (resultInt == 1) { InsertRegistryRun(); InitiateReboot(); } } } catch (HRESULT) { // hresult exception msg display is handled by the originator. the exception is rethrown and caught here in order to exit. } catch( CError se ) { uRetCode = se.m_nRetCode; se.ShowMessage(); } catch( ... ) { CError se( 0, ERR_FILE_HAS_PROBLEM, MB_ICONERROR, COR_EXIT_FAILURE ); uRetCode = se.m_nRetCode; se.ShowMessage(); } return uRetCode; } BOOL Reboot(DWORD resultDw) { if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw || ERROR_SUCCESS == resultDw ) { return (resultDw == ERROR_SUCCESS_REBOOT_REQUIRED); } return false; } BOOL HandleResult(DWORD resultDw) { if ( ERROR_SUCCESS_REBOOT_REQUIRED == resultDw || ERROR_SUCCESS == resultDw ) { return true; } else { // we display the error msg here and do not rethrow // this is because we need to continue with a system // reboot in the event that fx was installed // successfully before msi-install failure CError se( 0, ERR_FILE_HAS_PROBLEM, MB_ICONERROR, resultDw ); se.ShowMessage(); return false; } return true; } // ========================================================================== // CheckNetFxVersion() // Purpose: Checks whether the provided Microsoft .Net Framework redistributable files should be installed to the local machine // ========================================================================== //old time, no use BOOL CheckNetFxVersion(LPTSTR fxInstallerPath,char* netVersion) { BOOL ifNeedToInstall = TRUE; TCHAR fxInstaller[MAX_PATH + 1]; _sntprintf(fxInstaller, LENGTH(fxInstaller)-1, _T("%s"), fxInstallerPath); try { HRESULT hr; VS_FIXEDFILEINFO vsf; //hr = settings.GetFileVersion (fxInstaller, &vsf); if (FAILED(hr)) { //throw hr; CError se( 0,ERR_VERSION_DETECT_FAILED,MB_ICONERROR,COR_EXIT_FAILURE,fxInstaller); throw( se ); } // retrieve dotnetfx.exe build # DWORD dwFileVersionLS = vsf.dwFileVersionLS >> 16; // we need a text representation TCHAR subVersion[11]; // sufficient for DWORD max + zero term _stprintf(subVersion, _T("%u"), dwFileVersionLS); // now we'll check the registry for this value LONG regQueryResult; HKEY hkey = NULL; // Append the version to the key TCHAR fxRegKey[MAX_PATH+1]; sprintf(fxRegKey, "%s%s", FX_REG_KEY, netVersion); regQueryResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, // handle to open key fxRegKey, // name of subkey to open NULL, KEY_READ, &hkey // handle to open key ); // we don't proceed unless the call above succeeds if (ERROR_FILE_NOT_FOUND == regQueryResult) { //MessageBox(NULL, "Couldn't find .Net Key", "Error", MB_OK | MB_ICONINFORMATION); return ERROR_FILE_NOT_FOUND; } if (ERROR_SUCCESS == regQueryResult) { TCHAR policyStr[256]; DWORD bufLen = LENGTH(policyStr); regQueryResult = RegQueryValueEx( hkey, subVersion, NULL, NULL, (LPBYTE)policyStr, &bufLen); if (ERROR_SUCCESS == regQueryResult) { // key found, now we need to check for the existence of the appropriate language install dir. strncat(windowsDir, _T("\\Microsoft.Net\\Framework\\"), LENGTH(windowsDir)); strncat(windowsDir, settings.GetNetVersion(), LENGTH(windowsDir)); strncat(windowsDir, _T("."), LENGTH(windowsDir)); strncat(windowsDir, subVersion, LENGTH(windowsDir)); strncat(windowsDir, _T("\\"), LENGTH(windowsDir)); strncat(windowsDir, "",//settings.GetLanguageDirectory(), LENGTH(windowsDir)); DWORD resultDw = GetFileAttributes(windowsDir); if (resultDw != INVALID_FILE_ATTRIBUTES && (resultDw & FILE_ATTRIBUTE_DIRECTORY)) { // we found our subdirectory, no need to install ifNeedToInstall = FALSE; } } // if we receive an error other than 0x2, throw else if (ERROR_FILE_NOT_FOUND != regQueryResult) { RegCloseKey(hkey); throw HRESULT_FROM_WIN32(regQueryResult); } else { MessageBox( NULL, "Could not find the .Net Version Number in the registry", "Error", MB_OK | MB_ICONINFORMATION ); } RegCloseKey(hkey); } } catch( HRESULT hr ) { CError se; se.ShowHResultMessage(ERR_VERSION_DETECT_FAILED, 0, MB_OK, hr, fxInstaller); throw hr; } return ifNeedToInstall; } BOOL IfNeedToInstallNetFx(char* fxSetupNpdKey,char* keyValueName,char* keyValue) { BOOL ifNeedToInstall =false; LONG regQueryResult; HKEY hkey = NULL; // Append the version to the key TCHAR fullFxSetupNpdKey[MAX_PATH+1]; sprintf(fullFxSetupNpdKey, "%s%s%s",FX_INSTALL_REG_KEY,"\\",fxSetupNpdKey); regQueryResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, // handle to open key fullFxSetupNpdKey, // name of subkey to open NULL, KEY_READ, &hkey // handle to open key ); if (ERROR_SUCCESS != regQueryResult) { RegCloseKey(hkey); ifNeedToInstall=true; return ifNeedToInstall; } if(_tcsicmp(keyValueName,_T("")) !=0) { DWORD dwType; //wchar_t data[MAX_PATH]; TCHAR data[MAX_PATH]; DWORD bufLen = LENGTH(data); DWORD dwSize; regQueryResult = RegQueryValueEx( hkey, keyValueName, NULL, &dwType, (LPBYTE)data, &bufLen); if(ERROR_SUCCESS != regQueryResult) { RegCloseKey(hkey); ifNeedToInstall=true; return ifNeedToInstall; } if(_tcsicmp(keyValue,_T("")) !=0) { TCHAR data1[MAX_PATH]; if(dwType==REG_EXPAND_SZ||dwType==REG_SZ||dwType==REG_MULTI_SZ) { //printf("%s/n",data); sprintf(data1, "%s",data); } else if(dwType==REG_DWORD||dwType==REG_BINARY) { sprintf(data1, "%d",(long)*(short *)data); } if(_tcsicmp(data1, keyValue)!=0) { ifNeedToInstall=true; } } } RegCloseKey(hkey); return ifNeedToInstall; } // ========================================================================== // LastError // ========================================================================== HRESULT LastError () { HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); if (SUCCEEDED(hr)) { hr = E_FAIL; } return hr; } // ========================================================================== // InitiateReboot(): initiates a system reboot // ========================================================================== BOOL InitiateReboot() { #if(_WIN32_WINNT >= 0x0500) return ExitWindowsEx( EWX_REBOOT, EWX_FORCEIFHUNG); #else return ExitWindowsEx( EWX_REBOOT, 0); #endif /* _WIN32_WINNT >= 0x0500 */ } // ========================================================================== //TerminalServices // ========================================================================== // SetTSInInstallMode(): checks if Terminal Services is enabled and if so switches machine to INSTALL mode void SetTSInInstallMode() { if (IsTerminalServicesEnabled()) { processHelper.Run(false,TS_CHANGE_USER_TO_INSTALL); } } //Detecting If Terminal Services is Installed, code is taken directly from http://msdndevstg/library/psdk/termserv/termserv_7mp0.htm BOOL IsTerminalServicesEnabled() { BOOL bResult = FALSE; DWORD dwVersion; OSVERSIONINFOEXA osVersion; DWORDLONG dwlCondition = 0; HMODULE hmodK32 = NULL; HMODULE hmodNtDll = NULL; typedef ULONGLONG (WINAPI *PFnVerSetCondition) (ULONGLONG, ULONG, UCHAR); typedef BOOL (WINAPI *PFnVerifyVersionA) (POSVERSIONINFOEXA, DWORD, DWORDLONG); PFnVerSetCondition pfnVerSetCondition; PFnVerifyVersionA pfnVerifyVersionA; dwVersion = GetVersion(); // Are we running Windows NT? if (!(dwVersion & 0x80000000)) { // Is it Windows 2000 or greater? if (LOBYTE(LOWORD(dwVersion)) > 4) { // In Windows 2000, use the VerifyVersionInfo and VerSetConditionMask functions. Don't static link because it won't load on earlier systems. hmodNtDll = GetModuleHandleA( "ntdll.dll" ); if (hmodNtDll) { pfnVerSetCondition = (PFnVerSetCondition) GetProcAddress(hmodNtDll, "VerSetConditionMask"); if (pfnVerSetCondition != NULL) { dwlCondition = (*pfnVerSetCondition) (dwlCondition,VER_SUITENAME, VER_AND); // Get a VerifyVersionInfo pointer. hmodK32 = GetModuleHandleA( "KERNEL32.DLL" ); if (hmodK32 != NULL) { pfnVerifyVersionA = (PFnVerifyVersionA) GetProcAddress(hmodK32, "VerifyVersionInfoA") ; if (pfnVerifyVersionA != NULL) { ZeroMemory(&osVersion, sizeof(osVersion)); osVersion.dwOSVersionInfoSize = sizeof(osVersion); osVersion.wSuiteMask = VER_SUITE_TERMINAL; bResult = (*pfnVerifyVersionA) (&osVersion, VER_SUITENAME, dwlCondition); } } } } } else // This is Windows NT 4.0 or earlier. bResult = ValidateProductSuite( "Terminal Server" ); } return bResult; } // ValidateProductSuite() : Terminal Services detection code for systems running Windows NT 4.0 and earlier. BOOL ValidateProductSuite (LPSTR lpszSuiteToValidate) { BOOL fValidated = FALSE; LONG lResult; HKEY hKey = NULL; DWORD dwType = 0; DWORD dwSize = 0; LPSTR lpszProductSuites = NULL; LPSTR lpszSuite; // Open the ProductOptions key. lResult = RegOpenKeyA( HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Control\\ProductOptions", &hKey ); if (lResult != ERROR_SUCCESS) goto exit; // Determine required size of ProductSuite buffer. lResult = RegQueryValueExA( hKey, "ProductSuite", NULL, &dwType,NULL, &dwSize ); if (lResult != ERROR_SUCCESS || !dwSize) goto exit; // Allocate buffer. lpszProductSuites = (LPSTR) LocalAlloc( LPTR, dwSize ); if (!lpszProductSuites) goto exit; // Retrieve array of product suite strings. lResult = RegQueryValueExA( hKey, "ProductSuite", NULL, &dwType,(LPBYTE) lpszProductSuites, &dwSize ); if (lResult != ERROR_SUCCESS || dwType != REG_MULTI_SZ) goto exit; // Search for suite name in array of strings. lpszSuite = lpszProductSuites; while (*lpszSuite) { if (lstrcmpA( lpszSuite, lpszSuiteToValidate ) == 0) { fValidated = TRUE; break; } lpszSuite += (lstrlenA( lpszSuite ) + 1); } exit: if (lpszProductSuites) LocalFree( lpszProductSuites ); if (hKey) RegCloseKey( hKey ); return fValidated; } // ========================================================================== // Billboard // ========================================================================== // BillboardProc() Purpose: Callback proc used to set HWND_TOPMOST on billboard void ShowBillboard(DWORD * pdwThreadId, HANDLE * phThread) { if (windowCount != 0) return; HANDLE threadEvent = CreateEvent( NULL, // no security attributes FALSE, // auto-reset event FALSE, // initial state is not signaled NULL); // object not named *phThread = CreateThread(NULL, 0L, StaticThreadProc, (LPVOID)&threadEvent, 0, pdwThreadId ); // Wait for any message sent or posted to this queue or for one of the passed handles be set to signaled. // This is important as the window does not get created until the StaticThreadProc gets called HANDLE handles[1]; handles[0] = threadEvent; DWORD result = WaitForMultipleObjects(1, handles, FALSE, INFINITE); } void TeardownBillboard(DWORD dwThreadId, HANDLE hThread) { if (windowCount != 1 || hThread == NULL) return; // Tell the thread to destroy the modeless dialog while (!(PostThreadMessage(dwThreadId, PWM_THREADDESTROYWND, 0, 0 ))) { Sleep(5); } WaitForSingleObject( hThread, INFINITE ); CloseHandle( hThread ); hThread = NULL; windowCount = 0; } BOOL CALLBACK BillboardProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: SetWindowPos( hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, /*SWP_NOMOVE |*/ SWP_NOSIZE ); return TRUE; } return FALSE; } // StaticThreadProc() // Purpose: Thread proc that creates our billboard dialog DWORD WINAPI StaticThreadProc( LPVOID lpParameter ) { MSG msg; HANDLE startEvent = *(HANDLE*)lpParameter; // thread's read event // Create the billboard dialog up front so we can change the text billBoard = CreateDialog(settings.GetHInstance(), MAKEINTRESOURCE(DIALOG_BILLBOARD), GetDesktopWindow(), BillboardProc); ShowWindow(billBoard, SW_SHOW); windowCount = 1; SetEvent(startEvent); // Signal event while( GetMessage( &msg, NULL, 0, 0 ) ) { if (!::IsDialogMessage( billBoard, &msg )) { if (msg.message == PWM_THREADDESTROYWND) { //Tell the dialog to destroy itself DestroyWindow(billBoard); //Tell our thread to break out of message pump PostThreadMessage( threadNoDw, WM_QUIT, 0, 0 ); } } } return( 0L ); } void SetBillBoardText(LPTSTR cap, LPTSTR msg) { SetWindowText(billBoard,cap); SetDlgItemText(billBoard, TXT_BillboardMsg, msg); } // ========================================================================== // DlgProc // ========================================================================== INT_PTR CALLBACK ProcDlgMain(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: { HWND desktop = GetDesktopWindow(); RECT screenRect, dialogRect; GetClientRect(desktop, &screenRect); GetClientRect(hwnd, &dialogRect); SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2, (screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2, dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE); SetWindowText(hwnd,settings.AppTitle); HWND control = GetDlgItem(hwnd, CKBOX_SelectAll); CheckDlgButton(hwnd, 9999, BST_CHECKED); int i=0; for(i = 0;i < settings.StepNo;++i) { control = GetDlgItem(hwnd, 9900+i); ShowWindow(control, true); if(!settings.IsUnselected[i]) { CheckDlgButton(hwnd, 9900+i, BST_CHECKED); } if(settings.IsCompulsory[i]) { CheckDlgButton(hwnd, 9900+i, BST_CHECKED); EnableWindow(control, false); } SetWindowText(control,settings.StepDes[i]); } BringWindowToTop(hwnd); } break; case WM_COMMAND: switch(LOWORD(wParam)) { case CKBOX_SelectAll: { int i=0; if (IsDlgButtonChecked(hwnd, 9999) == BST_CHECKED) { for(i = 0;i < settings.StepNo;++i) { if(!settings.IsCompulsory[i]) { CheckDlgButton(hwnd, 9900+i, BST_CHECKED); } } } else { for(i = 0;i < settings.StepNo;++i) { if(!settings.IsCompulsory[i]) { CheckDlgButton(hwnd, 9900+i, BST_UNCHECKED); } } } return TRUE; } case BTN_Next: { int i=0; for(i = 0;i < settings.StepNo;++i) { if (IsDlgButtonChecked(hwnd, 9900+i) == BST_CHECKED) { settings.IsUnselected[i]=false; } else { settings.IsUnselected[i]=TRUE; } } EndDialog(hwnd, TRUE); return TRUE; } case BTN_Cancel: EndDialog(hwnd, FALSE); return FALSE; default: return TRUE; } case WM_DESTROY: EndDialog(hwnd, FALSE); return FALSE; default: return FALSE; } return TRUE; } INT_PTR CALLBACK ProcDlgEncrpt(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: { HWND desktop = GetDesktopWindow(); RECT screenRect, dialogRect; GetClientRect(desktop, &screenRect); GetClientRect(hwnd, &dialogRect); SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2, (screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2, dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE); BringWindowToTop(hwnd); } break; case WM_COMMAND: switch(LOWORD(wParam)) { case BTN_Caculate: { HWND controlClear = GetDlgItem(hwnd, EDIT_ClearCode); HWND controlEncrp = GetDlgItem(hwnd, EDIT_EncrptCode); char txtClear[300]; char txtEncrp[300]; GetWindowText(controlClear,txtClear,300); GetWindowText(controlEncrp,txtEncrp,300); if(_tcsicmp(txtClear,"") != 0) { EncryptHelper eh; unsigned char* key= (unsigned char *)DES_KEY; char *p=eh.DesEncrypt(key,txtClear); SetWindowText(controlEncrp,p); } else{ SetWindowText(controlEncrp,""); } break; } case BTN_Cancel: EndDialog(hwnd, FALSE); break; } case WM_DESTROY: break; default: return FALSE; } return TRUE; } INT_PTR CALLBACK ProcDlgPasswordVerification(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: { HWND desktop = GetDesktopWindow(); RECT screenRect, dialogRect; GetClientRect(desktop, &screenRect); GetClientRect(hwnd, &dialogRect); SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2, (screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2, dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE); BringWindowToTop(hwnd); } break; case WM_COMMAND: switch(LOWORD(wParam)) { case BTN_Ok: { HWND control = GetDlgItem(hwnd, EDIT_Password); char a[300]; GetWindowText(control,a,300); if(_tcsicmp(a,settings.StartPassword) == 0) { EndDialog(hwnd, TRUE); } else{ } break; } case BTN_Cancel: EndDialog(hwnd, FALSE); break; } case WM_DESTROY: break; default: return FALSE; } return TRUE; } INT_PTR CALLBACK ProcDlgMsg(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: { HWND desktop = GetDesktopWindow(); RECT screenRect, dialogRect; GetClientRect(desktop, &screenRect); GetClientRect(hwnd, &dialogRect); SetWindowPos(hwnd, HWND_TOP, (screenRect.right-screenRect.left)/2 - (dialogRect.right - dialogRect.left)/2, (screenRect.bottom-screenRect.top)/2 - (dialogRect.bottom - dialogRect.top)/2, dialogRect.right - dialogRect.left, dialogRect.bottom - dialogRect.top, SWP_NOSIZE); BringWindowToTop(hwnd); SetWindowText(hwnd,curDlgCaption); SetDlgItemText(hwnd, EDIT_Msg, curDlgMsg); } break; case WM_COMMAND: switch(LOWORD(wParam)) { case BTN_Ok: EndDialog(hwnd, FALSE); break; } case WM_DESTROY: break; default: return FALSE; } return TRUE; } // ========================================================================== // Registry operation // ========================================================================== void InsertRegistryRun() { try { HKEY l_HKey; LONG l_result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, CURVER_REG_KEY, 0, KEY_WRITE, &l_HKey); if (l_result != ERROR_SUCCESS) return; TCHAR l_ExeName[2000]; GetModuleFileName(NULL,(LPTSTR)l_ExeName,LENGTH(l_ExeName)); RegSetValueEx(l_HKey, C_DOT_NET_INSTALLER,0,REG_SZ,(LPBYTE)(LPCTSTR)l_ExeName, (DWORD)(LENGTH(l_ExeName)+1) ); RegCloseKey(l_HKey); } catch(...) { _ASSERT(false); } }; void RemoveRegistryRun() { try { HKEY l_HKey; LONG l_result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, CURVER_REG_KEY, 0, KEY_WRITE, &l_HKey); if (l_result != ERROR_SUCCESS) return; RegDeleteValue(l_HKey, C_DOT_NET_INSTALLER); RegCloseKey(l_HKey); } catch(...) { _ASSERT(false); } }; // ========================================================================== // WorkingDir // ========================================================================== BOOL SetWorkingDir() { // Desc: Retrieves the directory of the application. // Pre: None. // Post: The return value is the directory of the application ending in //'\'. TCHAR app_path[2000]; GetModuleFileName(NULL,(LPTSTR)app_path,LENGTH(app_path)); LONG len = LENGTH(app_path ); while ((len > 0) && ('\\' != app_path[ len - 1 ])) --len; app_path[ len ] = '\0'; return SetCurrentDirectory((LPCTSTR)app_path); } // ========================================================================== // IsProcessRunByAdmin // ==========================================================================
25.869925
145
0.630773
Liggin2019
313b5e3b56046814191534bd5353030f4f486fff
5,146
cpp
C++
Code/Framework/AzFramework/Tests/Application.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-03-12T14:13:45.000Z
2022-03-12T14:13:45.000Z
Code/Framework/AzFramework/Tests/Application.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Code/Framework/AzFramework/Tests/Application.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "FrameworkApplicationFixture.h" #include <AzCore/IO/FileIO.h> #include <AzCore/Settings/SettingsRegistryMergeUtils.h> #include <AzCore/StringFunc/StringFunc.h> #include <AzTest/Utils.h> class ApplicationTest : public UnitTest::FrameworkApplicationFixture { protected: void SetUp() override { FrameworkApplicationFixture::SetUp(); if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { settingsRegistry->Set(AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder, m_tempDirectory.GetDirectory()); } if (auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); fileIoBase != nullptr) { fileIoBase->SetAlias("@assets@", m_tempDirectory.GetDirectory()); } } void TearDown() override { FrameworkApplicationFixture::TearDown(); } AZStd::string m_root; AZ::Test::ScopedAutoTempDirectory m_tempDirectory; }; TEST_F(ApplicationTest, MakePathAssetRootRelative_AbsPath_Valid) { AZStd::string inputPath; AZ::StringFunc::Path::ConstructFull(m_tempDirectory.GetDirectory(), "TestA.txt", inputPath, true); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_AbsPath_Valid) { AZStd::string inputPath; AZ::StringFunc::Path::ConstructFull(m_tempDirectory.GetDirectory(), "TestA.txt", inputPath, true); m_application->MakePathRelative(inputPath, m_tempDirectory.GetDirectory()); EXPECT_EQ(inputPath, "TestA.txt"); } TEST_F(ApplicationTest, MakePathAssetRootRelative_AbsPath_RootLowerCase_Valid) { AZStd::string inputPath; AZStd::string root = m_tempDirectory.GetDirectory(); AZStd::to_lower(root.begin(), root.end()); AZ::StringFunc::Path::ConstructFull(root.c_str(), "TestA.txt", inputPath, true); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_AbsPath_RootLowerCase_Valid) { AZStd::string inputPath; AZStd::string root = m_tempDirectory.GetDirectory(); AZStd::to_lower(root.begin(), root.end()); AZ::StringFunc::Path::ConstructFull(root.c_str(), "TestA.txt", inputPath, true); m_application->MakePathRelative(inputPath, root.c_str()); EXPECT_EQ(inputPath, "TestA.txt"); } TEST_F(ApplicationTest, MakePathAssetRootRelative_AbsPathWithSubFolders_Valid) { AZStd::string inputPath; AZ::StringFunc::Path::ConstructFull(m_tempDirectory.GetDirectory(), "Foo/TestA.txt", inputPath, true); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "foo/testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_AbsPathWithSubFolders_Valid) { AZStd::string inputPath; AZ::StringFunc::Path::ConstructFull(m_tempDirectory.GetDirectory(), "Foo/TestA.txt", inputPath, true); m_application->MakePathRelative(inputPath, m_tempDirectory.GetDirectory()); EXPECT_EQ(inputPath, "Foo/TestA.txt"); } TEST_F(ApplicationTest, MakePathAssetRootRelative_RelPath_Valid) { AZStd::string inputPath("TestA.txt"); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_RelPath_Valid) { AZStd::string inputPath("TestA.txt"); m_application->MakePathRelative(inputPath, m_tempDirectory.GetDirectory()); EXPECT_EQ(inputPath, "TestA.txt"); } TEST_F(ApplicationTest, MakePathAssetRootRelative_RelPathWithSubFolder_Valid) { AZStd::string inputPath("Foo/TestA.txt"); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "foo/testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_RelPathWithSubFolder_Valid) { AZStd::string inputPath("Foo/TestA.txt"); m_application->MakePathRelative(inputPath, m_tempDirectory.GetDirectory()); EXPECT_EQ(inputPath, "Foo/TestA.txt"); } TEST_F(ApplicationTest, MakePathAssetRootRelative_RelPathStartingWithSeparator_Valid) { AZStd::string inputPath("//TestA.txt"); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_RelPathStartingWithSeparator_Valid) { AZStd::string inputPath("//TestA.txt"); m_application->MakePathRelative(inputPath, m_tempDirectory.GetDirectory()); EXPECT_EQ(inputPath, "TestA.txt"); } TEST_F(ApplicationTest, MakePathAssetRootRelative_RelPathWithSubFolderStartingWithSeparator_Valid) { AZStd::string inputPath("//Foo/TestA.txt"); m_application->MakePathAssetRootRelative(inputPath); EXPECT_EQ(inputPath, "foo/testa.txt"); } TEST_F(ApplicationTest, MakePathRelative_RelPathWithSubFolderStartingWithSeparator_Valid) { AZStd::string inputPath("//Foo/TestA.txt"); m_application->MakePathRelative(inputPath, m_tempDirectory.GetDirectory()); EXPECT_EQ(inputPath, "Foo/TestA.txt"); }
34.306667
127
0.753401
cypherdotXd
313da241fb30591a9e491199f641f7687654c555
965
cpp
C++
codeforces.ru/cf277.5/c.cpp
bolatov/contests
39654ec36e1b7ff62052e324428141a9564fd576
[ "MIT" ]
null
null
null
codeforces.ru/cf277.5/c.cpp
bolatov/contests
39654ec36e1b7ff62052e324428141a9564fd576
[ "MIT" ]
null
null
null
codeforces.ru/cf277.5/c.cpp
bolatov/contests
39654ec36e1b7ff62052e324428141a9564fd576
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> using namespace std; bool can(int m, int s) { return s >= 0 && s <= 9 * m; } int main(int argc, char const *argv[]) { int m,s; cin >> m >> s; int sum = s, sum2 = s; string minn = "", maxx = ""; for (int i = 0; i < m; i++) for (int d = 0; d < 10; d++) { if ((i > 0 || d > 0 || (m == 1 && d == 0)) && can(m - i - 1, sum - d)) { minn += char('0' + d); sum -= d; break; } } for (int i = m-1; i >= 0; i--) for (int d = 9; d >= 0; d--) { if (can(i, sum2 - d)) { maxx += char('0' + d); sum2 -= d; break; } } if (minn.size() != m) { cout << "-1 -1" << endl; } else { cout << minn << " " << maxx << endl; } return 0; }
19.693878
82
0.325389
bolatov
313e42da19b38f3850df4ebbbda12e102a8dc432
420
inl
C++
third-party/cuMatExt/cuMatLogging.inl
shamanDevel/SparseSurfaceConstraints
88357ff847369a45b9f16f9f44159196138f9147
[ "MIT" ]
16
2020-03-08T18:28:27.000Z
2022-02-13T20:32:56.000Z
third-party/cuMatExt/cuMatLogging.inl
shamanDevel/SparseSurfaceConstraints
88357ff847369a45b9f16f9f44159196138f9147
[ "MIT" ]
null
null
null
third-party/cuMatExt/cuMatLogging.inl
shamanDevel/SparseSurfaceConstraints
88357ff847369a45b9f16f9f44159196138f9147
[ "MIT" ]
3
2020-03-26T01:54:31.000Z
2020-11-18T13:32:46.000Z
//This file should never be included directly, //rather, a preprocessing macro // CUMAT_LOGGING_PLUGIN="#include "cuMatLogging.inl"" //should be defined globally #include <cinder/app/AppBase.h> #define CUMAT_LOG_DEBUG(...) CINDER_LOG_I(__VA_ARGS__) #define CUMAT_LOG_INFO(...) CINDER_LOG_I(__VA_ARGS__) #define CUMAT_LOG_WARNING(...) CINDER_LOG_W(__VA_ARGS__) #define CUMAT_LOG_SEVERE(...) CINDER_LOG_E(__VA_ARGS__)
35
56
0.783333
shamanDevel
31410c8491c5c51571bb9c7f467cd97df0e9483d
240
cpp
C++
1177.cpp
fenatan/URI-Online-Judge
983cadd364e658cdebcbc2c0165e8f54e023a823
[ "MIT" ]
null
null
null
1177.cpp
fenatan/URI-Online-Judge
983cadd364e658cdebcbc2c0165e8f54e023a823
[ "MIT" ]
null
null
null
1177.cpp
fenatan/URI-Online-Judge
983cadd364e658cdebcbc2c0165e8f54e023a823
[ "MIT" ]
null
null
null
#include <stdio.h> int main(){ int t, cont; scanf("%d", &t); cont = 0; for(int i =0; i < 1000; i++){ printf("N[%d] = %d\n", i,cont); cont++; if(cont == t) cont = 0; } return 0; }
16
39
0.383333
fenatan
31456f3d1416156987e215907a737654e51918fa
765
hpp
C++
src/sandbox/ProgramArgs.hpp
maxisoft/sandboxtank
ee1f37e3bda3dc27c8dfa64630166eed8a1af08d
[ "MIT" ]
null
null
null
src/sandbox/ProgramArgs.hpp
maxisoft/sandboxtank
ee1f37e3bda3dc27c8dfa64630166eed8a1af08d
[ "MIT" ]
3
2020-08-30T09:10:53.000Z
2020-08-30T09:41:57.000Z
src/sandbox/ProgramArgs.hpp
maxisoft/sandboxtank
ee1f37e3bda3dc27c8dfa64630166eed8a1af08d
[ "MIT" ]
1
2021-09-23T00:34:13.000Z
2021-09-23T00:34:13.000Z
#pragma once #include <cassert> #include <filesystem> #include <array> #include <optional> #include <map> #include <vector> #include <tchar.h> #include <cstdio> namespace maxisoft::sandbox { struct ProgramArgs { size_t argc; std::filesystem::path program; std::filesystem::path config; std::optional<std::wstring> sessionid; std::vector<std::wstring> additional_args; std::optional<std::wstring> user; std::optional<std::wstring> password; std::optional<std::wstring> domain; std::filesystem::path working_directory; [[nodiscard]] std::wstring to_child_args(bool prepend_current_process) const; static ProgramArgs parse_args(int argc, wchar_t *argv[]); }; }
22.5
85
0.657516
maxisoft
3145cadf23c84620a0bd3646fac1549fbc8ea499
2,434
cpp
C++
PhysXEvents.cpp
elix22/Urho3DPhysX
4f0a21e76ab4aa1779e273cfe64122699e08f5bc
[ "MIT" ]
8
2019-08-21T09:23:36.000Z
2021-12-23T07:07:57.000Z
PhysXEvents.cpp
elix22/Urho3DPhysX
4f0a21e76ab4aa1779e273cfe64122699e08f5bc
[ "MIT" ]
2
2019-08-21T13:58:08.000Z
2019-08-25T11:57:29.000Z
PhysXEvents.cpp
elix22/Urho3DPhysX
4f0a21e76ab4aa1779e273cfe64122699e08f5bc
[ "MIT" ]
6
2019-08-18T20:54:15.000Z
2020-08-11T02:35:37.000Z
#include "PhysXEvents.h" #include "Physics.h" #include "PhysXScene.h" #include "RigidActor.h" #include "KinematicController.h" #include <Urho3D/IO/Log.h> Urho3DPhysX::ErrorCallback::ErrorCallback(Physics* physics) : physics_(physics) { } Urho3DPhysX::ErrorCallback::~ErrorCallback() { } void Urho3DPhysX::ErrorCallback::reportError(PxErrorCode::Enum code, const char * message, const char * file, int line) { if (physics_) physics_->SendErrorEvent(code, message, file, line); } Urho3DPhysX::SimulationEventCallback::SimulationEventCallback(PhysXScene * scene) : scene_(scene) { } Urho3DPhysX::SimulationEventCallback::~SimulationEventCallback() { } void Urho3DPhysX::SimulationEventCallback::onConstraintBreak(PxConstraintInfo * constraints, PxU32 count) { } void Urho3DPhysX::SimulationEventCallback::onWake(PxActor ** actors, PxU32 count) { } void Urho3DPhysX::SimulationEventCallback::onSleep(PxActor ** actors, PxU32 count) { } void Urho3DPhysX::SimulationEventCallback::onContact(const PxContactPairHeader & pairHeader, const PxContactPair * pairs, PxU32 nbPairs) { if (scene_) { scene_->AddCollision(pairHeader, pairs, nbPairs); } } void Urho3DPhysX::SimulationEventCallback::onTrigger(PxTriggerPair * pairs, PxU32 count) { if (scene_) { scene_->AddTriggerEvents(pairs, count); } } void Urho3DPhysX::SimulationEventCallback::onAdvance(const PxRigidBody * const * bodyBuffer, const PxTransform * poseBuffer, const PxU32 count) { } Urho3DPhysX::BroadPhaseCallback::BroadPhaseCallback(PhysXScene * scene) : scene_(scene) { } Urho3DPhysX::BroadPhaseCallback::~BroadPhaseCallback() { } void Urho3DPhysX::BroadPhaseCallback::onObjectOutOfBounds(PxShape & shape, PxActor & actor) { } void Urho3DPhysX::BroadPhaseCallback::onObjectOutOfBounds(PxAggregate & aggregate) { } Urho3DPhysX::ControllerHitCallback::ControllerHitCallback() { } Urho3DPhysX::ControllerHitCallback::~ControllerHitCallback() { } void Urho3DPhysX::ControllerHitCallback::onShapeHit(const PxControllerShapeHit& hit) { static_cast<KinematicController*>(hit.controller->getUserData())->OnShapeHit(hit); } void Urho3DPhysX::ControllerHitCallback::onControllerHit(const PxControllersHit& hit) { static_cast<KinematicController*>(hit.controller->getUserData())->OnControllerHit(hit); } void Urho3DPhysX::ControllerHitCallback::onObstacleHit(const PxControllerObstacleHit& hit) { }
23.631068
143
0.768694
elix22
31466ca33813793ae064846b15401a505b804744
1,349
hpp
C++
src/img_set.hpp
yytdfc/libtorch-mnasnet
f7f025bdcaa3f2a1654b4ad5786a91f6179bf3c5
[ "MIT" ]
1
2019-02-05T16:40:29.000Z
2019-02-05T16:40:29.000Z
src/img_set.hpp
yytdfc/libtorch-mnasnet
f7f025bdcaa3f2a1654b4ad5786a91f6179bf3c5
[ "MIT" ]
null
null
null
src/img_set.hpp
yytdfc/libtorch-mnasnet
f7f025bdcaa3f2a1654b4ad5786a91f6179bf3c5
[ "MIT" ]
null
null
null
#include <torch/data/datasets/base.h> #include <torch/data/example.h> #include <torch/types.h> class ImgSet : public Dataset<ImgSet> { public: /// The mode in which the dataset is loaded. enum class Mode { kTrain, kTest }; /// Loads the MNIST dataset from the `root` path. /// /// The supplied `root` path should contain the *content* of the unzipped /// MNIST dataset, available from http://yann.lecun.com/exdb/mnist. explicit MNIST(const std::string& root, Mode mode = Mode::kTrain) :images_(read_images(root, mode == Mode::kTrain)), targets_(read_targets(root, mode == Mode::kTrain)) {}; /// Returns the `Example` at the given `index`. Example<> get(size_t index) override{ return {images_[index], targets_[index]}; }; /// Returns the size of the dataset. optional<size_t> size() const override{ return images_.size(0); }; /// Returns true if this is the training subset of MNIST. bool is_train() const noexcept{ return images_.size(0) == kTrainSize; }; /// Returns all images stacked into a single tensor. const Tensor& images() const{ return images_; }; /// Returns all targets stacked into a single tensor. const Tensor& targets() const{ return targets_; }; private: Tensor images_, targets_; };
28.702128
77
0.644922
yytdfc
3149634d70ee92dca8decb62f5436e91c12b97c1
648
cpp
C++
Strings_Equalization.cpp
De-Fau-Lt/Solutions
2539f815ab5c77769b3e3cc00fe0e7a7ec940ad5
[ "MIT" ]
null
null
null
Strings_Equalization.cpp
De-Fau-Lt/Solutions
2539f815ab5c77769b3e3cc00fe0e7a7ec940ad5
[ "MIT" ]
null
null
null
Strings_Equalization.cpp
De-Fau-Lt/Solutions
2539f815ab5c77769b3e3cc00fe0e7a7ec940ad5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s, t; cin >> s >> t; unordered_set<char> s1; unordered_set<char> s2; for (auto x : s) s1.insert(x); for (auto x : t) s2.insert(x); int c = 0; for (auto it = s1.begin(); it != s1.end(); it++) { if (s2.count(*it) > 0) { c = 1; cout << "YES\n"; break; } } if (c == 0) cout << "NO\n"; } }
18.514286
57
0.322531
De-Fau-Lt
314c19cf96e993d4dd52f21620fe9e7c190a4614
2,249
hpp
C++
src/c4/hash.hpp
leoetlino/c4core
cfd3060287aa1d8bf0f4de7c427d2fab0f816bd1
[ "MIT" ]
3
2020-09-29T06:20:20.000Z
2021-12-20T15:20:45.000Z
src/c4/hash.hpp
leoetlino/c4core
cfd3060287aa1d8bf0f4de7c427d2fab0f816bd1
[ "MIT" ]
null
null
null
src/c4/hash.hpp
leoetlino/c4core
cfd3060287aa1d8bf0f4de7c427d2fab0f816bd1
[ "MIT" ]
2
2020-10-09T08:14:38.000Z
2020-11-22T16:48:32.000Z
#ifndef _C4_HASH_HPP_ #define _C4_HASH_HPP_ #include "c4/config.hpp" #include <climits> /** @file hash.hpp */ /** @defgroup hash Hash utils * @see http://aras-p.info/blog/2016/08/02/Hash-Functions-all-the-way-down/ */ C4_BEGIN_NAMESPACE(c4) C4_BEGIN_NAMESPACE(detail) /** @internal * @ingroup hash * @see this was taken a great answer in stackoverflow: * https://stackoverflow.com/a/34597785/5875572 * @see http://aras-p.info/blog/2016/08/02/Hash-Functions-all-the-way-down/ */ template<typename ResultT, ResultT OffsetBasis, ResultT Prime> class basic_fnv1a final { static_assert(std::is_unsigned<ResultT>::value, "need unsigned integer"); public: using result_type = ResultT; private: result_type state_ {}; public: C4_CONSTEXPR14 basic_fnv1a() noexcept : state_ {OffsetBasis} {} C4_CONSTEXPR14 void update(const void *const data, const size_t size) noexcept { auto cdata = static_cast<const unsigned char *>(data); auto acc = this->state_; for(size_t i = 0; i < size; ++i) { const auto next = size_t(cdata[i]); acc = (acc ^ next) * Prime; } this->state_ = acc; } C4_CONSTEXPR14 result_type digest() const noexcept { return this->state_; } }; using fnv1a_32 = basic_fnv1a<uint32_t, UINT32_C( 2166136261), UINT32_C( 16777619)>; using fnv1a_64 = basic_fnv1a<uint64_t, UINT64_C(14695981039346656037), UINT64_C(1099511628211)>; template<size_t Bits> struct fnv1a; template<> struct fnv1a<32> { using type = fnv1a_32; }; template<> struct fnv1a<64> { using type = fnv1a_64; }; C4_END_NAMESPACE(detail) /** @ingroup hash */ template<size_t Bits> using fnv1a_t = typename detail::fnv1a<Bits>::type; /** @ingroup hash */ C4_CONSTEXPR14 inline size_t hash_bytes(const void *const data, const size_t size) noexcept { fnv1a_t<CHAR_BIT * sizeof(size_t)> fn{}; fn.update(data, size); return fn.digest(); } /** * @overload hash_bytes * @ingroup hash */ template<size_t N> C4_CONSTEXPR14 inline size_t hash_bytes(const char (&str)[N]) noexcept { fnv1a_t<CHAR_BIT * sizeof(size_t)> fn{}; fn.update(str, N); return fn.digest(); } C4_END_NAMESPACE(c4) #endif // _C4_HASH_HPP_
23.427083
96
0.678968
leoetlino
314c654635e645dde3a91ba4ad5a0d5d348d2b75
5,253
cpp
C++
source/geometry/GeometryPooling3D.cpp
WillTao-RD/MNN
48575121859093bab8468d6992596962063b7aff
[ "Apache-2.0" ]
2
2020-12-15T13:56:31.000Z
2022-01-26T03:20:28.000Z
source/geometry/GeometryPooling3D.cpp
qaz734913414/MNN
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
[ "Apache-2.0" ]
null
null
null
source/geometry/GeometryPooling3D.cpp
qaz734913414/MNN
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
[ "Apache-2.0" ]
1
2021-11-24T06:26:27.000Z
2021-11-24T06:26:27.000Z
// // GeometryPooling3D.cpp // MNN // // Created by MNN on 2020/7/28. // Copyright © 2018, Alibaba Group Holding Limited // #include "ConvertUtils.hpp" #include "geometry/GeometryComputer.hpp" #include "core/OpCommonUtils.hpp" #include "geometry/GeometryComputerUtils.hpp" namespace MNN { class GeometryPooling3D : public GeometryComputer { public: virtual bool onCompute(const Op* op, const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, Context& context, CommandBuffer& res) const override { MNN_ASSERT(1 == inputs.size()); MNN_ASSERT(1 == outputs.size()); auto input = inputs[0]; auto output = outputs[0]; MNN_ASSERT(input->dimensions() == 5); auto kernelSize = op->main_as_Pool3D()->kernels(); auto strideSize = op->main_as_Pool3D()->strides(); auto padSize = op->main_as_Pool3D()->pads(); auto poolType = op->main_as_Pool3D()->type(); auto padType = op->main_as_Pool3D()->padType(); const int kernelDepth = kernelSize->Get(0), kernelHeight = kernelSize->Get(1), kernelWidth = kernelSize->Get(2); const int strideDepth = strideSize->Get(0), strideHeight = strideSize->Get(1), strideWidth = strideSize->Get(2); const int padDepth = padSize->Get(0), padHeight = padSize->Get(1), padWidth = padSize->Get(2); const int outputDepth = output->length(2), outputHeight = output->length(3), outputWidth = output->length(4); const int inputDepth = input->length(2), inputHeight = input->length(3), inputWidth = input->length(4); const int channel = input->length(1), batch = input->length(0); std::shared_ptr<Tensor> reshapeInput; { reshapeInput.reset(Tensor::createDevice<float>({batch*inputDepth, channel, inputHeight, inputWidth})); auto outputDes = TensorUtils::getDescribe(reshapeInput.get()); outputDes->regions.clear(); outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4; outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL; auto totalSlice = TensorUtils::makeFullSlice(input); outputDes->regions.emplace_back(std::move(totalSlice)); res.extras.emplace_back(reshapeInput); } std::shared_ptr<Tensor> pool2dTmp1; { pool2dTmp1.reset(Tensor::createDevice<float>({batch*inputDepth, channel, outputHeight, outputWidth})); auto outputDes = TensorUtils::getDescribe(pool2dTmp1.get()); outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4; flatbuffers::FlatBufferBuilder builder; builder.Finish(GeometryComputerUtils::makePool(builder, std::make_pair(kernelWidth, kernelHeight), std::make_pair(strideWidth, strideHeight), poolType, padType, std::make_pair(padWidth, padHeight), false)); auto cmd = GeometryComputerUtils::makeCommand(builder, {reshapeInput.get()}, {pool2dTmp1.get()}); res.extras.emplace_back(pool2dTmp1); res.command.emplace_back(std::move(cmd)); } std::shared_ptr<Tensor> reshapeTmp1; { reshapeTmp1.reset(Tensor::createDevice<float>({batch, channel, inputDepth, outputHeight*outputWidth})); auto outputDes = TensorUtils::getDescribe(reshapeTmp1.get()); outputDes->regions.clear(); outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4; outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL; auto totalSlice = TensorUtils::makeFullSlice(pool2dTmp1.get()); outputDes->regions.emplace_back(std::move(totalSlice)); res.extras.emplace_back(reshapeTmp1); } std::shared_ptr<Tensor> pool2dTmp2; { pool2dTmp2.reset(Tensor::createDevice<float>({batch, channel, outputDepth, outputHeight*outputWidth})); TensorUtils::getDescribe(pool2dTmp2.get())->dimensionFormat = MNN_DATA_FORMAT_NC4HW4; auto countType = AvgPoolCountType_DEFAULT; if (poolType == PoolType_AVEPOOL) { countType = AvgPoolCountType_EXCLUDE_PADDING; } flatbuffers::FlatBufferBuilder builder; builder.Finish(GeometryComputerUtils::makePool(builder, std::make_pair(1, kernelDepth), std::make_pair(1, strideDepth), poolType, padType, std::make_pair(0, padDepth), false, countType)); auto cmd = GeometryComputerUtils::makeCommand(builder, {reshapeTmp1.get()}, {pool2dTmp2.get()}); res.extras.emplace_back(pool2dTmp2); res.command.emplace_back(std::move(cmd)); } { auto outputDes = TensorUtils::getDescribe(output); outputDes->dimensionFormat = MNN_DATA_FORMAT_NC4HW4; outputDes->memoryType = Tensor::InsideDescribe::MEMORY_VIRTUAL; auto totalSlice = TensorUtils::makeFullSlice(pool2dTmp2.get()); outputDes->regions.emplace_back(std::move(totalSlice)); } return true; } }; static void _create() { std::shared_ptr<GeometryComputer> comp(new GeometryPooling3D); GeometryComputer::registerGeometryComputer(comp, {OpType_Pooling3D}); } REGISTER_GEOMETRY(GeometryPooling3D, _create); } // namespace MNN
52.009901
218
0.665905
WillTao-RD
315125966bd503336d33f24b102415ee0c389169
3,355
cpp
C++
AutoCompleteComboBox.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
1
2020-07-19T10:19:18.000Z
2020-07-19T10:19:18.000Z
AutoCompleteComboBox.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
AutoCompleteComboBox.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
// ComboBoxEx.cpp : implementation file // // Autocompleting combo-box (like the URL edit box in netscape) // // Written by Chris Maunder (Chris.Maunder@cbr.clw.csiro.au) // Copyright (c) 1998. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name is included. If // the source code in this file is used in any commercial application // then acknowledgement must be made to the author of this file // (in whatever form you wish). // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability if it causes any damage to your // computer, causes your pet cat to fall ill, increases baldness or // makes you car start emitting strange noises when you start it up. // // Expect bugs. // // Please use and enjoy. Please let me know of any bugs/mods/improvements // that you have found/implemented and I will fix/incorporate them into this // file. // // Modified: 12 Sep 1998 Setting correct cursor position after // auto-complete: Petr Stejskal and Ryan Schneider // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "AutoCompleteComboBox.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CComboBoxEx CAutoCompleteComboBox::CAutoCompleteComboBox() { m_bAutoComplete = TRUE; } CAutoCompleteComboBox::~CAutoCompleteComboBox() { } BEGIN_MESSAGE_MAP(CAutoCompleteComboBox, CComboBox) //{{AFX_MSG_MAP(CComboBoxEx) ON_CONTROL_REFLECT(CBN_EDITUPDATE, OnEditUpdate) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CComboBoxEx message handlers BOOL CAutoCompleteComboBox::PreTranslateMessage(MSG* pMsg) { // Need to check for backspace/delete. These will modify the text in // the edit box, causing the auto complete to just add back the text // the user has just tried to delete. if (pMsg->message == WM_KEYDOWN) { m_bAutoComplete = TRUE; int nVirtKey = (int) pMsg->wParam; if (nVirtKey == VK_DELETE || nVirtKey == VK_BACK) m_bAutoComplete = FALSE; } return CComboBox::PreTranslateMessage(pMsg); } void CAutoCompleteComboBox::OnEditUpdate() { // if we are not to auto update the text, get outta here if (!m_bAutoComplete) return; // Get the text in the edit box CString str; GetWindowText(str); int nLength = str.GetLength(); // Currently selected range DWORD dwCurSel = GetEditSel(); WORD dStart = LOWORD(dwCurSel); WORD dEnd = HIWORD(dwCurSel); // Search for, and select in, and string in the combo box that is prefixed // by the text in the edit box if (SelectString(-1, str) == CB_ERR) { SetWindowText(str); // No text selected, so restore what was there before if (dwCurSel != CB_ERR) SetEditSel(dStart, dEnd); //restore cursor postion } // Set the text selection as the additional text that we have added if (dEnd < nLength && dwCurSel != CB_ERR) SetEditSel(dStart, dEnd); else SetEditSel(nLength, -1); }
29.955357
80
0.668554
joeriedel
3153e009a72700cb3dd8943ee0734bddeb83e78c
2,897
hxx
C++
src/dbl/service/server/service_connection.hxx
mcptr/dbl-service
9af5aee06be0a4b909782b251bf6078513399d33
[ "MIT" ]
null
null
null
src/dbl/service/server/service_connection.hxx
mcptr/dbl-service
9af5aee06be0a4b909782b251bf6078513399d33
[ "MIT" ]
null
null
null
src/dbl/service/server/service_connection.hxx
mcptr/dbl-service
9af5aee06be0a4b909782b251bf6078513399d33
[ "MIT" ]
1
2018-10-09T06:30:03.000Z
2018-10-09T06:30:03.000Z
#ifndef DBL_SERVICE_SERVER_SERVICE_CONNECTION_HXX #define DBL_SERVICE_SERVER_SERVICE_CONNECTION_HXX #include "connection.hxx" #include "dbl/auth/auth.hxx" #include "dbl/types/types.hxx" #include <memory> namespace dbl { namespace service { namespace server { class ServiceOperationError : public std::runtime_error { public: ServiceOperationError() = default; explicit ServiceOperationError(const std::string& msg) : std::runtime_error(msg) { } explicit ServiceOperationError( const std::string& msg, const types::Errors_t& errors) : std::runtime_error(msg), errors_(errors) { } ~ServiceOperationError() = default; virtual inline const types::Errors_t& get_errors() const { return errors_; } protected: const types::Errors_t errors_; }; class ServiceConnection : public Connection { public: ServiceConnection() = delete; ServiceConnection(std::shared_ptr<core::Api> api, boost::asio::ip::tcp::socket socket); virtual ~ServiceConnection() = default; protected: auth::Auth auth_; bool is_authenticated_ = false; virtual void process_request(const std::string& request, std::string& response); void dispatch(const std::string& cmd, const Json::Value& data, Json::Value& value); // op handlers void handle_status( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_flush_dns( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_block( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_unblock( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_set_service_password( const Json::Value& data, Json::Value& response, types::Errors_t& errors); void handle_remove_service_password( const Json::Value& data, Json::Value& response, types::Errors_t& errors); void handle_import_domain_list( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_get_domain_lists( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_get_domain_list( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_delete_domain_list( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_get_version( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_get_domain( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_get_domains( const Json::Value& data, Json::Value& response, types::Errors_t& errors) const; void handle_reload( const Json::Value& data, Json::Value& response, types::Errors_t& errors); }; } // server } // service } // dbl #endif
20.692857
57
0.722126
mcptr
3157f68bbb610485664b1c94a911623fb91d84c2
487
cpp
C++
WeatherViewer/main.cpp
ajstacher/CST276SRS01
bea416c7479cc590ff09d48dbe695ba1b07edb03
[ "MIT" ]
null
null
null
WeatherViewer/main.cpp
ajstacher/CST276SRS01
bea416c7479cc590ff09d48dbe695ba1b07edb03
[ "MIT" ]
null
null
null
WeatherViewer/main.cpp
ajstacher/CST276SRS01
bea416c7479cc590ff09d48dbe695ba1b07edb03
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "station.h" #include "current.h" #include "statistics.h" int main() { //for rand() in station srand(time(NULL)); //create WeatherStation::Station weather_station; //attached upon construction WeatherViewer::Current current_weather(weather_station); WeatherViewer::Statistics statistics(weather_station); //get data and notify observers for(auto i = 0; i < 3; i++) { weather_station.measure(); weather_station.notify(); } return 0; }
18.037037
57
0.716632
ajstacher
315cf13b69139c74025cb55f352c9a780dddeac3
3,955
cc
C++
components/ntp_snippets/remote/remote_suggestions_status_service.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
components/ntp_snippets/remote/remote_suggestions_status_service.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
components/ntp_snippets/remote/remote_suggestions_status_service.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 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/ntp_snippets/remote/remote_suggestions_status_service.h" #include <string> #include "components/ntp_snippets/features.h" #include "components/ntp_snippets/pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_manager.h" #include "components/variations/variations_associated_data.h" namespace ntp_snippets { namespace { const char kFetchingRequiresSignin[] = "fetching_requires_signin"; const char kFetchingRequiresSigninEnabled[] = "true"; const char kFetchingRequiresSigninDisabled[] = "false"; } // namespace RemoteSuggestionsStatusService::RemoteSuggestionsStatusService( SigninManagerBase* signin_manager, PrefService* pref_service) : status_(RemoteSuggestionsStatus::EXPLICITLY_DISABLED), require_signin_(false), signin_manager_(signin_manager), pref_service_(pref_service) { std::string param_value_str = variations::GetVariationParamValueByFeature( kArticleSuggestionsFeature, kFetchingRequiresSignin); if (param_value_str == kFetchingRequiresSigninEnabled) { require_signin_ = true; } else if (!param_value_str.empty() && param_value_str != kFetchingRequiresSigninDisabled) { DLOG(WARNING) << "Unknow value for the variations parameter " << kFetchingRequiresSignin << ": " << param_value_str; } } RemoteSuggestionsStatusService::~RemoteSuggestionsStatusService() = default; // static void RemoteSuggestionsStatusService::RegisterProfilePrefs( PrefRegistrySimple* registry) { registry->RegisterBooleanPref(prefs::kEnableSnippets, true); } void RemoteSuggestionsStatusService::Init( const StatusChangeCallback& callback) { DCHECK(status_change_callback_.is_null()); status_change_callback_ = callback; // Notify about the current state before registering the observer, to make // sure we don't get a double notification due to an undefined start state. RemoteSuggestionsStatus old_status = status_; status_ = GetStatusFromDeps(); status_change_callback_.Run(old_status, status_); pref_change_registrar_.Init(pref_service_); pref_change_registrar_.Add( prefs::kEnableSnippets, base::Bind(&RemoteSuggestionsStatusService::OnSnippetsEnabledChanged, base::Unretained(this))); } void RemoteSuggestionsStatusService::OnSnippetsEnabledChanged() { OnStateChanged(GetStatusFromDeps()); } void RemoteSuggestionsStatusService::OnStateChanged( RemoteSuggestionsStatus new_status) { if (new_status == status_) { return; } status_change_callback_.Run(status_, new_status); status_ = new_status; } bool RemoteSuggestionsStatusService::IsSignedIn() const { // TODO(dgn): remove the SigninManager dependency. It should be possible to // replace it by passing the new state via OnSignInStateChanged(). return signin_manager_ && signin_manager_->IsAuthenticated(); } void RemoteSuggestionsStatusService::OnSignInStateChanged() { OnStateChanged(GetStatusFromDeps()); } RemoteSuggestionsStatus RemoteSuggestionsStatusService::GetStatusFromDeps() const { if (!pref_service_->GetBoolean(prefs::kEnableSnippets)) { DVLOG(1) << "[GetStatusFromDeps] Disabled via pref"; return RemoteSuggestionsStatus::EXPLICITLY_DISABLED; } if (require_signin_ && !IsSignedIn()) { DVLOG(1) << "[GetStatusFromDeps] Signed out and disabled due to this."; return RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED; } DVLOG(1) << "[GetStatusFromDeps] Enabled, signed " << (IsSignedIn() ? "in" : "out"); return IsSignedIn() ? RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN : RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT; } } // namespace ntp_snippets
34.692982
77
0.763338
google-ar
316002e48643abdc8582e51b55bed3dc64dc6876
16,859
cpp
C++
opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
opengl/src/Rendering/ImageEffects/DepthOfFieldImageEffect.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DepthOfFieldImageEffect.hpp" #include "Rendering/OpenGLUtils.hpp" #include <Rendering/FrameBufferObject.hpp> #include <Rendering/RenderTarget.hpp> #include <Rendering/RenderPasses/RenderPass.hpp> #include <SceneGraph/Camera.hpp> using namespace crimild; using namespace crimild::opengl; const char *dof_generic_vs = R"( CRIMILD_GLSL_ATTRIBUTE( 0 ) vec3 aPosition; CRIMILD_GLSL_ATTRIBUTE( 4 ) vec2 aTextureCoord; CRIMILD_GLSL_VARYING_OUT vec2 vTextureCoord; void main() { vTextureCoord = aTextureCoord; CRIMILD_GLSL_VERTEX_OUTPUT = vec4( aPosition, 1.0 ); } )"; const char *dof_generic_fs = R"( CRIMILD_GLSL_PRECISION_FLOAT_HIGH CRIMILD_GLSL_VARYING_IN vec2 vTextureCoord; uniform sampler2D uColorMap; CRIMILD_GLSL_DECLARE_FRAGMENT_OUTPUT void main( void ) { CRIMILD_GLSL_FRAGMENT_OUTPUT = CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vTextureCoord ); } )"; const char *dof_blur_fs = R"( CRIMILD_GLSL_PRECISION_FLOAT_HIGH CRIMILD_GLSL_VARYING_IN vec2 vTextureCoord; CRIMILD_GLSL_DECLARE_FRAGMENT_OUTPUT uniform vec2 uTexelSize; uniform sampler2D uColorMap; uniform sampler2D uDepthMap; uniform int uOrientation; uniform float uBlurCoefficient; uniform float uFocusDistance; uniform float uNear; uniform float uFar; uniform float uPPM; float linearDepth( float z ) { z = 2.0 * z - 1.0; return ( 2.0 * uNear * uFar ) / ( uFar + uNear - z * ( uFar - uNear ) ); } // Calculate the blur diameter to apply on the image. float GetBlurDiameter( float d ) { float Dd = d; float xd = abs( Dd - uFocusDistance ); float xdd = ( Dd < uFocusDistance ) ? ( uFocusDistance - xd ) : ( uFocusDistance + xd ); float b = uBlurCoefficient * ( xd / xdd ); return b * uPPM; } void main () { const float MAX_BLUR_RADIUS = 10.0; float depth = linearDepth( CRIMILD_GLSL_FN_TEXTURE_2D( uDepthMap, vTextureCoord ).x ); float blurAmount = GetBlurDiameter( depth ); blurAmount = min( floor( blurAmount ), MAX_BLUR_RADIUS ); float count = 0.0; vec4 colour = vec4( 0.0 ); vec2 texelOffset; if ( uOrientation == 0 ) { texelOffset = vec2( uTexelSize.x, 0.0); } else { texelOffset = vec2(0.0, uTexelSize.y); } if ( blurAmount >= 1.0 ) { float halfBlur = blurAmount * 0.5; for ( float i = 0.0; i < MAX_BLUR_RADIUS; ++i ) { if ( i >= blurAmount ) { break; } float offset = i - halfBlur; vec2 vOffset = vTextureCoord + ( texelOffset * offset ); colour += CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vOffset ); ++count; } } if ( count > 0.0 ) { CRIMILD_GLSL_FRAGMENT_OUTPUT = colour / count; } else { CRIMILD_GLSL_FRAGMENT_OUTPUT = CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vTextureCoord ); } } )"; const char *dof_composite_fs = R"( CRIMILD_GLSL_PRECISION_FLOAT_HIGH CRIMILD_GLSL_VARYING_IN vec2 vTextureCoord; CRIMILD_GLSL_DECLARE_FRAGMENT_OUTPUT uniform sampler2D uColorMap; uniform sampler2D uDepthMap; uniform sampler2D uBlurMap; uniform float uBlurCoefficient; uniform float uFocusDistance; uniform float uNear; uniform float uFar; uniform float uPPM; float linearDepth( float z ) { z = 2.0 * z - 1.0; return ( 2.0 * uNear * uFar ) / ( uFar + uNear - z * ( uFar - uNear ) ); } // Calculate the blur diameter to apply on the image. float GetBlurDiameter (float d) { float Dd = d; float xd = abs( Dd - uFocusDistance ); float xdd = (Dd < uFocusDistance) ? (uFocusDistance - xd) : (uFocusDistance + xd); float b = uBlurCoefficient * (xd / xdd); return b * uPPM; } void main () { const float MAX_BLUR_RADIUS = 10.0; vec4 colour = CRIMILD_GLSL_FN_TEXTURE_2D( uColorMap, vTextureCoord ); float depth = linearDepth( CRIMILD_GLSL_FN_TEXTURE_2D( uDepthMap, vTextureCoord ).x ); vec4 blur = CRIMILD_GLSL_FN_TEXTURE_2D( uBlurMap, vTextureCoord ); float blurAmount = GetBlurDiameter( depth ); float lerp = min( blurAmount / MAX_BLUR_RADIUS, 1.0 ); CRIMILD_GLSL_FRAGMENT_OUTPUT = ( colour * ( 1.0 - lerp ) ) + ( blur * lerp ); } )"; DepthOfFieldImageEffect::DoFBlurShaderProgram::DoFBlurShaderProgram( void ) : ShaderProgram( OpenGLUtils::getVertexShaderInstance( dof_generic_vs ), OpenGLUtils::getFragmentShaderInstance( dof_blur_fs ) ) { registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::POSITION_ATTRIBUTE, "aPosition" ); registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::TEXTURE_COORD_ATTRIBUTE, "aTextureCoord" ); registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM, "uColorMap" ); registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM, "uDepthMap" ); _uOrientation = crimild::alloc< IntUniform >( "uOrientation", 0 ); _uTexelSize = crimild::alloc< Vector2fUniform >( "uTexelSize", Vector2f::ZERO ); _uBlurCoefficient = crimild::alloc< FloatUniform >( "uBlurCoefficient", 0.0f ); _uFocusDistance = crimild::alloc< FloatUniform >( "uFocusDistance", 0.0f ); _uPPM = crimild::alloc< FloatUniform >( "uPPM", 0.0f ); _uNear = crimild::alloc< FloatUniform >( "uNear", 0.0f ); _uFar = crimild::alloc< FloatUniform >( "uFar", 0.0f ); attachUniform( _uTexelSize ); attachUniform( _uOrientation ); attachUniform( _uBlurCoefficient ); attachUniform( _uFocusDistance ); attachUniform( _uNear ); attachUniform( _uFar ); attachUniform( _uPPM ); } DepthOfFieldImageEffect::DoFBlurShaderProgram::~DoFBlurShaderProgram( void ) { } DepthOfFieldImageEffect::DoFCompositeShaderProgram::DoFCompositeShaderProgram( void ) : ShaderProgram( OpenGLUtils::getVertexShaderInstance( dof_generic_vs ), OpenGLUtils::getFragmentShaderInstance( dof_composite_fs ) ) { registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::POSITION_ATTRIBUTE, "aPosition" ); registerStandardLocation( ShaderLocation::Type::ATTRIBUTE, ShaderProgram::StandardLocation::TEXTURE_COORD_ATTRIBUTE, "aTextureCoord" ); registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM, "uColorMap" ); registerStandardLocation( ShaderLocation::Type::UNIFORM, ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM, "uDepthMap" ); registerLocation( crimild::alloc< ShaderLocation >( ShaderLocation::Type::UNIFORM, "uBlurMap" ) ); _uBlurCoefficient = crimild::alloc< FloatUniform >( "uBlurCoefficient", 0.0f ); _uFocusDistance = crimild::alloc< FloatUniform >( "uFocusDistance", 0.0f ); _uPPM = crimild::alloc< FloatUniform >( "uPPM", 0.0f ); _uNear = crimild::alloc< FloatUniform >( "uNear", 0.0f ); _uFar = crimild::alloc< FloatUniform >( "uFar", 0.0f ); attachUniform( _uBlurCoefficient ); attachUniform( _uFocusDistance ); attachUniform( _uNear ); attachUniform( _uFar ); attachUniform( _uPPM ); } DepthOfFieldImageEffect::DoFCompositeShaderProgram::~DoFCompositeShaderProgram( void ) { } DepthOfFieldImageEffect::DepthOfFieldImageEffect( void ) : DepthOfFieldImageEffect( 1024 ) { } DepthOfFieldImageEffect::DepthOfFieldImageEffect( int resolution ) : _resolution( resolution ), _focalDistance( crimild::alloc< FloatUniform >( "uFocalDistance", 50.0f ) ), _focusDistance( crimild::alloc< FloatUniform >( "uFocusDistance", 10000.0f ) ), _fStop( crimild::alloc< FloatUniform >( "uFStop", 2.8f ) ), _aperture( crimild::alloc< FloatUniform >( "uAperture", 35.0f ) ) { _auxFBOs.push_back( crimild::alloc< StandardFrameBufferObject >( resolution, resolution ) ); _auxFBOs.push_back( crimild::alloc< StandardFrameBufferObject >( resolution, resolution ) ); _dofBlurProgram = crimild::alloc< DoFBlurShaderProgram >(); _dofCompositeProgram = crimild::alloc< DoFCompositeShaderProgram >(); } DepthOfFieldImageEffect::~DepthOfFieldImageEffect( void ) { } void DepthOfFieldImageEffect::compute( Renderer *renderer, Camera *camera ) { auto sceneFBO = renderer->getFrameBuffer( RenderPass::S_BUFFER_NAME ); if ( sceneFBO == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named '", RenderPass::S_BUFFER_NAME, "'" ); return; } auto colorTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_COLOR_TARGET_NAME ]; if ( colorTarget == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot get color target from scene" ); return; } auto depthTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_DEPTH_TARGET_NAME ]; if ( depthTarget->getTexture() == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Depth texture is null" ); return; } auto blurFBO = renderer->getFrameBuffer( Renderer::FBO_AUX_1024 ); if ( blurFBO == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named '", Renderer::FBO_AUX_1024, "'" ); return; } float f = getFocalDistance(); float Ds = getFocusDistance(); float ms = f / ( Ds - f ); float N = getFStop(); float PPM = Numericf::sqrt( ( getResolution() * getResolution() ) + ( getResolution() * getResolution() ) ) / getAperture(); float b = f * ms / N; auto fboA = getAuxFBO( 0 ); auto fboB = getAuxFBO( 1 ); getBlurProgram()->setTexelSize( Vector2f( 1.0f / ( float ) getResolution(), 1.0f / ( float ) getResolution() ) ); getBlurProgram()->setBlurCoefficient( b ); getBlurProgram()->setFocusDistance( Ds ); getBlurProgram()->setPPM( PPM ); getBlurProgram()->setNear( 1000.0f * camera->getFrustum().getDMin() ); getBlurProgram()->setFar( 1000.0f * camera->getFrustum().getDMax() ); getBlurProgram()->setOrientation( 0 ); renderer->bindFrameBuffer( fboA ); renderer->bindProgram( getBlurProgram() ); renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() ); renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() ); renderer->drawScreenPrimitive( getBlurProgram() ); renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() ); renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() ); renderer->unbindProgram( getBlurProgram() ); renderer->unbindFrameBuffer( fboA ); auto aColorTarget = fboA->getRenderTargets()[ RenderTarget::RENDER_TARGET_NAME_COLOR ]; if ( aColorTarget == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot get color target from scene" ); return; } getBlurProgram()->setOrientation( 0 ); renderer->bindFrameBuffer( fboB ); renderer->bindProgram( getBlurProgram() ); renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), aColorTarget->getTexture() ); renderer->bindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() ); renderer->drawScreenPrimitive( getBlurProgram() ); renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), aColorTarget->getTexture() ); renderer->unbindTexture( getBlurProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() ); renderer->unbindProgram( getBlurProgram() ); renderer->unbindFrameBuffer( fboB ); } void DepthOfFieldImageEffect::apply( crimild::Renderer *renderer, crimild::Camera *camera ) { auto sceneFBO = renderer->getFrameBuffer( RenderPass::S_BUFFER_NAME ); if ( sceneFBO == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named '", RenderPass::S_BUFFER_NAME, "'" ); return; } auto colorTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_COLOR_TARGET_NAME ]; if ( colorTarget->getTexture() == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Color texture is null" ); return; } auto depthTarget = sceneFBO->getRenderTargets()[ RenderPass::S_BUFFER_DEPTH_TARGET_NAME ]; if ( depthTarget->getTexture() == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Depth texture is null" ); return; } auto blurFBO = getAuxFBO( 1 ); if ( blurFBO == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot find FBO named 'dof/fbo/fboB'" ); return; } auto blurTarget = blurFBO->getRenderTargets()[ RenderTarget::RENDER_TARGET_NAME_COLOR ]; if ( blurTarget->getTexture() == nullptr || blurTarget->getTexture()->getCatalog() == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Blur texture is null" ); return; } float f = getFocalDistance(); float Ds = getFocusDistance(); float ms = f / ( Ds - f ); float N = getFStop(); float PPM = Numericf::sqrt( ( getResolution() * getResolution() ) + ( getResolution() * getResolution() ) ) / getAperture(); float b = f * ms / N; getCompositeProgram()->setBlurCoefficient( b ); getCompositeProgram()->setFocusDistance( Ds ); getCompositeProgram()->setPPM( PPM ); getCompositeProgram()->setNear( 1000.0f * camera->getFrustum().getDMin() ); getCompositeProgram()->setFar( 1000.0f * camera->getFrustum().getDMax() ); renderer->bindProgram( getCompositeProgram() ); renderer->bindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() ); renderer->bindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() ); renderer->bindTexture( getCompositeProgram()->getLocation( "uBlurMap" ), blurTarget->getTexture() ); renderer->drawScreenPrimitive( getCompositeProgram() ); renderer->unbindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::COLOR_MAP_UNIFORM ), colorTarget->getTexture() ); renderer->unbindTexture( getCompositeProgram()->getStandardLocation( ShaderProgram::StandardLocation::DEPTH_MAP_UNIFORM ), depthTarget->getTexture() ); renderer->unbindTexture( getCompositeProgram()->getLocation( "uBlurMap" ), blurTarget->getTexture() ); renderer->unbindProgram( getCompositeProgram() ); }
40.722222
155
0.690314
hhsaez
3167bcf9b71fd04f17176a61cef538a2ad9f636c
7,910
cpp
C++
cpp/src/cylon/util/murmur3.cpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
229
2020-07-01T14:05:10.000Z
2022-03-25T12:26:58.000Z
cpp/src/cylon/util/murmur3.cpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
261
2020-06-30T23:23:15.000Z
2022-03-16T09:55:40.000Z
cpp/src/cylon/util/murmur3.cpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
36
2020-06-30T23:14:52.000Z
2022-03-03T02:37:09.000Z
/* * 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. */ /** * Murmur 3 hash, code is taken from * https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp */ #include <iostream> #include "murmur3.hpp" #include "compiler.h" #if defined(CYLON_COMP_GCC) #define FORCE_INLINE inline __attribute__((always_inline)) #else #define FORCE_INLINE __forceinline #endif namespace cylon { namespace util { inline uint32_t rotl32(uint32_t x, int8_t r) { return (x << r) | (x >> (32 - r)); } inline uint64_t rotl64(uint64_t x, int8_t r) { return (x << r) | (x >> (64 - r)); } #define ROTL32(x, y) rotl32(x, y) #define ROTL64(x, y) rotl64(x, y) #define BIG_CONSTANT(x) (x##LLU) //----------------------------------------------------------------------------- // Block read - if your platform needs to do endian-swapping or can only // handle aligned reads, do the conversion here FORCE_INLINE uint32_t getblock32(const uint32_t *p, int i) { return p[i]; } FORCE_INLINE uint64_t getblock64(const uint64_t *p, int i) { return p[i]; } //----------------------------------------------------------------------------- // Finalization mix - force all bits of a hash block to avalanche FORCE_INLINE uint32_t fmix32(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } //---------- FORCE_INLINE uint64_t fmix64(uint64_t k) { k ^= k >> 33; k *= BIG_CONSTANT(0xff51afd7ed558ccd); k ^= k >> 33; k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); k ^= k >> 33; return k; } //----------------------------------------------------------------------------- void MurmurHash3_x86_32(const void *key, int len, uint32_t seed, void *out) { const uint8_t *data = (const uint8_t *) key; const int nblocks = len / 4; uint32_t h1 = seed; const uint32_t c1 = 0xcc9e2d51; const uint32_t c2 = 0x1b873593; //---------- // body const uint32_t *blocks = (const uint32_t *) (data + nblocks * 4); for (int i = -nblocks; i; i++) { uint32_t k1 = getblock32(blocks, i); k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 13); h1 = h1 * 5 + 0xe6546b64; } //---------- // tail const uint8_t *tail = (const uint8_t *) (data + nblocks * 4); uint32_t k1 = 0; switch (len & 3) { case 3:k1 ^= tail[2] << 16; case 2:k1 ^= tail[1] << 8; case 1:k1 ^= tail[0]; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; } //---------- // finalization h1 ^= len; h1 = fmix32(h1); *reinterpret_cast<uint32_t *>(out) = h1; } //----------------------------------------------------------------------------- void MurmurHash3_x86_128(const void *key, const int len, uint32_t seed, void *out) { const uint8_t *data = (const uint8_t *) key; const int nblocks = len / 16; uint32_t h1 = seed; uint32_t h2 = seed; uint32_t h3 = seed; uint32_t h4 = seed; const uint32_t c1 = 0x239b961b; const uint32_t c2 = 0xab0e9789; const uint32_t c3 = 0x38b34ae5; const uint32_t c4 = 0xa1e38b93; const uint32_t *blocks = (const uint32_t *) (data + nblocks * 16); for (int i = -nblocks; i; i++) { uint32_t k1 = getblock32(blocks, i * 4 + 0); uint32_t k2 = getblock32(blocks, i * 4 + 1); uint32_t k3 = getblock32(blocks, i * 4 + 2); uint32_t k4 = getblock32(blocks, i * 4 + 3); k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1, 19); h1 += h2; h1 = h1 * 5 + 0x561ccd1b; k2 *= c2; k2 = ROTL32(k2, 16); k2 *= c3; h2 ^= k2; h2 = ROTL32(h2, 17); h2 += h3; h2 = h2 * 5 + 0x0bcaa747; k3 *= c3; k3 = ROTL32(k3, 17); k3 *= c4; h3 ^= k3; h3 = ROTL32(h3, 15); h3 += h4; h3 = h3 * 5 + 0x96cd1c35; k4 *= c4; k4 = ROTL32(k4, 18); k4 *= c1; h4 ^= k4; h4 = ROTL32(h4, 13); h4 += h1; h4 = h4 * 5 + 0x32ac3b17; } //---------- // tail const uint8_t *tail = (const uint8_t *) (data + nblocks * 16); uint32_t k1 = 0; uint32_t k2 = 0; uint32_t k3 = 0; uint32_t k4 = 0; switch (len & 15) { case 15:k4 ^= tail[14] << 16; case 14:k4 ^= tail[13] << 8; case 13:k4 ^= tail[12] << 0; k4 *= c4; k4 = ROTL32(k4, 18); k4 *= c1; h4 ^= k4; case 12:k3 ^= tail[11] << 24; case 11:k3 ^= tail[10] << 16; case 10:k3 ^= tail[9] << 8; case 9:k3 ^= tail[8] << 0; k3 *= c3; k3 = ROTL32(k3, 17); k3 *= c4; h3 ^= k3; case 8:k2 ^= tail[7] << 24; case 7:k2 ^= tail[6] << 16; case 6:k2 ^= tail[5] << 8; case 5:k2 ^= tail[4] << 0; k2 *= c2; k2 = ROTL32(k2, 16); k2 *= c3; h2 ^= k2; case 4:k1 ^= tail[3] << 24; case 3:k1 ^= tail[2] << 16; case 2:k1 ^= tail[1] << 8; case 1:k1 ^= tail[0] << 0; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; h1 ^= k1; } h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len; h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; h1 = fmix32(h1); h2 = fmix32(h2); h3 = fmix32(h3); h4 = fmix32(h4); h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; (reinterpret_cast<uint32_t *>(out))[0] = h1; (reinterpret_cast<uint32_t *>(out))[1] = h2; (reinterpret_cast<uint32_t *>(out))[2] = h3; (reinterpret_cast<uint32_t *>(out))[3] = h4; } void MurmurHash3_x64_128(const void *key, const int len, const uint32_t seed, void *out) { const uint8_t *data = (const uint8_t *) key; const int nblocks = len / 16; uint64_t h1 = seed; uint64_t h2 = seed; const uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5); const uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f); const uint64_t *blocks = (const uint64_t *) (data); for (int i = 0; i < nblocks; i++) { uint64_t k1 = getblock64(blocks, i * 2 + 0); uint64_t k2 = getblock64(blocks, i * 2 + 1); k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1; h1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2; h2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } const uint8_t *tail = (const uint8_t *) (data + nblocks * 16); uint64_t k1 = 0; uint64_t k2 = 0; switch (len & 15) { case 15:k2 ^= ((uint64_t) tail[14]) << 48; case 14:k2 ^= ((uint64_t) tail[13]) << 40; case 13:k2 ^= ((uint64_t) tail[12]) << 32; case 12:k2 ^= ((uint64_t) tail[11]) << 24; case 11:k2 ^= ((uint64_t) tail[10]) << 16; case 10:k2 ^= ((uint64_t) tail[9]) << 8; case 9:k2 ^= ((uint64_t) tail[8]) << 0; k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2; case 8:k1 ^= ((uint64_t) tail[7]) << 56; case 7:k1 ^= ((uint64_t) tail[6]) << 48; case 6:k1 ^= ((uint64_t) tail[5]) << 40; case 5:k1 ^= ((uint64_t) tail[4]) << 32; case 4:k1 ^= ((uint64_t) tail[3]) << 24; case 3:k1 ^= ((uint64_t) tail[2]) << 16; case 2:k1 ^= ((uint64_t) tail[1]) << 8; case 1:k1 ^= ((uint64_t) tail[0]) << 0; k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1; } h1 ^= len; h2 ^= len; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; (reinterpret_cast<uint64_t *>(out))[0] = h1; (reinterpret_cast<uint64_t *>(out))[1] = h2; } } // namespace util } // namespace cylon
24.042553
84
0.525032
deHasara
3168e4a09c0e78c678ed89b72d7f03167fa4ac03
4,186
cpp
C++
src/MResProvider_Textures.cpp
viktorcpp/endless2.0save
9824aebd56346f1b9526b730063b84918bd6ac08
[ "MIT" ]
null
null
null
src/MResProvider_Textures.cpp
viktorcpp/endless2.0save
9824aebd56346f1b9526b730063b84918bd6ac08
[ "MIT" ]
null
null
null
src/MResProvider_Textures.cpp
viktorcpp/endless2.0save
9824aebd56346f1b9526b730063b84918bd6ac08
[ "MIT" ]
null
null
null
namespace endless { //MResProvider_Textures void MResProvider_Textures::Load( MTexture::TextureInternalData::Component& comp, const char* path ) { if( path == 0 ) { LOGE( "%s : path == 0", __FUNCTION__ ); return; } std::string _error_buffer; D3D11_SHADER_RESOURCE_VIEW_DESC _srv_desc; TexMetadata _tex_metadata; ScratchImage _scratch_image; D3D11_SAMPLER_DESC _sampler_desc; ID3D11Resource* _texture_res = nullptr; ID3D11ShaderResourceView* _shader_resview = nullptr; ID3D11SamplerState* _samplerstate = nullptr; ID3D11Device* _device = const_cast<ID3D11Device*>( MCore::GetMRendererDriver()->GetDevice() ); ZeroMemory( &_srv_desc, sizeof( D3D11_SHADER_RESOURCE_VIEW_DESC ) ); ZeroMemory( &_tex_metadata, sizeof( TexMetadata ) ); ZeroMemory( &_sampler_desc, sizeof( D3D11_SAMPLER_DESC ) ); std::wstring wpath; MUtils::LtoW( path, wpath); __TRY__ HRESULT hr = LoadFromDDSFile( wpath.c_str(), DDS_FLAGS_NONE, nullptr, _scratch_image ); if( FAILED(hr) ) { MUtils::TranslateLastError(_error_buffer); LOGE( "%s : LoadFromDDSFile FAILED <%s> at <%s>\n", __FUNCTION__, _error_buffer.c_str(), path ); return; } _tex_metadata = _scratch_image.GetMetadata(); _srv_desc.Format = _tex_metadata.format; hr = CreateTexture( _device, _scratch_image.GetImages(), _scratch_image.GetImageCount(), _tex_metadata, &_texture_res ); if( FAILED(hr) ) { MUtils::TranslateLastError(_error_buffer); LOGE( "%s : CreateTexture FAILED <%s>\n", __FUNCTION__, _error_buffer.c_str() ); return; } if( _tex_metadata.arraySize > 1 ) { _srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY; _srv_desc.Texture1DArray.MipLevels = (UINT)_tex_metadata.mipLevels; _srv_desc.Texture1DArray.ArraySize = (UINT)_tex_metadata.arraySize; } else { _srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; _srv_desc.Texture1D.MipLevels = (UINT)_tex_metadata.mipLevels; } hr = _device->CreateShaderResourceView( _texture_res, &_srv_desc, &_shader_resview ); if( FAILED(hr) ) { MUtils::TranslateLastError(_error_buffer); LOGE( "%s : CreateShaderResourceView FAILED <%s>\n", __FUNCTION__, _error_buffer.c_str() ); return; } // Sampler State default _sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; _sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; _sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; _sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; _sampler_desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; _sampler_desc.MinLOD = 0; _sampler_desc.MaxLOD = D3D11_FLOAT32_MAX; _sampler_desc.MipLODBias = 0.0f; _sampler_desc.MaxAnisotropy = 1; _sampler_desc.BorderColor[0] = 0; _sampler_desc.BorderColor[1] = 0; _sampler_desc.BorderColor[2] = 0; _sampler_desc.BorderColor[3] = 0; hr = _device->CreateSamplerState( &_sampler_desc, &_samplerstate ); if( FAILED( hr ) ) { MUtils::TranslateLastError(_error_buffer); LOGE( "%s : CreateSamplerState FAILED <%s>\n", __FUNCTION__, _error_buffer.c_str() ); return; } comp.resource = _texture_res; comp.sampler_state = _samplerstate; comp.shader_res_view = _shader_resview; __CATCH__ } // Load MResProvider_Textures::MResProvider_Textures() {} MResProvider_Textures::MResProvider_Textures(MResProvider_Textures&) {} MResProvider_Textures::~MResProvider_Textures() {} } // namespace endless
37.711712
128
0.605351
viktorcpp
3168fefb5f1222fdcea6c08eb2d03c2e93d7a926
1,148
hpp
C++
src/FCFS.hpp
zwimer/CPU-Simulator
9e2e52a17e01258d36ac2780fb342319b922ca10
[ "MIT" ]
null
null
null
src/FCFS.hpp
zwimer/CPU-Simulator
9e2e52a17e01258d36ac2780fb342319b922ca10
[ "MIT" ]
null
null
null
src/FCFS.hpp
zwimer/CPU-Simulator
9e2e52a17e01258d36ac2780fb342319b922ca10
[ "MIT" ]
null
null
null
/* Operating Systems Project 1 * Alex Slanski, Owen Stenson, Zac Wimer */ #ifndef FCFS_hpp #define FCFS_hpp //My includes #include "Algo.hpp" //System includes #include <set> #include <list> //FCFS algorithm class class FCFS : public Algo { private: //Representation bool ProcessRunning; uint FinishContextSwitch; std::list<Process*> Queued; public: //Constructor FCFS(); //Destructor ~FCFS(); //Get the current queue const std::ostringstream* getQ() const; //Returns true if the ready queue is empty bool queueEmpty() const; //Returns the amount of time until you want void addProcess(Process *p); //The algorithm will return an int specifying //the next time it wants to be notified of the time //Return's -1 is done, otherwise returns a positive number int nextNotify() const; //Returns an event to do at time t //This will only be called at time t! //Returns NULL if there is no new event //If this returns an event, a context swtich will start Event* getNextAction(); }; #endif /* FCFS_hpp */
20.5
62
0.649826
zwimer
3169678165a9a86ed8a9c281b07f7acef6a94a72
16,593
cpp
C++
src/ossim/imaging/ossimConvolutionSource.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/imaging/ossimConvolutionSource.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/imaging/ossimConvolutionSource.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
1
2019-09-25T00:43:35.000Z
2019-09-25T00:43:35.000Z
// Copyright (C) 2000 ImageLinks Inc. // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //******************************************************************* // $Id: ossimConvolutionSource.cpp 23664 2015-12-14 14:17:27Z dburken $ #include <ossim/imaging/ossimConvolutionSource.h> #include <ossim/imaging/ossimImageData.h> #include <ossim/imaging/ossimDiscreteConvolutionKernel.h> #include <ossim/imaging/ossimImageDataFactory.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimKeyword.h> static const ossimKeyword NUMBER_OF_MATRICES = ossimKeyword("number_of_matrices", ""); static const ossimKeyword NUMBER_OF_ROWS = ossimKeyword("rows", ""); static const ossimKeyword NUMBER_OF_COLS = ossimKeyword("cols", ""); RTTI_DEF1(ossimConvolutionSource, "ossimConvolutionSource", ossimImageSourceFilter); ossimConvolutionSource::ossimConvolutionSource() : ossimImageSourceFilter(), theTile(NULL) { } ossimConvolutionSource::ossimConvolutionSource(ossimImageSource* inputSource, const NEWMAT::Matrix& convolutionMatrix) : ossimImageSourceFilter(inputSource), theTile(NULL) { theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionMatrix)); setKernelInformation(); initialize(); } ossimConvolutionSource::ossimConvolutionSource(ossimImageSource* inputSource, const vector<NEWMAT::Matrix>& convolutionList) : ossimImageSourceFilter(inputSource), theTile(NULL) { setConvolutionList(convolutionList); } ossimConvolutionSource::~ossimConvolutionSource() { deleteConvolutionList(); } void ossimConvolutionSource::setConvolution(const double* kernel, int nrows, int ncols, bool doWeightedAverage) { NEWMAT::Matrix m(nrows, ncols); const double* tempPtr = kernel; for(int row = 0; row < nrows; ++row) { for(int col = 0; col < ncols; ++col) { m[row][col] =*tempPtr; ++tempPtr; } } setConvolution(m, doWeightedAverage); } void ossimConvolutionSource::setConvolutionList(const vector<NEWMAT::Matrix>& convolutionList, bool doWeightedAverage) { deleteConvolutionList(); ossim_uint32 idx; for(idx = 0; idx < convolutionList.size(); ++idx) { theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionList[idx], doWeightedAverage)); } setKernelInformation(); } ossimRefPtr<ossimImageData> ossimConvolutionSource::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theInputConnection) return ossimRefPtr<ossimImageData>(); if((!isSourceEnabled())|| (theConvolutionKernelList.size() < 1)) { return theInputConnection->getTile(tileRect, resLevel); } if(!theTile.valid()) { allocate(); if(!theTile.valid()) // Throw exception??? { return theInputConnection->getTile(tileRect, resLevel); } } ossim_uint32 w = tileRect.width(); ossim_uint32 h = tileRect.height(); ossim_uint32 tw = theTile->getWidth(); ossim_uint32 th = theTile->getHeight(); theTile->setWidth(w); theTile->setHeight(h); if((w*h)!=(tw*th)) { theTile->initialize(); theTile->makeBlank(); } else { theTile->makeBlank(); } theTile->setOrigin(tileRect.ul()); long offsetX = (theMaxKernelWidth)/2; long offsetY = (theMaxKernelHeight)/2; ossimIrect requestRect(tileRect.ul().x - offsetX, tileRect.ul().y - offsetY, tileRect.lr().x + offsetX, tileRect.lr().y + offsetY); ossimRefPtr<ossimImageData> input = theInputConnection->getTile(requestRect, resLevel); if(!input.valid() || (input->getDataObjectStatus() == OSSIM_NULL)|| (input->getDataObjectStatus() == OSSIM_EMPTY)) { return input; } switch(theTile->getScalarType()) { case OSSIM_UCHAR: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast<ossim_uint8>(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast<ossim_uint8>(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_USHORT16: case OSSIM_USHORT11: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast<ossim_uint16>(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast<ossim_uint16>(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_SSHORT16: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast<ossim_sint16>(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast<ossim_sint16>(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_FLOAT: case OSSIM_NORMALIZED_FLOAT: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast<float>(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast<float>(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } case OSSIM_DOUBLE: case OSSIM_NORMALIZED_DOUBLE: { if(theConvolutionKernelList.size() == 1) { convolve(static_cast<double>(0), input, theConvolutionKernelList[0]); } else { ossim_uint32 upperBound = (ossim_uint32)theConvolutionKernelList.size(); ossim_uint32 idx; for(idx = 0; idx < upperBound; ++idx) { convolve(static_cast<double>(0), input, theConvolutionKernelList[idx]); input->loadTile(theTile.get()); } } break; } default: { theTile->loadTile(input.get()); } } theTile->validate(); return theTile; } template <class T> void ossimConvolutionSource::convolve(T /* dummyVariable */, ossimRefPtr<ossimImageData> inputTile, ossimDiscreteConvolutionKernel* kernel) { ossimIpt startOrigin = theTile->getOrigin(); // Make sure that the patch is not empty or NULL // ossimIpt startDelta(startOrigin.x - inputTile->getOrigin().x, startOrigin.y - inputTile->getOrigin().y); ossimDataObjectStatus status = inputTile->getDataObjectStatus(); // let's setup some variables that we will need to do the // convolution algorithm. // ossimIrect patchRect = inputTile->getImageRectangle(); long tileHeight = theTile->getHeight(); long tileWidth = theTile->getWidth(); long outputBands = theTile->getNumberOfBands(); long convolutionWidth = kernel->getWidth(); long convolutionHeight = kernel->getHeight(); long convolutionOffsetX= convolutionWidth/2; long convolutionOffsetY= convolutionHeight/2; long patchWidth = patchRect.width(); long convolutionTopLeftOffset = 0; long convolutionCenterOffset = 0; long outputOffset = 0; T np = 0; const double minPix = ossim::defaultMin(getOutputScalarType()); const double maxPix = ossim::defaultMax(getOutputScalarType()); // const double* maxPix = inputTile->getMaxPix(); const double* nullPix = inputTile->getNullPix(); double convolveResult = 0; if(status == OSSIM_PARTIAL) // must check for NULLS { for(long y = 0; y <tileHeight; y++) { convolutionCenterOffset = patchWidth*(startDelta.y + y) + startDelta.x; convolutionTopLeftOffset = patchWidth*(startDelta.y + y - convolutionOffsetY) + startDelta.x-convolutionOffsetX; for(long x =0; x < tileWidth; x++) { if(!inputTile->isNull(convolutionCenterOffset)) { for(long b = 0; b < outputBands; ++b) { T* buf = (T*)(inputTile->getBuf(b)) + convolutionTopLeftOffset; T* outBuf = (T*)(theTile->getBuf(b)); kernel->convolveSubImage(buf, patchWidth, convolveResult, (T)nullPix[b]); convolveResult = convolveResult < minPix? minPix:convolveResult; convolveResult = convolveResult > maxPix? maxPix:convolveResult; outBuf[outputOffset] = (T)convolveResult; } } else { theTile->setNull(outputOffset); } ++convolutionCenterOffset; ++convolutionTopLeftOffset; ++outputOffset; } } } else // do not need to check for nulls here. { for(long b = 0; b < outputBands; ++b) { double convolveResult = 0; const T* buf = (const T*)inputTile->getBuf(b); T* outBuf = (T*)(theTile->getBuf(b)); np =(T)nullPix[b]; outputOffset = 0; for(long y = 0; y <tileHeight; y++) { convolutionTopLeftOffset = patchWidth*(startDelta.y + y - convolutionOffsetY) + startDelta.x-convolutionOffsetX; for(long x =0; x < tileWidth; x++) { kernel->convolveSubImage(&buf[convolutionTopLeftOffset], patchWidth, convolveResult, np); // NOT SURE IF I WANT TO CLAMP IN A CONVOLUTION SOURCE // seems better to clamp to a scalar range instead of an input min max convolveResult = convolveResult < minPix? (T)minPix:convolveResult; convolveResult = convolveResult > maxPix?(T)maxPix:convolveResult; outBuf[outputOffset] = (T)convolveResult; ++outputOffset; ++convolutionTopLeftOffset; } } } } } void ossimConvolutionSource::initialize() { ossimImageSourceFilter::initialize(); theTile = NULL; } void ossimConvolutionSource::allocate() { if(theInputConnection) { theTile = ossimImageDataFactory::instance()->create(this, theInputConnection); theTile->initialize(); } } bool ossimConvolutionSource::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossim_uint32 numberOfMatrices = 0; for(ossim_uint32 m = 0; m < theConvolutionKernelList.size();++m) { if(theConvolutionKernelList[m]) { ++numberOfMatrices; const NEWMAT::Matrix& kernel = theConvolutionKernelList[m]->getKernel(); ossimString mPrefix = "m" + ossimString::toString(numberOfMatrices) + "."; kwl.add(prefix, (mPrefix + "rows").c_str(), kernel.Nrows(), true); kwl.add(prefix, (mPrefix + "cols").c_str(), kernel.Ncols(), true); for(ossim_int32 row = 0; row < kernel.Nrows(); ++row) { for(ossim_int32 col =0; col < kernel.Ncols(); ++col) { ossimString newPrefix = mPrefix + ossimString::toString(row+1) + "_" + ossimString::toString(col+1); kwl.add(prefix, newPrefix, kernel[row][col], true); } } } } kwl.add(prefix, NUMBER_OF_MATRICES, numberOfMatrices, true); return ossimImageSourceFilter::saveState(kwl, prefix); } bool ossimConvolutionSource::loadState(const ossimKeywordlist& kwl, const char* prefix) { deleteConvolutionList(); const char* numberOfMatrices = kwl.find(prefix, NUMBER_OF_MATRICES); ossim_int32 matrixCount = ossimString(numberOfMatrices).toLong(); ossim_int32 numberOfMatches = 0; ossim_int32 index = 0; while(numberOfMatches < matrixCount) { ossimString newPrefix = prefix; newPrefix += ossimString("m"); newPrefix += ossimString::toString(index); newPrefix += ossimString("."); const char* rows = kwl.find((newPrefix+NUMBER_OF_ROWS.key()).c_str()); const char* cols = kwl.find((newPrefix+NUMBER_OF_COLS.key()).c_str()); if(rows&&cols) { ++numberOfMatches; ossim_int32 numberOfRows = ossimString(rows).toLong(); ossim_int32 numberOfCols = ossimString(cols).toLong(); NEWMAT::Matrix convolutionMatrix(numberOfRows, numberOfCols); for(ossim_int32 r = 1; r <= numberOfRows; r++) { for(ossim_int32 c = 1; c <= numberOfCols; c++) { convolutionMatrix[r-1][c-1] = 0.0; ossimString value = ossimString::toString(r); value += "_"; value += ossimString::toString(c); const char* v = kwl.find(newPrefix.c_str(), value.c_str()); if(v) { convolutionMatrix[r-1][c-1] = ossimString(v).toDouble(); } } } theConvolutionKernelList.push_back(new ossimDiscreteConvolutionKernel(convolutionMatrix)); } ++index; } setKernelInformation(); return ossimImageSourceFilter::loadState(kwl, prefix); } void ossimConvolutionSource::setKernelInformation() { ossim_uint32 index; if(theConvolutionKernelList.size() > 0) { theMaxKernelWidth = theConvolutionKernelList[0]->getWidth(); theMaxKernelHeight = theConvolutionKernelList[0]->getHeight(); for(index = 1; index < theConvolutionKernelList.size(); ++index) { ossim_int32 w = theConvolutionKernelList[index]->getWidth(); ossim_int32 h = theConvolutionKernelList[index]->getHeight(); theMaxKernelWidth = theMaxKernelWidth < w?w:theMaxKernelWidth; theMaxKernelHeight = theMaxKernelHeight < h?h:theMaxKernelHeight; } } } void ossimConvolutionSource::deleteConvolutionList() { for(ossim_int32 index = 0; index < (ossim_int32)theConvolutionKernelList.size(); ++index) { delete theConvolutionKernelList[index]; } theConvolutionKernelList.clear(); } void ossimConvolutionSource::setConvolution(const NEWMAT::Matrix& convolutionMatrix, bool doWeightedAverage) { std::vector<NEWMAT::Matrix> m; m.push_back(convolutionMatrix); setConvolutionList(m, doWeightedAverage); }
31.426136
124
0.560779
rkanavath
316a2329329f475ebcc44926f2c66907e487279d
2,748
cpp
C++
src/VAC/SaveAndLoad.cpp
Qt-Widgets/vpaint
6b1bf57e3c239194443f7284adfd5c5326cd1bf2
[ "ECL-2.0", "Apache-2.0" ]
697
2015-08-08T09:27:02.000Z
2022-03-25T04:38:29.000Z
src/VAC/SaveAndLoad.cpp
Qt-Widgets/vpaint
6b1bf57e3c239194443f7284adfd5c5326cd1bf2
[ "ECL-2.0", "Apache-2.0" ]
125
2015-08-09T08:45:42.000Z
2022-03-31T11:26:16.000Z
src/VAC/SaveAndLoad.cpp
Qt-Widgets/vpaint
6b1bf57e3c239194443f7284adfd5c5326cd1bf2
[ "ECL-2.0", "Apache-2.0" ]
64
2015-08-09T10:34:34.000Z
2022-01-03T18:01:57.000Z
// Copyright (C) 2012-2019 The VPaint Developers. // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT // // 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 "SaveAndLoad.h" #include <QTextStream> int Save::indent_ = 0; Field::Field() : string_() { } Field::Field(const QString & string) : string_(string) { } QTextStream & operator<<(QTextStream & str, const Field & field) { str << (Save::newField(field.string_)); return str; } QTextStream & operator>>(QTextStream & str, Field & field) { field = Read::field(str); return str; } QString Save::indent(int n) { QString res; for(int i=0; i<n; i++) res += " "; return res; } void Save::resetIndent() { indent_ = 0; } void Save::incrIndent() { indent_ += 4; } void Save::decrIndent() { indent_ -= 4; } QString Save::indent() { return indent(indent_); } QString Save::newField(const QString & fieldName) { return "\n" + indent() + fieldName + " : "; } QString Save::openCurlyBrackets() { QString res = "\n" + indent() + "{"; incrIndent(); return res; } QString Save::closeCurlyBrackets() { decrIndent(); return "\n" + indent() + "}"; } QString Read::field(QTextStream & in) { QString res, colon; in >> res >> colon; return res; } QString Read::string(QTextStream & in) { QString res; in >> res; return res; } #include <QtDebug> void Read::skipBracket(QTextStream & in) { QString skip; in >> skip; //qDebug() << skip; } QString Read::readBracketedBlock(QTextStream & in) { QString res; // Read first opening bracket, ignore everything which is before unsigned int openedBracket = 0; char c; while(!openedBracket) { in >> c; if(c == '[' || c == '(' || c == '{') { openedBracket++; res.append(c); } } // Read until match found while(openedBracket) { in >> c; res.append(c); if(c == '[' || c == '(' || c == '{') openedBracket++; else if(c == ']' || c == ')' || c == '}') openedBracket--; } return res; }
18.951724
75
0.598981
Qt-Widgets
316a3eecc38ef16cafa9b1a22e75b52fdfa2592c
8,707
cpp
C++
tests/Console/main.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
13
2017-03-21T22:46:18.000Z
2020-07-30T01:31:57.000Z
tests/Console/main.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
null
null
null
tests/Console/main.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
2
2018-07-23T19:56:41.000Z
2020-07-30T01:32:01.000Z
// ForkENGINE: Console Test // 25/02/2014 #include <fengine/core.h> #include <fengine/using.h> #include <iostream> using namespace std; using namespace Fork; class MyLogEventHandler : public IO::Console::LogEventHandler { public: void OnPrintLn(const std::string& indent, const std::string& message, const IO::Log::EntryTypes type) override; //void OnStartLn(const std::string& indent); }; /*void MyLogEventHandler::OnStartLn(const std::string& indent) { OnPushColor(Platform::ConsoleManip::Colors::White); OnPrint("[" + IO::SystemClock::SecondsToTimePoint(IO::SystemClock::ElapsedTime()) + "] "); OnPopColor(); IO::Console::LogEventHandler::OnStartLn(indent); }*/ void MyLogEventHandler::OnPrintLn(const std::string& indent, const std::string& message, const IO::Log::EntryTypes type) { auto start = message.find("\""); if (start != std::string::npos) { auto end = message.find("\"", start + 1); if (end != std::string::npos) { ++end; Platform::ConsoleManip::ScopedColor unused(Platform::ConsoleManip::Colors::Gray); IO::Console::Print(indent + message.substr(0, start)); { Platform::ConsoleManip::ScopedColor unused2(Platform::ConsoleManip::Colors::Pink | Platform::ConsoleManip::Colors::Intens); IO::Console::Print(message.substr(start, end - start)); } IO::Console::PrintLn(message.substr(end, message.size() - end)); return; } } IO::Console::LogEventHandler::OnPrintLn(indent, message, type); } int main() { IO::Log::AddEventHandler(std::make_shared<MyLogEventHandler>()); IO::Log::AddEventHandler(std::make_shared<IO::LogFile::LogEventHandler>("LogFile.txt")); #if 1//!ENCRYPTION TEST! IO::CryptoBitKey bitKey("LoL Code"); std::string encryptStr = "One Time Pad"; IO::Log::Message("Original String: \"" + encryptStr + "\""); bitKey.EncodeContainer(encryptStr); IO::Log::Message("After Encryption: \"" + encryptStr + "\""); bitKey.DecodeContainer(encryptStr); IO::Log::Message("After Decryption: \"" + encryptStr + "\""); #endif #if 1//!COLLISION TEST! { Math::Triangle3f triA { { -1, -1, 0 }, { 0, 1, 0 }, { 1, -1, 0 } }; Math::Triangle3f triB { { -1, 0, -1 }, { 0, 0, 1 }, { 0, 0, -1 } }; Math::Line3f intersect; if (Math::CheckIntersectionWithTriangle(triA, triB, intersect)) IO::Log::Message("Intersection: " + IO::Printer::Print(intersect.start) + ", " + IO::Printer::Print(intersect.end)); else IO::Log::Message("No Intersection"); } #endif #if 1//!MEMENTO TEST! MementoHierarchy<int> timeline(0); timeline.Commit(3); timeline.Commit(4); timeline.Prev(); timeline.Commit(5); timeline.Commit(6); timeline.Prev(); timeline.Prev(); timeline.Commit(4); timeline.Commit(5); timeline.Commit(7); timeline.Traverse( [](MementoHierarchy<int>::TreeNode* node) { IO::Log::Message(std::string(node->Level()*2, ' ') + ToStr(node->data)); } ); #endif // Common math tests Matrix2f m2; Matrix3f m3; Matrix4f m4; AABB2f box1; box1.InsertPoint(Vector2f(5, 2)); Angle<> angle = Degree<>(45.0f) * 2.0f + Radian<>(0.5f); angle += Degree<>(90.0f); angle += Radian<>(Math::pi/2); angle *= 2.5f; Angle<> angle2 = Degree<>(90.0f) + Radian<>(Math::pi/2); auto deg1 = angle2.Get<Degree<>>(); Degree<> deg2(angle2); auto rad1 = angle2.Get<Radian<>>(); Radian<> rad2(angle2); auto degRadEq = (rad2 == deg2); Recti rc(4, 2, 20, 19); Frustum<> frustum; frustum.Normalize(); Line3f line(Vector3f(0, 0, 0), Vector3f(0, 2, 3)); Ray3f ray(line); Cylinder<> cylinder(1.0f, 3.0f); IO::Log::Message("cylinder volume = " + ToStr(cylinder.Volume())); Cone<> cone(1.0f, 3.0f); IO::Log::Message("cone volume = " + ToStr(cone.Volume())); Capsule<> capsule(1.0f, 3.0f); IO::Log::Message("capsule volume = " + ToStr(capsule.Volume())); // Quaternion tests m3.RotateX(Degree<>(70).Get<Radian<>>()); Quaternion<> quat(m3); Matrix3f m3b = quat.Mat3(); IO::Console::PrintLn("m3:"); IO::Console::PrintLn(IO::Printer::Print(m3)); IO::Console::PrintLn("\nquat:"); IO::Console::PrintLn(IO::Printer::Print(quat)); IO::Console::PrintLn("\nm3b:"); IO::Console::PrintLn(IO::Printer::Print(m3b)); IO::Console::PrintLn("\nm4:"); IO::Console::PrintLn(IO::Printer::Print(m4)); Transform2Df trans2; Transform3Df trans3; quat.SetupEulerRotation(Vector3f(0.5f, 0.2f, -0.4f)); auto eulerRot = quat.EulerRotation(); IO::Console::PrintLn(IO::Printer::Print(eulerRot)); // Container tests try { IO::Log::Message("Buffer Test"); struct Test { Test(int X = 0, float* P = nullptr) : x(X), p(P) {} int x; float* p; }; StrideBuffer buf; buf.SetStride(sizeof(Test)); buf.PushBack<Test>(Test(5)); buf.PushBack<Test>(Test(42)); for (size_t i = 0; i < buf.Size(); ++i) { const auto entry = buf.Get<Test>(i); IO::Log::Message("x = " + ToStr(entry.x) + ", p = " + ToStr((long)entry.p)); } } catch (const std::exception& err) { IO::Log::Error(err.what()); } try { throw IndexOutOfBoundsException(__FUNCTION__, 5); } catch (const DefaultException& err) { IO::Log::Error(err); } // File test IO::VirtualFile inFile("test.txt"); inFile.WriteStringNL("/--------------\\"); inFile.WriteStringNL("| Hello, World |"); inFile.WriteStringNL("\\--------------/"); inFile.WriteToHDD(); // OS version tests const auto sysInfo = Platform::QuerySystemInfo(); std::string version; version += "<0101>" + sysInfo.osName + "</>"; version += " " + sysInfo.osProductType; version += " " + sysInfo.osExtensions; version += " <0110>(" + sysInfo.osBuild + ")</>"; IO::Log::MessageColored(version); // Console tests IO::Log::Message("ForkENGINE Version " + EngineVersion()); IO::Log::ScopedIndent indent; IO::Log::Message("Hello, World!"); IO::Log::Message("angle = " + ToStr(angle.Get<Degree<>>()) + " degrees"); IO::Log::Message("angle = " + ToStr(angle.Get<Radian<>>()) + " radians"); IO::Log::Message("angle = " + ToStr(angle.Get<Angle<>>()) + " angle units"); IO::Log::Error("Test 1"); IO::Log::Message("Test 2"); IO::Log::Warning("Test 3"); IO::Log::Message("Test 4", Platform::ConsoleManip::Colors::Black, Platform::ConsoleManip::Colors::White); IO::Log::Success("Test Completed Successful"); IO::Log::Message("Hello, \"User\"!"); IO::Log::MessageColored("Foo <1101>Bar</> Blub &amp; <0000|1001>x &lt; 2</> End"); IO::Log::MessageColored("<1001>L</><0101>U</><0011>K</><1101>A</><1011>S</>"); // Polynom and printer test IO::Log::Message("Polynomial: " + IO::Printer::Print(Math::Polynomial<float, 3>({ 3, -4.34f, 0, 1 }))); // Raster number tests const float rasterSize = 5.0f; const bool flushRaster = true; Math::RasterNumber<float> rasterNum = -8.5f; auto IncRaster = [&](float val) { rasterNum += val; auto num = static_cast<float>(rasterNum); auto rnum = (flushRaster ? rasterNum.RasterFlush(rasterSize) : rasterNum.Raster(rasterSize)); IO::Log::Message( "num = " + ToStr(num) + "\trasterNum(" + ToStr(rasterSize) + ") = " + ToStr(rnum) ); }; IncRaster(4.4f); IncRaster(2.6f); IncRaster(1.5f); IncRaster(0.4f); IncRaster(3.8f); IncRaster(5.7f); // Filename tests IO::Filename filename("/home/lh/Tests/TestFile1.txt"); filename.ChangePath("C:/Users/Lukas Hermanns\\"); //filename.PopPath(); filename.AddPath("../../Program Files\\Test/../Foo-Bar"); filename.RemovePath("c:/program files/Foo-bars/Bla"); filename.ChangeExt("dump"); filename.ChangeNameExt("test.obj"); filename.ChangeName("LoL..."); filename.ChangeName("FILE"); IO::Log::Message("Filename tests:"); IO::Log::Message("filename.Get = " + filename.Get()); IO::Log::Message("filename.Path = " + filename.Path()); IO::Log::Message("filename.Name = " + filename.Name()); IO::Log::Message("filename.Ext = " + filename.Ext()); IO::Log::Message("filename.NameExt = " + filename.NameExt()); IO::Console::Wait(); return 0; }
29.023333
139
0.58206
LukasBanana
316a5316001f07e932360a93d7d4f450c480cb9d
8,535
cpp
C++
torch/csrc/jit/codegen/cuda/lower_loops.cpp
sanchitintel/pytorch
416f59308023b5d98f6ea4ecdd0bcd3829edb7a7
[ "Intel" ]
60,067
2017-01-18T17:21:31.000Z
2022-03-31T21:37:45.000Z
torch/csrc/jit/codegen/cuda/lower_loops.cpp
sanchitintel/pytorch
416f59308023b5d98f6ea4ecdd0bcd3829edb7a7
[ "Intel" ]
66,955
2017-01-18T17:21:38.000Z
2022-03-31T23:56:11.000Z
torch/csrc/jit/codegen/cuda/lower_loops.cpp
sanchitintel/pytorch
416f59308023b5d98f6ea4ecdd0bcd3829edb7a7
[ "Intel" ]
19,210
2017-01-18T17:45:04.000Z
2022-03-31T23:51:56.000Z
#include <c10/util/irange.h> #include <torch/csrc/jit/codegen/cuda/lower_loops.h> #include <torch/csrc/jit/codegen/cuda/arith.h> #include <torch/csrc/jit/codegen/cuda/ir_iostream.h> #include <torch/csrc/jit/codegen/cuda/ir_utils.h> #include <torch/csrc/jit/codegen/cuda/iter_visitor.h> #include <torch/csrc/jit/codegen/cuda/kernel_expr_evaluator.h> #include <torch/csrc/jit/codegen/cuda/kernel_ir_printer.h> #include <torch/csrc/jit/codegen/cuda/lower2device.h> #include <torch/csrc/jit/codegen/cuda/lower_utils.h> #include <torch/csrc/jit/codegen/cuda/transform_replay.h> #include <algorithm> #include <deque> #include <numeric> namespace torch { namespace jit { namespace fuser { namespace cuda { std::vector<kir::Expr*> LoopNestGenerator::loweredExprs( const std::vector<Expr*>& exprs) { FUSER_PERF_SCOPE("GpuLower::Lower::LoopNestGenerator::loweredExprs"); TORCH_INTERNAL_ASSERT(FusionGuard::getCurFusion() != nullptr); LoopNestGenerator generator(exprs); return generator.lowered_exprs_; } LoopNestGenerator::LoopNestGenerator(const std::vector<Expr*>& exprs) { generate(exprs); } namespace { kir::ForLoop* openForHelper(kir::ForLoop* scope, IterDomain* id) { const auto gpu_lower = GpuLower::current(); kir::IrBuilder ir_builder(gpu_lower->kernel()); const auto kir_id = gpu_lower->lowerValue(id)->as<kir::IterDomain>(); auto extent_with_halo = gpu_lower->haloInfo().getExtent(kir_id); kir::ForLoop* new_scope = nullptr; if (extent_with_halo) { // When an axis is extended with halo, unrolling and vectorization // are assumed to not be used for now. TORCH_INTERNAL_ASSERT( id->getParallelType() != ParallelType::Unroll && !isParallelTypeVectorize(id->getParallelType())); // Use the extent that's extended by halo new_scope = ir_builder.create<kir::ForLoop>( kir_id, id->isBroadcast() ? ir_builder.zeroVal() : ir_builder.create<kir::Int>(c10::nullopt), nullptr, extent_with_halo, nullptr, false, nullptr); } else { new_scope = ir_builder.create<kir::ForLoop>(kir_id); } if (scope != nullptr) { scope->body().insert(0, new_scope); } return new_scope; } } // namespace void LoopNestGenerator::openFor(IterDomain* iter_domain) { if (for_loops_.size() > 0) { const auto new_scope = openForHelper(for_loops_.back(), iter_domain); // for_loop_allocations_.insert({new_scope, 0}); for_loops_.push_back(new_scope); } else { for_loops_.push_back(openForHelper(nullptr, iter_domain)); lowered_exprs_.insert(lowered_exprs_.begin(), for_loops_.back()); } } void LoopNestGenerator::closeFor() { TORCH_INTERNAL_ASSERT(!for_loops_.empty()); for_loops_.pop_back(); } void LoopNestGenerator::pushFront(kir::Expr* expr) { if (for_loops_.size() == 0) { lowered_exprs_.insert(lowered_exprs_.begin(), expr); } else { for_loops_.back()->body().insert(0, expr); } } void LoopNestGenerator::handle(Expr* expr) { const auto gpu_lower = GpuLower::current(); kir::IrBuilder ir_builder(gpu_lower->kernel()); // Check if it's a tensor view expression we need to place in the loop nest // structure if (!ir_utils::isTVOp(expr)) { // Close all the loops, scalar operations cannot be inside for loops based // on expr sorting. while (!for_loops_.empty()) { closeFor(); } pushFront(gpu_lower->lowerExpr(expr)); for (auto out : expr->outputs()) { TORCH_INTERNAL_ASSERT( out->getValType().value() == ValType::Scalar, "Unrecognized output type found in expr ", expr, " cannot lower ", out->getValType().value()); pushFront(ir_builder.create<kir::Allocate>( gpu_lower->lowerValue(out), MemoryType::Local, ir_builder.create<kir::Int>(1))); } return; } TensorView* out_tv = expr->output(0)->as<TensorView>(); // Figure out what the entire loop structure should look like. std::deque<IterDomain*> loop_structure; // Fill the entire loop structure by Looking at each axis // individually in out's domain for (size_t out_i = 0; out_i < out_tv->nDims(); out_i++) { // Note: It is not safe to skip trivial reduction axes as they could be // inlined with other tensor views. This happens in // NVFuserTest.FusionBNRepro_CUDA as of this commit on norm_hack_2_rebased // branch // Look up the concrete ID in the parallel map, not in the loop // map, which also maps non-CA axes. auto concrete_id = gpu_lower->caParallelMap().getConcreteMappedID(out_tv->axis(out_i)); loop_structure.push_back(concrete_id); } auto loop_structure_it = loop_structure.begin(); auto for_loop_it = for_loops_.begin(); auto last_for_loop_matched = for_loops_.begin(); // Match the loop structure with the current for-loops. Reuse // matching loops and close unmatched ones. while (loop_structure_it != loop_structure.end() && for_loop_it != for_loops_.end()) { auto lowered_out_id = gpu_lower->lowerValue(*loop_structure_it)->as<kir::IterDomain>(); // Similar to the above, the parallel map is used rather than the // loop map. Again, non-CA axes should not share loops, so the // parallel map should be used. if (gpu_lower->caParallelMap().areMapped( lowered_out_id, (*for_loop_it)->iter_domain())) { loop_structure_it++; last_for_loop_matched = ++for_loop_it; } else { ++for_loop_it; } } auto n_loops_to_close = std::distance(last_for_loop_matched, for_loops_.end()); TORCH_INTERNAL_ASSERT( n_loops_to_close >= 0 && n_loops_to_close <= (std::ptrdiff_t)for_loops_.size(), "Tried to close an invalid number of loops: ", n_loops_to_close); if (max_close < n_loops_to_close && max_close > 0) { // Figure out where the last for loop matches from out_tv, go until the // max_close loop marked from previous tv's producer domain. Make sure // none of these domains are actually present in current out_tv. If these // loops map to current out_tv, it should be responsible for deciding if // they stay or go, this could result from an invalid compute at topology // on the DAG or bad expression sorting. auto for_loops_it = for_loops_.end() - n_loops_to_close; auto for_loops_it_end = for_loops_.end() - max_close; for (; for_loops_it != for_loops_it_end; for_loops_it++) { TORCH_INTERNAL_ASSERT( std::none_of( loop_structure_it, loop_structure.end(), [&gpu_lower, &for_loops_it](IterDomain* loop_structure_id) { // Check loop structure doesn't map for_loops in for loop map auto id0 = (*for_loops_it)->iter_domain(); auto id1 = gpu_lower->lowerValue(loop_structure_id) ->as<kir::IterDomain>(); return gpu_lower->caLoopMap().areMapped(id0, id1); }), "Invalid loop found to close."); } n_loops_to_close = std::min(n_loops_to_close, max_close); } for (int64_t i_loop_close = 0; i_loop_close < n_loops_to_close; i_loop_close++) { closeFor(); } // Open the remaining needed loops for (; loop_structure_it != loop_structure.end(); ++loop_structure_it) { openFor(*loop_structure_it); } if (out_tv->getMaxProducerPosition() == 0) { max_close = -1; } else { auto produce_at_id = loop_structure[out_tv->getMaxProducerPosition() - 1]; auto max_close_loop = std::find_if( for_loops_.begin(), for_loops_.end(), [&produce_at_id, &gpu_lower](kir::ForLoop* fl) { auto produce_at_lowered_it = gpu_lower->lowerValue(produce_at_id)->as<kir::IterDomain>(); return gpu_lower->caParallelMap().areMapped( produce_at_lowered_it, fl->iter_domain()); }); max_close = std::distance(max_close_loop, for_loops_.end()); max_close = max_close > 0 ? max_close - 1 : max_close; } pushFront(gpu_lower->lowerExpr(expr)); } // Generate the loop nest structure and place it in lowered_exprs_ void LoopNestGenerator::generate(const std::vector<Expr*>& exprs) { TORCH_INTERNAL_ASSERT(lowered_exprs_.empty()); // Process the carefully ordered expressions for (auto it = exprs.rbegin(); it != exprs.rend(); ++it) { handle(*it); } } } // namespace cuda } // namespace fuser } // namespace jit } // namespace torch
34.554656
78
0.673462
sanchitintel
316f7fa87e927b61a192ca89ff949b36a2db3016
5,071
cpp
C++
src/source/TMC2660Stepper.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
336
2018-03-26T13:51:46.000Z
2022-03-21T21:58:47.000Z
src/source/TMC2660Stepper.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
218
2017-07-28T06:13:53.000Z
2022-03-26T16:41:21.000Z
src/source/TMC2660Stepper.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
176
2018-09-11T22:16:27.000Z
2022-03-26T13:04:03.000Z
#include "TMCStepper.h" #include "SW_SPI.h" TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, float RS) : _pinCS(pinCS), Rsense(RS) {} TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, uint16_t pinMOSI, uint16_t pinMISO, uint16_t pinSCK) : _pinCS(pinCS), Rsense(default_RS) { SW_SPIClass *SW_SPI_Obj = new SW_SPIClass(pinMOSI, pinMISO, pinSCK); TMC_SW_SPI = SW_SPI_Obj; } TMC2660Stepper::TMC2660Stepper(uint16_t pinCS, float RS, uint16_t pinMOSI, uint16_t pinMISO, uint16_t pinSCK) : _pinCS(pinCS), Rsense(RS) { SW_SPIClass *SW_SPI_Obj = new SW_SPIClass(pinMOSI, pinMISO, pinSCK); TMC_SW_SPI = SW_SPI_Obj; } void TMC2660Stepper::switchCSpin(bool state) { // Allows for overriding in child class to make use of fast io digitalWrite(_pinCS, state); } uint32_t TMC2660Stepper::read() { uint32_t response = 0UL; uint32_t dummy = ((uint32_t)DRVCONF_register.address<<17) | DRVCONF_register.sr; if (TMC_SW_SPI != nullptr) { switchCSpin(LOW); response |= TMC_SW_SPI->transfer((dummy >> 16) & 0xFF); response <<= 8; response |= TMC_SW_SPI->transfer((dummy >> 8) & 0xFF); response <<= 8; response |= TMC_SW_SPI->transfer(dummy & 0xFF); } else { SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE3)); switchCSpin(LOW); response |= SPI.transfer((dummy >> 16) & 0xFF); response <<= 8; response |= SPI.transfer((dummy >> 8) & 0xFF); response <<= 8; response |= SPI.transfer(dummy & 0xFF); SPI.endTransaction(); } switchCSpin(HIGH); return response >> 4; } void TMC2660Stepper::write(uint8_t addressByte, uint32_t config) { uint32_t data = (uint32_t)addressByte<<17 | config; if (TMC_SW_SPI != nullptr) { switchCSpin(LOW); TMC_SW_SPI->transfer((data >> 16) & 0xFF); TMC_SW_SPI->transfer((data >> 8) & 0xFF); TMC_SW_SPI->transfer(data & 0xFF); } else { SPI.beginTransaction(SPISettings(spi_speed, MSBFIRST, SPI_MODE3)); switchCSpin(LOW); SPI.transfer((data >> 16) & 0xFF); SPI.transfer((data >> 8) & 0xFF); SPI.transfer(data & 0xFF); SPI.endTransaction(); } switchCSpin(HIGH); } void TMC2660Stepper::begin() { //set pins pinMode(_pinCS, OUTPUT); switchCSpin(HIGH); //TODO: Push shadow registers toff(8); //off_time(8); tbl(1); //blank_time(24); } bool TMC2660Stepper::isEnabled() { return toff() > 0; } uint8_t TMC2660Stepper::test_connection() { uint32_t drv_status = DRVSTATUS(); switch (drv_status) { case 0xFFCFF: return 1; case 0: return 2; default: return 0; } } /* Requested current = mA = I_rms/1000 Equation for current: I_rms = (CS+1)/32 * V_fs/R_sense * 1/sqrt(2) Solve for CS -> CS = 32*sqrt(2)*I_rms*R_sense/V_fs - 1 Example: vsense = 0b0 -> V_fs = 0.310V //Typical mA = 1650mA = I_rms/1000 = 1.65A R_sense = 0.100 Ohm -> CS = 32*sqrt(2)*1.65*0.100/0.310 - 1 = 24,09 CS = 24 */ uint16_t TMC2660Stepper::cs2rms(uint8_t CS) { return (float)(CS+1)/32.0 * (vsense() ? 0.165 : 0.310)/(Rsense+0.02) / 1.41421 * 1000; } uint16_t TMC2660Stepper::rms_current() { return cs2rms(cs()); } void TMC2660Stepper::rms_current(uint16_t mA) { uint8_t CS = 32.0*1.41421*mA/1000.0*Rsense/0.310 - 1; // If Current Scale is too low, turn on high sensitivity R_sense and calculate again if (CS < 16) { vsense(true); CS = 32.0*1.41421*mA/1000.0*Rsense/0.165 - 1; } else { // If CS >= 16, turn off high_sense_r vsense(false); } if (CS > 31) CS = 31; cs(CS); //val_mA = mA; } void TMC2660Stepper::push() { DRVCTRL( sdoff() ? DRVCTRL_1_register.sr : DRVCTRL_0_register.sr); CHOPCONF(CHOPCONF_register.sr); SMARTEN(SMARTEN_register.sr); SGCSCONF(SGCSCONF_register.sr); DRVCONF(DRVCONF_register.sr); } void TMC2660Stepper::hysteresis_end(int8_t value) { hend(value+3); } int8_t TMC2660Stepper::hysteresis_end() { return hend()-3; }; void TMC2660Stepper::hysteresis_start(uint8_t value) { hstrt(value-1); } uint8_t TMC2660Stepper::hysteresis_start() { return hstrt()+1; } void TMC2660Stepper::microsteps(uint16_t ms) { switch(ms) { case 256: mres(0); break; case 128: mres(1); break; case 64: mres(2); break; case 32: mres(3); break; case 16: mres(4); break; case 8: mres(5); break; case 4: mres(6); break; case 2: mres(7); break; case 0: mres(8); break; default: break; } } uint16_t TMC2660Stepper::microsteps() { switch(mres()) { case 0: return 256; case 1: return 128; case 2: return 64; case 3: return 32; case 4: return 16; case 5: return 8; case 6: return 4; case 7: return 2; case 8: return 0; } return 0; } void TMC2660Stepper::blank_time(uint8_t value) { switch (value) { case 16: tbl(0b00); break; case 24: tbl(0b01); break; case 36: tbl(0b10); break; case 54: tbl(0b11); break; } } uint8_t TMC2660Stepper::blank_time() { switch (tbl()) { case 0b00: return 16; case 0b01: return 24; case 0b10: return 36; case 0b11: return 54; } return 0; }
25.872449
111
0.649576
ManuelMcLure
31716dc44479baf6e425aa2d736e7ba7ce0731b8
2,504
cpp
C++
decorator.cpp
retorillo/twitter-header
f00aa4899f6e2ebbbea68566c7e1329663faf966
[ "MIT" ]
null
null
null
decorator.cpp
retorillo/twitter-header
f00aa4899f6e2ebbbea68566c7e1329663faf966
[ "MIT" ]
null
null
null
decorator.cpp
retorillo/twitter-header
f00aa4899f6e2ebbbea68566c7e1329663faf966
[ "MIT" ]
null
null
null
#include "decorator.h" int main(int argc, char** argv) { if (!PeekNamedPipe(GetStdHandle(STD_INPUT_HANDLE), NULL, NULL, NULL, NULL, NULL)) { printf("error: no piping input\n"); return -1; } std::ostringstream figletout; char buf[256]; while (fgets(buf, sizeof(buf), stdin)) figletout << buf; std::string figlet = figletout.str(); auto parseint = [](const char* str) { // TODO: throws format error return std::atoi(str); }; int optc; int mode = 0; int padl = 0, padr = 0, padt = 0, padb = 0; while ((optc = getopt(argc, argv, "m:l:r:t:b:")) != -1) { switch (optc) { case 'm': mode = parseint(optarg); break; case 'l': padl = parseint(optarg); break; case 'r': padr = parseint(optarg); break; case 't': padt = parseint(optarg); break; case 'b': padb = parseint(optarg); break; } } enum mode_t { mode_mixed = 0, mode_figlet = 1, mode_background = 2, }; int maxw = 0; for (auto l : lines(figlet)) maxw = std::max(maxw, (int)l.size()); std::string randomstr = "0123456789ABCDEF"; std::random_device rdev; auto getch = [mode, &rdev, &randomstr]() { if (mode == mode_figlet) return std::string(" "); auto min = std::random_device::min(), max = std::random_device::max(); double r = static_cast<double>(rdev() - min) / (max - min); return randomstr.substr(round(r * (randomstr.size() - 1)), 1); }; auto padvert = [maxw, padl, padr, getch](int h) { int w = maxw + padl + padr; for (int c = 0; c < h * w; c++) printf(c > 0 && (c + 1) % w == 0 ? "%s\n" : "%s", getch().c_str()); }; padvert(padt); for (auto l : lines(figlet)) { for (int c = -padl; c < maxw + padr; c++) { if (c < 0 || c >= l.size()) { printf(getch().c_str()); } else { if (l[c] == 0x20) printf(getch().c_str()); else printf(mode == mode_background ? " " : l.substr(c, 1).c_str()); } } printf("\n"); } padvert(padb); return 0; } std::vector<std::string> lines(std::string str) { std::regex r("\\r?\\n"); std::string norm = std::regex_replace(str, r, "\n", std::regex_constants::match_any); std::ostringstream ostr; std::vector<std::string> vec; auto push = [&vec, &ostr]() { if (ostr.str().size() > 0) vec.push_back(ostr.str()); ostr.str(""); }; for (int c = 0; c < norm.size(); c++) { if (norm[c] == '\n') push(); else ostr << norm[c]; } push(); return vec; }
28.781609
87
0.545927
retorillo
317eb30a5430c2b6b4f38957885c41795d17e487
3,718
hpp
C++
src/stdplus/fd/ops.hpp
pzh2386034/stdplus
9148977c89406ee3b096dc5a3bd9e8f22abb7764
[ "Apache-2.0" ]
4
2018-11-05T10:44:47.000Z
2020-11-20T08:16:15.000Z
src/stdplus/fd/ops.hpp
pzh2386034/stdplus
9148977c89406ee3b096dc5a3bd9e8f22abb7764
[ "Apache-2.0" ]
1
2020-11-18T22:40:50.000Z
2020-11-19T16:14:18.000Z
src/stdplus/fd/ops.hpp
pzh2386034/stdplus
9148977c89406ee3b096dc5a3bd9e8f22abb7764
[ "Apache-2.0" ]
2
2018-11-05T10:44:35.000Z
2022-01-14T01:47:39.000Z
#pragma once #include <stdplus/fd/intf.hpp> #include <stdplus/raw.hpp> #include <stdplus/types.hpp> #include <utility> namespace stdplus { namespace fd { namespace detail { void readExact(Fd& fd, span<std::byte> data); void recvExact(Fd& fd, span<std::byte> data, RecvFlags flags); void writeExact(Fd& fd, span<const std::byte> data); void sendExact(Fd& fd, span<const std::byte> data, SendFlags flags); span<std::byte> readAligned(Fd& fd, size_t align, span<std::byte> buf); span<std::byte> recvAligned(Fd& fd, size_t align, span<std::byte> buf, RecvFlags flags); span<const std::byte> writeAligned(Fd& fd, size_t align, span<const std::byte> data); span<const std::byte> sendAligned(Fd& fd, size_t align, span<const std::byte> data, SendFlags flags); template <typename Fun, typename Container, typename... Args> auto alignedOp(Fun&& fun, Fd& fd, Container&& c, Args&&... args) { using Data = raw::detail::dataType<Container>; auto ret = fun(fd, sizeof(Data), raw::asSpan<std::byte>(c), std::forward<Args>(args)...); return span<Data>(std::begin(c), ret.size() / sizeof(Data)); } } // namespace detail template <typename Container> inline auto read(Fd& fd, Container&& c) { return detail::alignedOp(detail::readAligned, fd, std::forward<Container>(c)); } template <typename Container> inline auto recv(Fd& fd, Container&& c, RecvFlags flags) { return detail::alignedOp(detail::recvAligned, fd, std::forward<Container>(c), flags); } template <typename Container> inline auto write(Fd& fd, Container&& c) { return detail::alignedOp(detail::writeAligned, fd, std::forward<Container>(c)); } template <typename Container> inline auto send(Fd& fd, Container&& c, SendFlags flags) { return detail::alignedOp(detail::sendAligned, fd, std::forward<Container>(c), flags); } template <typename T> inline void readExact(Fd& fd, T&& t) { detail::readExact(fd, raw::asSpan<std::byte>(t)); } template <typename T> inline void recvExact(Fd& fd, T&& t, RecvFlags flags) { detail::recvExact(fd, raw::asSpan<std::byte>(t), flags); } template <typename T> inline void writeExact(Fd& fd, T&& t) { detail::writeExact(fd, raw::asSpan<std::byte>(t)); } template <typename T> inline void sendExact(Fd& fd, T&& t, SendFlags flags) { detail::sendExact(fd, raw::asSpan<std::byte>(t), flags); } inline size_t lseek(Fd& fd, off_t offset, Whence whence) { return fd.lseek(offset, whence); } inline void truncate(Fd& fd, off_t size) { return fd.truncate(size); } template <typename SockAddr> inline void bind(Fd& fd, SockAddr&& sockaddr) { return fd.bind(raw::asSpan<std::byte>(sockaddr)); } template <typename Opt> inline void setsockopt(Fd& fd, SockLevel level, SockOpt optname, Opt&& opt) { return fd.setsockopt(level, optname, raw::asSpan<std::byte>(opt)); } template <typename Data> inline int constIoctl(const Fd& fd, unsigned long id, Data&& data) { return fd.constIoctl(id, raw::asSpan<std::byte>(data).data()); } template <typename Data> inline int ioctl(Fd& fd, unsigned long id, Data&& data) { return fd.ioctl(id, raw::asSpan<std::byte>(data).data()); } inline FdFlags getFdFlags(const Fd& fd) { return fd.fcntlGetfd(); } inline void setFdFlags(Fd& fd, FdFlags flags) { return fd.fcntlSetfd(flags); } inline FileFlags getFileFlags(const Fd& fd) { return fd.fcntlGetfl(); } inline void setFileFlags(Fd& fd, FileFlags flags) { return fd.fcntlSetfl(flags); } } // namespace fd } // namespace stdplus
25.465753
79
0.653846
pzh2386034
317faaa00b1b6a123534476f089e762e2bddba9d
4,257
cpp
C++
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/search/ConjunctionScorer.cpp
zaubara/BRFullTextSearch
e742f223a1c203eacb576711dd57b1187aee3deb
[ "Apache-2.0" ]
151
2015-01-17T06:29:38.000Z
2022-02-17T11:27:38.000Z
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/search/ConjunctionScorer.cpp
yonglam/BRFullTextSearch
e742f223a1c203eacb576711dd57b1187aee3deb
[ "Apache-2.0" ]
28
2015-03-01T20:14:42.000Z
2019-07-22T09:23:54.000Z
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/search/ConjunctionScorer.cpp
yonglam/BRFullTextSearch
e742f223a1c203eacb576711dd57b1187aee3deb
[ "Apache-2.0" ]
28
2015-03-05T13:24:12.000Z
2022-03-26T09:16:29.000Z
/*------------------------------------------------------------------------------ * Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. ------------------------------------------------------------------------------*/ #include "CLucene/_ApiHeader.h" #include "_ConjunctionScorer.h" #include "Similarity.h" #include "CLucene/util/_Arrays.h" #include <assert.h> #include <algorithm> CL_NS_USE(index) CL_NS_USE(util) CL_NS_DEF(search) ConjunctionScorer::ConjunctionScorer(Similarity* similarity, ScorersType* _scorers): Scorer(similarity), firstTime(true), more(false), coord(0.0), lastDoc(-1) { this->scorers = _CLNEW CL_NS(util)::ObjectArray<Scorer>(_scorers->size()); _scorers->toArray(this->scorers->values); coord = getSimilarity()->coord(this->scorers->length, this->scorers->length); } ConjunctionScorer::ConjunctionScorer(Similarity* similarity, const CL_NS(util)::ArrayBase<Scorer*>* _scorers): Scorer(similarity), firstTime(true), more(false), coord(0.0), lastDoc(-1) { this->scorers = _CLNEW CL_NS(util)::ObjectArray<Scorer>(_scorers->length); memcpy(this->scorers->values, _scorers->values, _scorers->length * sizeof(Scorer*)); coord = getSimilarity()->coord(this->scorers->length, this->scorers->length); } ConjunctionScorer::~ConjunctionScorer(){ _CLLDELETE(scorers); } TCHAR* ConjunctionScorer::toString(){ return stringDuplicate(_T("ConjunctionScorer")); } int32_t ConjunctionScorer::doc() const{ return lastDoc; } bool ConjunctionScorer::next() { if (firstTime) { init(0); } else if (more) { more = scorers->values[(scorers->length-1)]->next(); } return doNext(); } bool ConjunctionScorer::doNext() { int32_t first=0; Scorer* lastScorer = scorers->values[scorers->length-1]; Scorer* firstScorer; while (more && (firstScorer=scorers->values[first])->doc() < (lastDoc=lastScorer->doc())) { more = firstScorer->skipTo(lastDoc); lastScorer = firstScorer; first = (first == (scorers->length-1)) ? 0 : first+1; } return more; } bool ConjunctionScorer::skipTo(int32_t target) { if (firstTime) return init(target); else if (more) more = scorers->values[(scorers->length-1)]->skipTo(target); return doNext(); } int ConjunctionScorer_sort(const void* _elem1, const void* _elem2){ const Scorer* elem1 = *(const Scorer**)_elem1; const Scorer* elem2 = *(const Scorer**)_elem2; return elem1->doc() - elem2->doc(); } bool ConjunctionScorer::init(int32_t target) { firstTime = false; more = scorers->length>1; for (size_t i=0; i<scorers->length; i++) { more = target==0 ? scorers->values[i]->next() : scorers->values[i]->skipTo(target); if (!more) return false; } // Sort the array the first time... // We don't need to sort the array in any future calls because we know // it will already start off sorted (all scorers on same doc). // note that this comparator is not consistent with equals! qsort(scorers->values,scorers->length, sizeof(Scorer*), ConjunctionScorer_sort); doNext(); // If first-time skip distance is any predictor of // scorer sparseness, then we should always try to skip first on // those scorers. // Keep last scorer in it's last place (it will be the first // to be skipped on), but reverse all of the others so that // they will be skipped on in order of original high skip. int32_t end=(scorers->length-1)-1; for (int32_t i=0; i<(end>>1); i++) { Scorer* tmp = scorers->values[i]; scorers->values[i] = scorers->values[end-i]; scorers->values[end-i] = tmp; } return more; } float_t ConjunctionScorer::score(){ float_t sum = 0.0f; for (size_t i = 0; i < scorers->length; i++) { sum += scorers->values[i]->score(); } return sum * coord; } Explanation* ConjunctionScorer::explain(int32_t /*doc*/) { _CLTHROWA(CL_ERR_UnsupportedOperation,"UnsupportedOperationException: ConjunctionScorer::explain"); } CL_NS_END
31.768657
112
0.641532
zaubara
318264bec727bd0aa42e12064c31a73c586f8470
225
hpp
C++
include/pykebc/code.hpp
kodo-pp/pykebc-vm
a8428fff0c4bba0e41ef8992e135d4122b862692
[ "Apache-2.0" ]
null
null
null
include/pykebc/code.hpp
kodo-pp/pykebc-vm
a8428fff0c4bba0e41ef8992e135d4122b862692
[ "Apache-2.0" ]
null
null
null
include/pykebc/code.hpp
kodo-pp/pykebc-vm
a8428fff0c4bba0e41ef8992e135d4122b862692
[ "Apache-2.0" ]
null
null
null
#pragma once #include <pykebc/object.hpp> #include <cstdint> #include <vector> namespace pykebc::code { struct Code { std::vector<uint32_t> instructions; std::vector<Object*> constants; }; } // namespace pykebc
11.842105
39
0.693333
kodo-pp
31862c317577bdfcae93770f62f5e108f41bf31c
89,640
cpp
C++
Commands.cpp
UKTailwind/MMB4W
cda50487f2ce23ea1b2a8da79b7b38be46cdece2
[ "Unlicense" ]
3
2022-02-20T11:32:27.000Z
2022-03-02T21:22:50.000Z
Commands.cpp
UKTailwind/MMB4W
cda50487f2ce23ea1b2a8da79b7b38be46cdece2
[ "Unlicense" ]
null
null
null
Commands.cpp
UKTailwind/MMB4W
cda50487f2ce23ea1b2a8da79b7b38be46cdece2
[ "Unlicense" ]
null
null
null
/*********************************************************************************************************************** MMBasic for Windows Commands.cpp <COPYRIGHT HOLDERS> Geoff Graham, Peter Mather Copyright (c) 2021, <COPYRIGHT HOLDERS> 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. The name MMBasic be used when referring to the interpreter in any documentation and promotional material and the original copyright message be displayed on the console at startup (additional copyright messages may be added). 4. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the <copyright holder>. 5. Neither the name of the <copyright holder> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDERS> AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDERS> 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 "olcPixelGameEngine.h" #include "MainThread.h" #include "MMBasic_Includes.h" #include <math.h> void flist(int, int, int); //void clearprog(void); void ListNewLine(int* ListCnt, int all); void ListProgramFlash(unsigned char* p, int all); char MMErrMsg[MAXERRMSG]; // the error message unsigned char* KeyInterrupt = NULL; volatile int Keycomplete = 0; int keyselect = 0; char runcmd[STRINGSIZE] = { 0 }; // stack to keep track of nested FOR/NEXT loops struct s_forstack forstack[MAXFORLOOPS + 1]; int forindex; // stack to keep track of nested DO/LOOP loops struct s_dostack dostack[MAXDOLOOPS]; int doindex; // counts the number of nested DO/LOOP loops // stack to keep track of GOSUBs, SUBs and FUNCTIONs unsigned char* gosubstack[MAXGOSUB]; unsigned char* errorstack[MAXGOSUB]; int gosubindex; unsigned char DimUsed = false; // used to catch OPTION BASE after DIM has been used int TraceOn; // used to track the state of TRON/TROFF unsigned char* TraceBuff[TRACE_BUFF_SIZE]; int TraceBuffIndex; // used for listing the contents of the trace buffer int OptionErrorSkip=0; // how to handle an error int MMerrno=0; // the error number int ListCnt; sa_data datastore[MAXRESTORE]; int restorepointer = 0; const unsigned int CaseOption = 0xffffffff; // used to store the case of the listed output void cmd_null(void) { // do nothing (this is just a placeholder for commands that have no action) } // utility routine used by DoDim() below and other places in the interpreter // checks if the type has been explicitly specified as in DIM FLOAT A, B, ... etc extern "C" unsigned char* CheckIfTypeSpecified(unsigned char* p, int* type, int AllowDefaultType) { unsigned char* tp; if((tp = checkstring(p, (unsigned char*)"INTEGER")) != NULL) *type = T_INT | T_IMPLIED; else if((tp = checkstring(p, (unsigned char*)"STRING")) != NULL) *type = T_STR | T_IMPLIED; else if((tp = checkstring(p, (unsigned char*)"FLOAT")) != NULL) *type = T_NBR | T_IMPLIED; else { if(!AllowDefaultType) error((char *)"Variable type"); tp = p; *type = DefaultType; // if the type is not specified use the default } return tp; } void execute_one_command(unsigned char* p) { int cmd, i; CheckAbort(); targ = T_CMD; skipspace(p); // skip any whitespace if(*p >= C_BASETOKEN && *p - C_BASETOKEN < CommandTableSize - 1 && (commandtbl[*p - C_BASETOKEN].type & T_CMD)) { cmd = *p - C_BASETOKEN; if(*p == cmdWHILE || *p == cmdDO || *p == cmdFOR) error((char*)"Invalid inside THEN ... ELSE"); cmdtoken = *p; cmdline = p + 1; skipspace(cmdline); commandtbl[cmd].fptr(); // execute the command } else { if(!isnamestart(*p)) error((char*)"Invalid character"); i = FindSubFun(p, false); // it could be a defined command if(i >= 0) // >= 0 means it is a user defined command DefinedSubFun(false, p, i, NULL, NULL, NULL, NULL); else error((char*)"Unknown command"); } ClearTempMemory(); // at the end of each command we need to clear any temporary string vars } void cmd_quit(void) { SystemMode = MODE_QUIT; } void cmd_inc(void) { unsigned char* p, *q; int vtype; getargs(&cmdline, 3, (unsigned char *)","); if(argc == 1) { p = (unsigned char *)findvar(argv[0], V_FIND); if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); vtype = TypeMask(vartbl[VarIndex].type); if(vtype & T_STR) error((char *)"Invalid variable"); // sanity check if(vtype & T_NBR) (*(MMFLOAT*)p) = (*(MMFLOAT*)p) + 1.0; else if(vtype & T_INT)*(long long int*)p = *(long long int*)p + 1; else error((char *)"Syntax"); } else { p = (unsigned char*)findvar(argv[0], V_FIND); if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); vtype = TypeMask(vartbl[VarIndex].type); if(vtype & T_STR) { q = getstring(argv[2]); if (*p + *q > MAXSTRLEN) error((char*)"String too long"); Mstrcat(p, q); } else if(vtype & T_NBR) { (*(MMFLOAT*)p) = (*(MMFLOAT*)p) + getnumber(argv[2]); } else if(vtype & T_INT) { *(long long int*)p = *(long long int*)p + getinteger(argv[2]); } else error((char *)"syntax"); } } // the PRINT command void cmd_print(void) { unsigned char* s, * p; unsigned char* ss; MMFLOAT f; long long int i64; int i, t, fnbr; int docrlf; // this is used to suppress the cr/lf if needed getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)";,"); // this is a macro and must be the first executable stmt // s = 0; *s = 56; // for testing the exception handler docrlf = true; if(argc > 0 && *argv[0] == '#') { // check if the first arg is a file number argv[0]++; if((*argv[0] == 'G') || (*argv[0] == 'g')) { argv[0]++; if(!((*argv[0] == 'P') || (*argv[0] == 'p')))error((char *)"Syntax"); argv[0]++; if(!((*argv[0] == 'S') || (*argv[0] == 's')))error((char *)"Syntax"); if(!GPSchannel) error((char *)"GPS not activated"); if(argc != 3) error((char *)"Only a single string parameter allowed"); p = argv[2]; t = T_NOTYPE; p = evaluate(p, &f, &i64, &s, &t, true); // get the value and type of the argument ss = (unsigned char*)s; if(!(t & T_STR)) error((char *)"Only a single string parameter allowed"); int i, xsum = 0; if(ss[1] != '$' || ss[ss[0]] != '*')error((char *)"GPS command must start with dollar and end with star"); for (i = 1; i <= ss[0]; i++) { SerialPutchar(GPSchannel, s[i]); if(s[i] == '$')xsum = 0; if(s[i] != '*')xsum ^= s[i]; } i = xsum / 16; i = i + '0'; if(i > '9')i = i - '0' + 'A'; SerialPutchar(GPSchannel, i); i = xsum % 16; i = i + '0'; if(i > '9')i = i - '0' + 'A'; SerialPutchar(GPSchannel, i); SerialPutchar(GPSchannel, 13); SerialPutchar(GPSchannel, 10); return; } else { fnbr = (int)getinteger(argv[0]); // get the number i = 1; if(argc >= 2 && *argv[1] == ',') i = 2; // and set the next argument to be looked at } } else { fnbr = 0; // no file number so default to the standard output i = 0; } if (argc >= 3) { if (checkstring(argv[2], (unsigned char*)"BREAK")) { if (FileTable[fnbr].com == 0 || FileTable[fnbr].com > MAXCOMPORTS)error((char*)"Syntax"); SendBreak(fnbr); return; } } for (; i < argc; i++) { // step through the arguments if(*argv[i] == ',') { MMfputc('\t', fnbr); // print a tab for a comma docrlf = false; // a trailing comma should suppress CR/LF } else if(*argv[i] == ';') { docrlf = false; // other than suppress cr/lf do nothing for a semicolon } else { // we have a normal expression p = argv[i]; while (*p) { t = T_NOTYPE; p = evaluate(p, &f, &i64, &s, &t, true); // get the value and type of the argument if(t & T_NBR) { *inpbuf = ' '; // preload a space FloatToStr((char *)(inpbuf + ((f >= 0) ? 1 : 0)), f, 0, STR_AUTO_PRECISION, ' ');// if positive output a space instead of the sign MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output } else if(t & T_INT) { *inpbuf = ' '; // preload a space IntToStr((char *)(inpbuf + ((i64 >= 0) ? 1 : 0)), i64, 10); // if positive output a space instead of the sign MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output } else if(t & T_STR) { MMfputs((unsigned char*)s, fnbr); // print if a string (s is a MMBasic string) } else error((char *)"Attempt to print reserved word"); } docrlf = true; } } if(docrlf) MMfputs((unsigned char*)"\2\r\n", fnbr); // print the terminating cr/lf unless it has been suppressed PrintPixelMode = 0; } void cmd_debug(void) { unsigned char* s, * p; MMFLOAT f; long long int i64; int i, t, fnbr; int docrlf; // this is used to suppress the cr/lf if needed getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)";,"); // this is a macro and must be the first executable stmt // s = 0; *s = 56; // for testing the exception handler docrlf = true; { fnbr = 99999; // no file number so default to the standard output i = 0; } for (; i < argc; i++) { // step through the arguments if (*argv[i] == ',') { MMfputc('\t', fnbr); // print a tab for a comma docrlf = false; // a trailing comma should suppress CR/LF } else if (*argv[i] == ';') { docrlf = false; // other than suppress cr/lf do nothing for a semicolon } else { // we have a normal expression p = argv[i]; while (*p) { t = T_NOTYPE; p = evaluate(p, &f, &i64, &s, &t, true); // get the value and type of the argument if (t & T_NBR) { *inpbuf = ' '; // preload a space FloatToStr((char*)(inpbuf + ((f >= 0) ? 1 : 0)), f, 0, STR_AUTO_PRECISION, ' ');// if positive output a space instead of the sign MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output } else if (t & T_INT) { *inpbuf = ' '; // preload a space IntToStr((char*)(inpbuf + ((i64 >= 0) ? 1 : 0)), i64, 10); // if positive output a space instead of the sign MMfputs((unsigned char*)CtoM(inpbuf), fnbr); // convert to a MMBasic string and output } else if (t & T_STR) { MMfputs((unsigned char*)s, fnbr); // print if a string (s is a MMBasic string) } else error((char*)"Attempt to print reserved word"); } docrlf = true; } } if (docrlf) MMfputs((unsigned char*)"\2\r\n", fnbr); // print the terminating cr/lf unless it has been suppressed PrintPixelMode = 0; } // the LET command // because the LET is implied (ie, line does not have a recognisable command) // it ends up as the place where mistyped commands are discovered. This is why // the error message is "Unknown command" void cmd_let(void) { int t, size; MMFLOAT f; long long int i64; unsigned char* s; unsigned char* p1, *p2; p1 = cmdline; // search through the line looking for the equals sign while (*p1 && tokenfunction(*p1) != op_equal) p1++; if(!*p1) error((char *)"Unknown command"); // check that we have a straight forward variable p2 = skipvar(cmdline, false); skipspace(p2); if(p1 != p2) error((char *)"Syntax"); // create the variable and get the length if it is a string p2 = (unsigned char *)findvar(cmdline, V_FIND); size = vartbl[VarIndex].size; if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); // step over the equals sign, evaluate the rest of the command and save in the variable p1++; if(vartbl[VarIndex].type & T_STR) { t = T_STR; p1 = evaluate(p1, &f, &i64, &s, &t, false); if(*s > size) error((char *)"String too long"); Mstrcpy(p2, s); } else if(vartbl[VarIndex].type & T_NBR) { t = T_NBR; p1 = evaluate(p1, &f, &i64, &s, &t, false); if(t & T_NBR) (*(MMFLOAT*)p2) = f; else (*(MMFLOAT*)p2) = (MMFLOAT)i64; } else { t = T_INT; p1 = evaluate(p1, &f, &i64, &s, &t, false); if(t & T_INT) (*(long long int*)p2) = i64; else (*(long long int*)p2) = FloatToInt64(f); } checkend(p1); } int as_strcmpi(const char* s1, const char* s2) { const unsigned char* p1 = (const unsigned char*)s1; const unsigned char* p2 = (const unsigned char*)s2; unsigned char c1, c2; if(p1 == p2) return 0; do { c1 = tolower(*p1++); c2 = tolower(*p2++); if(c1 == '\0') break; } while (c1 == c2); return c1 - c2; } void sortStrings(char** arr, int n) { char temp[16]; int i, j; // Sorting strings using bubble sort for (j = 0; j < n - 1; j++) { for (i = j + 1; i < n; i++) { if(as_strcmpi(arr[j], arr[i]) > 0) { strcpy(temp, arr[j]); strcpy(arr[j], arr[i]); strcpy(arr[i], temp); } } } } void sortPorts(char** arr, int n) { char temp[16]; int i, j; // Sorting strings using bubble sort for (j = 0; j < n - 1; j++) { for (i = j + 1; i < n; i++) { char** c=NULL; int a = strtol((const char *) & arr[j][3], c, 10); int b = strtol((const char*)&arr[i][3], c, 10); if (a>b) { strcpy(temp, arr[j]); strcpy(arr[j], arr[i]); strcpy(arr[i], temp); } } } } void ListFile(char* pp, int all) { /****** char buff[STRINGSIZE]; FRESULT fr; FILINFO fno; int fnbr; int i, ListCnt = 1; fr = f_stat(pp, &fno); if(fr == FR_OK && !(fno.fattrib & AM_DIR)) { fnbr = FindFreeFileNbr(); if(!BasicFileOpen(pp, fnbr, FA_READ)) return; while (!FileEOF(fnbr)) { // while waiting for the end of file memset(buff, 0, 256); MMgetline(fnbr, (char*)buff); // get the input line for (i = 0; i < strlen(buff); i++)if(buff[i] == TAB) buff[i] = ' '; MMPrintString(buff); ListCnt += strlen(buff) / OptionWidth; ListNewLine(&ListCnt, all); } FileClose(fnbr); } else error((char *)"File not found");*/ } void QueryKey(HKEY hKey) { LPSTR achKey=(LPSTR)GetTempMemory(STRINGSIZE); // buffer for subkey name TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name DWORD cchClassName = MAX_PATH; // size of class string DWORD cSubKeys = 0; // number of subkeys DWORD cbMaxSubKey; // longest subkey size DWORD cchMaxClass; // longest class string DWORD cValues; // number of values for key DWORD cchMaxValue; // longest value name DWORD cbMaxValueData; // longest value data DWORD cbSecurityDescriptor; // size of security descriptor FILETIME ftLastWriteTime; // last write time DWORD i, retCode; DWORD cchValue = 255; // Get the class name and the value count. retCode = RegQueryInfoKey( hKey, // key handle achClass, // buffer for class name &cchClassName, // size of class string NULL, // reserved &cSubKeys, // number of subkeys &cbMaxSubKey, // longest subkey size &cchMaxClass, // longest class string &cValues, // number of values for this key &cchMaxValue, // longest value name &cbMaxValueData, // longest value data &cbSecurityDescriptor, // security descriptor &ftLastWriteTime); // last write time // Enumerate the subkeys, until RegEnumKeyEx fails. // Enumerate the key values. if (cValues>0 && cValues<=128 && retCode== ERROR_SUCCESS) { char** c = (char**)GetTempMemory((cValues) * sizeof(*c) + (cValues) *(cchMaxValue + 1)); MMPrintString((char *)"Number of com ports : "); PInt(cValues); PRet(); char *b = (char *)GetTempMemory(cbMaxValueData+1); LPSTR achValue = (LPSTR)GetTempMemory(cchMaxValue+1); DWORD fred= cbMaxValueData+1; for (i = 0, retCode = ERROR_SUCCESS; i < cValues; i++) { cchValue = 255; achValue[0] = '\0'; memset(b,0, cbMaxValueData + 1); fred = cbMaxValueData + 1; retCode = RegEnumValueA(hKey, i, achValue, &cchValue, NULL, NULL, (LPBYTE)b, &fred); if (retCode == ERROR_SUCCESS) { c[i] = (char*)((int)c + sizeof(char*) * (cValues) + i * (cchMaxValue + 1)); strcpy(c[i], b); } } sortPorts(c, cValues); for (int j = 0; j < (int)cValues; j++) { MMPrintString(c[j]); PRet(); } } } void cmd_list(void) { unsigned char* p; int i, j, k, m, step; if((p = checkstring(cmdline, (unsigned char*)"ALL"))) { if(!(*p == 0 || *p == '\'')) { getargs(&p, 1, (unsigned char *)","); char* buff = (char *)GetTempMemory(STRINGSIZE); strcpy(buff, (const char *)getCstring(argv[0])); if(strchr(buff, '.') == NULL) strcat(buff, ".BAS"); ListProgram((unsigned char*)buff, true); } else { ListProgram(NULL, true); checkend(p); } } else if ((p = checkstring(cmdline, (unsigned char*)"FLASH"))) { ListProgramFlash((unsigned char*)ProgMemory, false); checkend(p); } else if (p = checkstring(cmdline, (unsigned char *)"PAGES")) { PO("MODE ", 3); MMPrintString((char*)" has "); PInt(MAXPAGES+1); MMPrintString((char*)" pages\r\n"); MMPrintString((char*)"Page no. Page Address Width Height Size "); PRet(); for (int i = 0; i <= MAXPAGES; i++) { MMPrintString((char*)" "); if (i < 10)MMPrintString((char*)" "); PInt(i); MMPrintString((char *)" &H"); PIntH((uint32_t)PageTable[i].address); if (PageTable[i].xmax < 1000)MMPrintString((char*)" "); else MMPrintString((char*)" "); PInt((uint32_t)PageTable[i].xmax); MMPrintString((char*)" "); PInt((uint32_t)PageTable[i].ymax); if (PageTable[i].size < 0xFFFF)MMPrintString((char*)" "); MMPrintString((char*)" &H"); PIntH((uint32_t)PageTable[i].size); PRet(); } } else if ((p = checkstring(cmdline, (unsigned char*)"COM PORTS"))) { HKEY hregkey; LSTATUS res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, KEY_READ, &hregkey); QueryKey(hregkey); RegCloseKey((HKEY)hregkey); } else if ((p = checkstring(cmdline, (unsigned char*)"FILE ALL"))) { getargs(&p, 1, (unsigned char*)","); char* buff = (char*)GetTempMemory(STRINGSIZE); strcpy(buff, (char*)getCstring(argv[0])); if (strchr(buff, '.') == NULL) strcat(buff, ".BAS"); ListProgram((unsigned char*)buff, true); } else if ((p = checkstring(cmdline, (unsigned char*)"FILE"))) { getargs(&p, 1, (unsigned char *)","); char* buff = (char *)GetTempMemory(STRINGSIZE); strcpy(buff, (char *)getCstring(argv[0])); if (strchr(buff, '.') == NULL) strcat(buff, ".BAS"); ListProgram((unsigned char *)buff, false); } else if ((p = checkstring(cmdline, (unsigned char*)"COMMANDS"))) { step = OptionWidth/18; m = 0; char** c = (char **)GetTempMemory((CommandTableSize + 5) * sizeof(*c) + (CommandTableSize + 5) * 18); for (i = 0; i < CommandTableSize + 5; i++) { c[m] = (char*)((int)c + sizeof(char*) * (CommandTableSize + 5) + m * 18); if(m < CommandTableSize)strcpy(c[m], (const char *)commandtbl[i].name); else if(m == CommandTableSize)strcpy(c[m], "Color"); else if(m == CommandTableSize + 1)strcpy(c[m], "Else If"); else if(m == CommandTableSize + 2)strcpy(c[m], "End If"); else if(m == CommandTableSize + 3)strcpy(c[m], "Exit Do"); else strcpy(c[m], "Cat"); if(strcasecmp(c[m],"CSub")!=0 && strcasecmp(c[m], "End CSub") != 0)m++; } sortStrings(c, m); for (i = 1; i < m; i += step) { for (k = 0; k < step; k++) { if(i + k < m) { MMPrintString(c[i + k]); if(k != (step - 1))for (j = strlen(c[i + k]); j < 15; j++)MMputchar(' '); } } MMPrintString((char *)"\r\n"); } MMPrintString((char *)"Total of "); PInt(m - 1); MMPrintString((char *)" commands\r\n"); } else if((p = checkstring(cmdline, (unsigned char*)"FUNCTIONS"))) { m = 0; step = OptionWidth / 18; char** c = (char**)GetTempMemory((TokenTableSize + 5) * sizeof(*c) + (TokenTableSize + 5) * 18); for (i = 0; i < TokenTableSize + 5; i++) { c[m] = (char*)((int)c + sizeof(char*) * (TokenTableSize + 5) + m * 18); if(m < TokenTableSize)strcpy(c[m], (const char*)tokentbl[i].name); else if(m == TokenTableSize)strcpy(c[m], "=>"); else if(m == TokenTableSize + 1)strcpy(c[m], "=<"); /* else if(m==TokenTableSize+2)strcpy(c[m],"OCT$("); else if(m==TokenTableSize+3)strcpy(c[m],"HEX$("); else if(m==TokenTableSize+4)strcpy(c[m],"MM.I2C"); */ else if(m == TokenTableSize + 2)strcpy(c[m], "MM.Fontheight"); else if(m == TokenTableSize + 3)strcpy(c[m], "MM.Fontwidth"); else strcpy(c[m], "MM.Info$("); m++; } sortStrings(c, m); for (i = 1; i < m; i += step) { for (k = 0; k < step; k++) { if(i + k < m) { MMPrintString(c[i + k]); if(k != (step - 1))for (j = strlen(c[i + k]); j < 15; j++)MMputchar(' '); } } MMPrintString((char *)"\r\n"); } MMPrintString((char *)"Total of "); PInt(m - 1); MMPrintString((char *)" functions and operators\r\n"); } else { if(!(*cmdline == 0 || *cmdline == '\'')) { getargs(&cmdline, 1, (unsigned char *)","); char* buff = (char *)GetTempMemory(STRINGSIZE); strcpy(buff, (const char*)getCstring(argv[0])); if(strchr(buff, '.') == NULL) strcat(buff, ".BAS"); ListProgram((unsigned char*)buff, false); } else { ListProgram(NULL, false); checkend(cmdline); } } } void ListNewLine(int* ListCnt, int all) { MMPrintString((char *)"\r\n"); (*ListCnt)++; if(!all && *ListCnt >= OptionHeight) { MMPrintString((char *)"PRESS ANY KEY ..."); MMgetchar(); MMPrintString((char *)"\r \r"); *ListCnt = 1; } } void ListProgramFlash(unsigned char* p, int all) { char b[STRINGSIZE]; char* pp; int ListCnt = 1; while (!(*p == 0 || *p == 0xff)) { // normally a LIST ends at the break so this is a safety precaution if(*p == T_NEWLINE) { p = llist((unsigned char*) b, (unsigned char *)p); // otherwise expand the line pp = b; while (*pp) { if(MMCharPos >= OptionWidth) ListNewLine(&ListCnt, all); MMputchar(*pp++); } ListNewLine(&ListCnt, all); if(p[0] == 0 && p[1] == 0) break; // end of the listing ? } } } void ListProgram(unsigned char* pp, int all) { char buff[STRINGSIZE]; int fnbr; int i, ListCnt = 1; if (pp == NULL) { if (!*lastfileedited)error((char*)"Nothing to list"); strcpy(buff, lastfileedited); } else { fullfilename((char *)pp, buff, NULL); } if(!existsfile(buff))error((char*)"File not found"); fnbr = FindFreeFileNbr(); if (!BasicFileOpen((char *)buff, fnbr, (char *)"rb")) return; while (!MMfeof(fnbr)) { // while waiting for the end of file memset(buff, 0, 256); MMgetline(fnbr, (char*)buff); // get the input line for (i = 0; i < (int)strlen(buff); i++)if (buff[i] == TAB) buff[i] = ' '; MMPrintString(buff); ListCnt += strlen(buff) / OptionWidth; ListNewLine(&ListCnt, all); } FileClose(fnbr); } void execute(char* mycmd) { // char *temp_tknbuf; unsigned char* ttp; int i = 0, toggle = 0; // temp_tknbuf = GetTempStrMemory(); // strcpy(temp_tknbuf, tknbuf); // first save the current token buffer in case we are in immediate mode // we have to fool the tokeniser into thinking that it is processing a program line entered at the console skipspace(mycmd); strcpy((char *)inpbuf, (const char *)getCstring((unsigned char *)mycmd)); // then copy the argument if (!(toupper(inpbuf[0]) == 'R' && toupper(inpbuf[1]) == 'U' && toupper(inpbuf[2]) == 'N')) { //convert the string to upper case while (inpbuf[i]) { if (inpbuf[i] == 34) { if (toggle == 0)toggle = 1; else toggle = 0; } if (!toggle) { if (inpbuf[i] == ':')error((char *)"Only single statements allowed"); inpbuf[i] = toupper(inpbuf[i]); } i++; } tokenise(true); // and tokenise it (the result is in tknbuf) memset(inpbuf, 0, STRINGSIZE); tknbuf[strlen((char *)tknbuf)] = 0; tknbuf[strlen((char*)tknbuf) + 1] = 0; ttp = nextstmt; // save the globals used by commands ScrewUpTimer = 1000; ExecuteProgram(tknbuf); // execute the function's code ScrewUpTimer = 0; // TempMemoryIsChanged = true; // signal that temporary memory should be checked nextstmt = ttp; return; } else { unsigned char* p = inpbuf; char * s=NULL; char fn[STRINGSIZE] = { 0 }; p[0] = GetCommandValue((unsigned char *)"RUN"); memmove(&p[1], &p[4], strlen((char *)p) - 4); p[strlen((char*)p) - 3] = 0; // MMPrintString(fn); PRet(); CloseAudio(1); strcpy((char *)tknbuf, (char*)inpbuf); longjmp(jmprun, 1); } } void cmd_execute(void) { execute((char*)cmdline); } void cmd_run(void) { skipspace(cmdline); memset(runcmd, 0, STRINGSIZE); memcpy(runcmd, cmdline, strlen((char *)cmdline)); if (*cmdline && *cmdline != '\'') { if (!FileLoadProgram(cmdline, 0)) return; } else { if (*lastfileedited == 0)error((char*)"Nothing to run"); if (!FileLoadProgram((unsigned char *)lastfileedited, 1)) return; } ClearRuntime(); WatchdogSet = false; PrepareProgram(true); IgnorePIN = false; if(*ProgMemory != T_NEWLINE) return; // no program to run nextstmt = ProgMemory; } void cmd_continue(void) { if(*cmdline == tokenFOR) { if(forindex == 0) error((char *)"No FOR loop is in effect"); nextstmt = forstack[forindex - 1].nextptr; return; } if(checkstring(cmdline, (unsigned char*)"DO")) { if(doindex == 0) error((char *)"No DO loop is in effect"); nextstmt = dostack[doindex - 1].loopptr; return; } // must be a normal CONTINUE checkend(cmdline); if(CurrentLinePtr) error((char *)"Invalid in a program"); if(ContinuePoint == NULL) error((char *)"Cannot continue"); // IgnorePIN = false; nextstmt = ContinuePoint; } void cmd_new(void) { checkend(cmdline); ClearProgram(); uSec(250000); memset(inpbuf, 0, STRINGSIZE); memset(lastfileedited, 0, STRINGSIZE); memset(Option.lastfilename, 0, STRINGSIZE); SaveOptions(); longjmp(mark, 1); // jump back to the input prompt } void cmd_erase(void) { int i, j, k, len; char p[MAXVARLEN + 1], * s, * x; getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char *)","); // getargs macro must be the first executable stmt in a block if((argc & 0x01) == 0) error((char *)"Argument count"); for (i = 0; i < argc; i += 2) { strcpy((char*)p, (const char *)argv[i]); while (!isnamechar(p[strlen(p) - 1])) p[strlen(p) - 1] = 0; makeupper((unsigned char *)p); // all variables are stored as uppercase for (j = MAXVARS / 2; j < MAXVARS; j++) { s = p; x = vartbl[j].name; len = strlen(p); while (len > 0 && *s == *x) { // compare the variable to the name that we have len--; s++; x++; } if(!(len == 0 && (*x == 0 || strlen(p) == MAXVARLEN))) continue; // found the variable if(((vartbl[i].type & T_STR) || vartbl[i].dims[0] != 0) && !(vartbl[i].type & T_PTR)) { FreeMemory((unsigned char *)vartbl[i].val.s); // free any memory (if allocated) vartbl[i].val.s = NULL; } k = i + 1; if(k == MAXVARS)k = MAXVARS / 2; if(vartbl[k].type) { vartbl[j].name[0] = '~'; vartbl[j].type = T_BLOCKED; } else { vartbl[j].name[0] = 0; vartbl[j].type = T_NOTYPE; } vartbl[i].dims[0] = 0; // and again vartbl[i].level = 0; Globalvarcnt--; break; } if(j == MAXVARS) error((char *)"Cannot find $", p); } } void cmd_clear(void) { checkend(cmdline); if(LocalIndex)error((char *)"Invalid in a subroutine"); ClearVars(0); } void cmd_goto(void) { if(isnamestart(*cmdline)) nextstmt = findlabel(cmdline); // must be a label else nextstmt = findline((int)getinteger(cmdline), true); // try for a line number CurrentLinePtr = nextstmt; } void cmd_if(void) { int r, i, testgoto, testelseif; unsigned char ss[3]; // this will be used to split up the argument line unsigned char* p, * tp; unsigned char* rp = NULL; ss[0] = tokenTHEN; ss[1] = tokenELSE; ss[2] = 0; testgoto = false; testelseif = false; retest_an_if: { // start a new block getargs(&cmdline, 20, ss); // getargs macro must be the first executable stmt in a block if(testelseif && argc > 2) error((char *)"Unexpected text"); // if there is no THEN token retry the test with a GOTO. If that fails flag an error if(argc < 2 || *argv[1] != ss[0]) { if(testgoto) error((char *)"IF without THEN"); ss[0] = tokenGOTO; testgoto = true; goto retest_an_if; } // allow for IF statements embedded inside this IF if(argc >= 3 && *argv[2] == cmdIF) argc = 3; // this is IF xx=yy THEN IF ... so we want to evaluate only the first 3 if(argc >= 5 && *argv[4] == cmdIF) argc = 5; // this is IF xx=yy THEN cmd ELSE IF ... so we want to evaluate only the first 5 if(argc == 4 || (argc == 5 && *argv[3] != ss[1])) error((char *)"Syntax"); r = (getnumber(argv[0]) != 0); // evaluate the expression controlling the if statement if(r) { // the test returned TRUE // first check if it is a multiline if(ie, only 2 args) if(argc == 2) { // if multiline do nothing, control will fall through to the next line (which is what we want to execute next) ; } else { // This is a standard single line IF statement // Because the test was TRUE we are just interested in the THEN cmd stage. if(*argv[1] == tokenGOTO) { cmdline = argv[2]; cmd_goto(); return; } else if(isdigit(*argv[2])) { nextstmt = findline((int)getinteger(argv[2]), true); } else { if(argc == 5) { // this is a full IF THEN ELSE and the statement we want to execute is between the THEN & ELSE // this is handled by a special routine execute_one_command((unsigned char *)argv[2]); } else { // easy - there is no ELSE clause so just point the next statement pointer to the byte after the THEN token for (p = cmdline; *p && *p != ss[0]; p++); // search for the token nextstmt = p + 1; // and point to the byte after } } } } else { // the test returned FALSE so we are just interested in the ELSE stage (if present) // first check if it is a multiline if(ie, only 2 args) if(argc == 2) { // search for the next ELSE, or ENDIF and pass control to the following line // if an ELSEIF is found re execute this function to evaluate the condition following the ELSEIF i = 1; p = nextstmt; while (1) { p = GetNextCommand(p, &rp, (unsigned char *)"No matching ENDIF"); if(*p == cmdtoken) { // found a nested IF command, we now need to determine if it is a single or multiline IF // search for a THEN, then check if only white space follows. If so, it is multiline. tp = p + 1; while (*tp && *tp != ss[0]) tp++; if(*tp) tp++; // step over the THEN skipspace(tp); if(*tp == 0 || *tp == '\'') // yes, only whitespace follows i++; // count it as a nested IF else // no, it is a single line IF skipelement(p); // skip to the end so that we avoid an ELSE continue; } if(*p == cmdELSE && i == 1) { // found an ELSE at the same level as this IF. Step over it and continue with the statement after it skipelement(p); nextstmt = p; break; } if((*p == cmdELSEIF) && i == 1) { // we have found an ELSEIF statement at the same level as our IF statement // setup the environment to make this function evaluate the test following ELSEIF and jump back // to the start of the function. This is not very clean (it uses the dreaded goto for a start) but it works p++; // step over the token skipspace(p); CurrentLinePtr = rp; if(*p == 0) error((char *)"Syntax"); // there must be a test after the elseif cmdline = p; skipelement(p); nextstmt = p; testgoto = false; testelseif = true; goto retest_an_if; } if(*p == cmdENDIF) i--; // found an ENDIF so decrement our nested counter if(i == 0) { // found our matching ENDIF stmt. Step over it and continue with the statement after it skipelement(p); nextstmt = p; break; } } } else { // this must be a single line IF statement // check if there is an ELSE on the same line if(argc == 5) { // there is an ELSE command if(isdigit(*argv[4])) // and it is just a number, so get it and find the line nextstmt = findline((int)getinteger(argv[4]), true); else { // there is a statement after the ELSE clause so just point to it (the byte after the ELSE token) for (p = cmdline; *p && *p != ss[1]; p++); // search for the token nextstmt = p + 1; // and point to the byte after } } else { // no ELSE on a single line IF statement, so just continue with the next statement skipline(cmdline); nextstmt = cmdline; } } } } } void cmd_else(void) { int i; unsigned char* p, * tp; // search for the next ENDIF and pass control to the following line i = 1; p = nextstmt; if(cmdtoken == cmdELSE) checkend(cmdline); while (1) { p = GetNextCommand(p, NULL, (unsigned char *)"No matching ENDIF"); if(*p == cmdIF) { // found a nested IF command, we now need to determine if it is a single or multiline IF // search for a THEN, then check if only white space follows. If so, it is multiline. tp = p + 1; while (*tp && *tp != tokenTHEN) tp++; if(*tp) tp++; // step over the THEN skipspace(tp); if(*tp == 0 || *tp == '\'') // yes, only whitespace follows i++; // count it as a nested IF } if(*p == cmdENDIF) i--; // found an ENDIF so decrement our nested counter if(i == 0) break; // found our matching ENDIF stmt } // found a matching ENDIF. Step over it and continue with the statement after it skipelement(p); nextstmt = p; } void cmd_end(void) { checkend(cmdline); memset(inpbuf, 0, STRINGSIZE); longjmp(mark, 1); // jump back to the input prompt } void cmd_select(void) { int i, type; unsigned char* p, * rp = NULL, * SaveCurrentLinePtr; void* v; MMFLOAT f = 0; long long int i64 = 0; unsigned char s[STRINGSIZE]; // these are the tokens that we will be searching for // they are cached the first time this command is called type = T_NOTYPE; v = DoExpression(cmdline, &type); // evaluate the select case value type = TypeMask(type); if(type & T_NBR) f = *(MMFLOAT*)v; if(type & T_INT) i64 = *(long long int*)v; if(type & T_STR) Mstrcpy((unsigned char*)s, (unsigned char*)v); // now search through the program looking for a matching CASE statement // i tracks the nesting level of any nested SELECT CASE commands SaveCurrentLinePtr = CurrentLinePtr; // save where we are because we will have to fake CurrentLinePtr to get errors reported correctly i = 1; p = nextstmt; while(1) { p = GetNextCommand(p, &rp, (unsigned char*)"No matching END SELECT"); if(*p == cmdSELECT_CASE) i++; // found a nested SELECT CASE command, increase the nested count and carry on searching // is this a CASE stmt at the same level as this SELECT CASE. if(*p == cmdCASE && i == 1) { int t; MMFLOAT ft, ftt; long long int i64t, i64tt; unsigned char* st, * stt; CurrentLinePtr = rp; // and report errors at the line we are on // loop through the comparison elements on the CASE line. Each element is separated by a comma do { p++; skipspace(p); t = type; // check for CASE IS, eg CASE IS > 5 -or- CASE > 5 and process it if it is // an operator can be >, <>, etc but it can also be a prefix + or - so we must not catch them if((SaveCurrentLinePtr = checkstring(p, (unsigned char*)"IS")) || ((tokentype(*p) & T_OPER) && !(*p == GetTokenValue((unsigned char*)"+") || *p == GetTokenValue((unsigned char*)"-")))) { int o; if(SaveCurrentLinePtr) p += 2; skipspace(p); if(tokentype(*p) & T_OPER) o = *p++ - C_BASETOKEN; // get the operator else error((char *)"Syntax"); if(type & T_NBR) ft = f; if(type & T_INT) i64t = i64; if(type & T_STR) st = s; while (o != E_END) p = doexpr(p, &ft, &i64t, &st, &o, &t); // get the right hand side of the expression and evaluate the operator in o if(!(t & T_INT)) error((char *)"Syntax"); // comparisons must always return an integer if(i64t) { // evaluates to true skipelement(p); nextstmt = p; CurrentLinePtr = SaveCurrentLinePtr; return; // if we have a match just return to the interpreter and let it execute the code } else { // evaluates to false skipspace(p); continue; } } // it must be either a single value (eg, "foo") or a range (eg, "foo" TO "zoo") // evaluate the first value p = evaluate(p, &ft, &i64t, &st, &t, true); skipspace(p); if(*p == tokenTO) { // is there is a TO keyword? p++; t = type; p = evaluate(p, &ftt, &i64tt, &stt, &t, false); // evaluate the right hand side of the TO expression if(((type & T_NBR) && f >= ft && f <= ftt) || ((type & T_INT) && i64 >= i64t && i64 <= i64tt) || (((type & T_STR) && Mstrcmp(s, st) >= 0) && (Mstrcmp(s, stt) <= 0))) { skipelement(p); nextstmt = p; CurrentLinePtr = SaveCurrentLinePtr; return; // if we have a match just return to the interpreter and let it execute the code } else { skipspace(p); continue; // otherwise continue searching } } // if we got to here the element must be just a single match. So make the test if(((type & T_NBR) && f == ft) || ((type & T_INT) && i64 == i64t) || ((type & T_STR) && Mstrcmp(s, st) == 0)) { skipelement(p); nextstmt = p; CurrentLinePtr = SaveCurrentLinePtr; return; // if we have a match just return to the interpreter and let it execute the code } skipspace(p); } while (*p == ','); // keep looping through the elements on the CASE line checkend(p); CurrentLinePtr = SaveCurrentLinePtr; } // test if we have found a CASE ELSE statement at the same level as this SELECT CASE // if true it means that we did not find a matching CASE - so execute this code if(*p == cmdCASE_ELSE && i == 1) { p++; // step over the token checkend(p); skipelement(p); nextstmt = p; CurrentLinePtr = SaveCurrentLinePtr; return; } if(*p == cmdEND_SELECT) i--; // found an END SELECT so decrement our nested counter if(i == 0) { // found our matching END SELECT stmt. Step over it and continue with the statement after it skipelement(p); nextstmt = p; CurrentLinePtr = SaveCurrentLinePtr; return; } } } // if we have hit a CASE or CASE ELSE we must search for a END SELECT at this level and resume at that point void cmd_case(void) { int i; unsigned char* p; // search through the program looking for a END SELECT statement // i tracks the nesting level of any nested SELECT CASE commands i = 1; p = nextstmt; while (1) { p = GetNextCommand(p, NULL, (unsigned char *)"No matching END SELECT"); if(*p == cmdSELECT_CASE) i++; // found a nested SELECT CASE command, we now need to search for its END CASE if(*p == cmdEND_SELECT) i--; // found an END SELECT so decrement our nested counter if(i == 0) { // found our matching END SELECT stmt. Step over it and continue with the statement after it skipelement(p); nextstmt = p; break; } } } void cmd_input(void) { unsigned char s[STRINGSIZE]; unsigned char* p, * sp, * tp; int i, fnbr; getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)",;"); // this is a macro and must be the first executable stmt // is the first argument a file number specifier? If so, get it if(argc >= 3 && *argv[0] == '#') { argv[0]++; fnbr = (int)getinteger(argv[0]); i = 2; } else { fnbr = 0; // is the first argument a prompt? // if so, print it followed by an optional question mark if(argc >= 3 && *argv[0] == '"' && (*argv[1] == ',' || *argv[1] == ';')) { *(argv[0] + strlen((char*)argv[0]) - 1) = 0; argv[0]++; MMPrintString((char*)argv[0]); if(*argv[1] == ';') MMPrintString((char*)"? "); i = 2; } else { MMPrintString((char*)"? "); // no prompt? then just print the question mark i = 0; } } if(argc - i < 1) error((char *)"Syntax"); // no variable to input to *inpbuf = 0; // start with an empty buffer MMgetline(fnbr, (char *)inpbuf); // get the line p = inpbuf; // step through the variables listed for the input statement // and find the next item on the line and assign it to the variable for (; i < argc; i++) { sp = s; // sp is a temp pointer into s[] if(*argv[i] == ',' || *argv[i] == ';') continue; skipspace(p); if(*p != 0) { if(*p == '"') { // if it is a quoted string p++; // step over the quote while (*p && *p != '"') *sp++ = *p++; // and copy everything upto the next quote while (*p && *p != ',') p++; // then find the next comma } else { // otherwise it is a normal string of characters while (*p && *p != ',') *sp++ = *p++; // copy up to the comma while (sp > s && sp[-1] == ' ') sp--; // and trim trailing whitespace } } *sp = 0; // terminate the string tp = (unsigned char*)findvar((unsigned char*)argv[i], V_FIND); // get the variable and save its new value if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); if(vartbl[VarIndex].type & T_STR) { if(strlen((char*)s) > vartbl[VarIndex].size) error((char *)"String too long"); strcpy((char*)tp, (char*)s); CtoM(tp); // convert to a MMBasic string } else if(vartbl[VarIndex].type & T_INT) { *((long long int*)tp) = strtoll((char*)s, (char**)&sp, 10); // convert to an integer } else *((MMFLOAT*)tp) = (MMFLOAT)atof((char*)s); if(*p == ',') p++; } } void cmd_trace(void) { if (checkstring(cmdline, (unsigned char *)"ON")) TraceOn = true; else if (checkstring(cmdline, (unsigned char*)"OFF")) TraceOn = false; else if (checkstring(cmdline, (unsigned char*)"LIST")) { int i; cmdline += 4; skipspace(cmdline); if (*cmdline == 0 || *cmdline == '\'') //' i = TRACE_BUFF_SIZE - 1; else i = (int)getint(cmdline, 0, TRACE_BUFF_SIZE - 1); i = TraceBuffIndex - i; if (i < 0) i += TRACE_BUFF_SIZE; while (i != TraceBuffIndex) { TraceLines((char *)TraceBuff[i]); if (++i >= TRACE_BUFF_SIZE) i = 0; } } else error((char *)"Unknown command"); } // FOR command void cmd_for(void) { int i, t, vlen, test; unsigned char ss[4]; // this will be used to split up the argument line unsigned char* p, * tp, * xp; void* vptr; unsigned char* vname, vtype; // static unsigned char fortoken, nexttoken; // cache these tokens for speed // if(!fortoken) fortoken = GetCommandValue((unsigned char *)"For"); // if(!nexttoken) nexttoken = GetCommandValue((unsigned char *)"Next"); ss[0] = tokenEQUAL; ss[1] = tokenTO; ss[2] = tokenSTEP; ss[3] = 0; { // start a new block getargs(&cmdline, 7, ss); // getargs macro must be the first executable stmt in a block if(argc < 5 || argc == 6 || *argv[1] != ss[0] || *argv[3] != ss[1]) error((char *)"FOR with misplaced = or TO"); if(argc == 6 || (argc == 7 && *argv[5] != ss[2])) error((char *)"Syntax"); // get the variable name and trim any spaces vname = argv[0]; if(*vname && *vname == ' ') vname++; while (*vname && vname[strlen((char*)vname) - 1] == ' ') vname[strlen((char*)vname) - 1] = 0; vlen = strlen((char*)vname); vptr = findvar(argv[0], V_FIND); // create the variable if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); vtype = TypeMask(vartbl[VarIndex].type); if(vtype & T_STR) error((char *)"Invalid variable"); // sanity check // check if the FOR variable is already in the stack and remove it if it is // this is necessary as the program can jump out of the loop without hitting // the NEXT statement and this will eventually result in a stack overflow for (i = 0; i < forindex; i++) { if(forstack[i].var == vptr && forstack[i].level == LocalIndex) { while (i < forindex - 1) { forstack[i].forptr = forstack[i + 1].forptr; forstack[i].nextptr = forstack[i + 1].nextptr; forstack[i].var = forstack[i + 1].var; forstack[i].vartype = forstack[i + 1].vartype; forstack[i].level = forstack[i + 1].level; forstack[i].tovalue.i = forstack[i + 1].tovalue.i; forstack[i].stepvalue.i = forstack[i + 1].stepvalue.i; i++; } forindex--; break; } } if(forindex == MAXFORLOOPS) error((char *)"Too many nested FOR loops"); forstack[forindex].var = vptr; // save the variable index forstack[forindex].vartype = vtype; // save the type of the variable forstack[forindex].level = LocalIndex; // save the level of the variable in terms of sub/funs forindex++; // incase functions use for loops if(vtype & T_NBR) { *(MMFLOAT*)vptr = getnumber(argv[2]); // get the starting value for a float and save forstack[forindex - 1].tovalue.f = getnumber(argv[4]); // get the to value and save if(argc == 7) forstack[forindex - 1].stepvalue.f = getnumber(argv[6]);// get the step value for a float and save else forstack[forindex - 1].stepvalue.f = 1.0; // default is +1 } else { *(long long int*)vptr = getinteger(argv[2]); // get the starting value for an integer and save forstack[forindex - 1].tovalue.i = getinteger(argv[4]); // get the to value and save if(argc == 7) forstack[forindex - 1].stepvalue.i = getinteger(argv[6]);// get the step value for an integer and save else forstack[forindex - 1].stepvalue.i = 1; // default is +1 } forindex--; forstack[forindex].forptr = nextstmt + 1; // return to here when looping // now find the matching NEXT command t = 1; p = nextstmt; while (1) { p = GetNextCommand(p, &tp, (unsigned char*)"No matching NEXT"); // if(*p == fortoken) t++; // count the FOR // if(*p == nexttoken) { // is it NEXT if(*p == cmdFOR) t++; // count the FOR if(*p == cmdNEXT) { // is it NEXT xp = p + 1; // point to after the NEXT token while (*xp && mystrncasecmp(xp, vname, vlen)) xp++; // step through looking for our variable if(*xp && !isnamechar(xp[vlen])) // is it terminated correctly? t = 0; // yes, found the matching NEXT else t--; // no luck, just decrement our stack counter } if(t == 0) { // found the matching NEXT forstack[forindex].nextptr = p; // pointer to the start of the NEXT command break; } } // test the loop value at the start if(forstack[forindex].vartype & T_INT) test = (forstack[forindex].stepvalue.i >= 0 && *(long long int*)vptr > forstack[forindex].tovalue.i) || (forstack[forindex].stepvalue.i < 0 && *(long long int*)vptr < forstack[forindex].tovalue.i); else test = (forstack[forindex].stepvalue.f >= 0 && *(MMFLOAT*)vptr > forstack[forindex].tovalue.f) || (forstack[forindex].stepvalue.f < 0 && *(MMFLOAT*)vptr < forstack[forindex].tovalue.f); if(test) { // loop is invalid at the start, so go to the end of the NEXT command skipelement(p); // find the command after the NEXT command nextstmt = p; // this is where we will continue } else { forindex++; // save the loop data and continue on with the command after the FOR statement } } } void cmd_next(void) { int i, vindex, test; void* vtbl[MAXFORLOOPS]; int vcnt; unsigned char* p; getargs(&cmdline, MAXFORLOOPS * 2, (unsigned char*)(unsigned char *)","); // getargs macro must be the first executable stmt in a block vindex = 0; // keep lint happy for (vcnt = i = 0; i < argc; i++) { if(i & 0x01) { if(*argv[i] != ',') error((char *)"Syntax"); } else vtbl[vcnt++] = findvar(argv[i], V_FIND | V_NOFIND_ERR); // find the variable and error if not found } loopback: // first search the for stack for a loop with the same variable specified on the NEXT's line if(vcnt) { for (i = forindex - 1; i >= 0; i--) for (vindex = vcnt - 1; vindex >= 0; vindex--) if(forstack[i].var == vtbl[vindex]) goto breakout; } else { // if no variables specified search the for stack looking for an entry with the same program position as // this NEXT statement. This cheats by using the cmdline as an identifier and may not work inside an IF THEN ELSE for (i = 0; i < forindex; i++) { p = forstack[i].nextptr + 1; skipspace(p); if(p == cmdline) goto breakout; } } error((char *)"Cannot find a matching FOR"); breakout: // found a match // apply the STEP value to the variable and test against the TO value if(forstack[i].vartype & T_INT) { *(long long int*)forstack[i].var += forstack[i].stepvalue.i; test = (forstack[i].stepvalue.i >= 0 && *(long long int*)forstack[i].var > forstack[i].tovalue.i) || (forstack[i].stepvalue.i < 0 && *(long long int*)forstack[i].var < forstack[i].tovalue.i); } else { *(MMFLOAT*)forstack[i].var += forstack[i].stepvalue.f; test = (forstack[i].stepvalue.f >= 0 && *(MMFLOAT*)forstack[i].var > forstack[i].tovalue.f) || (forstack[i].stepvalue.f < 0 && *(MMFLOAT*)forstack[i].var < forstack[i].tovalue.f); } if(test) { // the loop has terminated // remove the entry in the table, then skip forward to the next element and continue on from there while (i < forindex - 1) { forstack[i].forptr = forstack[i + 1].forptr; forstack[i].nextptr = forstack[i + 1].nextptr; forstack[i].var = forstack[i + 1].var; forstack[i].vartype = forstack[i + 1].vartype; forstack[i].level = forstack[i + 1].level; forstack[i].tovalue.i = forstack[i + 1].tovalue.i; forstack[i].stepvalue.i = forstack[i + 1].stepvalue.i; i++; } forindex--; if(vcnt > 0) { // remove that entry from our FOR stack for (; vindex < vcnt - 1; vindex++) vtbl[vindex] = vtbl[vindex + 1]; vcnt--; if(vcnt > 0) goto loopback; else return; } } else { // we have not reached the terminal value yet, so go back and loop again nextstmt = forstack[i].forptr; } } void cmd_do(void) { int i; unsigned char* p, * tp, * evalp; if(cmdtoken == cmdWHILE)error((char *)"Unknown command"); // if it is a DO loop find the WHILE token and (if found) get a pointer to its expression while (*cmdline && *cmdline != tokenWHILE) cmdline++; if(*cmdline == tokenWHILE) { evalp = ++cmdline; } else evalp = NULL; // check if this loop is already in the stack and remove it if it is // this is necessary as the program can jump out of the loop without hitting // the LOOP or WEND stmt and this will eventually result in a stack overflow for (i = 0; i < doindex; i++) { if(dostack[i].doptr == nextstmt) { while (i < doindex - 1) { dostack[i].evalptr = dostack[i + 1].evalptr; dostack[i].loopptr = dostack[i + 1].loopptr; dostack[i].doptr = dostack[i + 1].doptr; dostack[i].level = dostack[i + 1].level; i++; } doindex--; break; } } // add our pointers to the top of the stack if(doindex == MAXDOLOOPS) error((char *)"Too many nested DO or WHILE loops"); dostack[doindex].evalptr = evalp; dostack[doindex].doptr = nextstmt; dostack[doindex].level = LocalIndex; // now find the matching LOOP command i = 1; p = nextstmt; while (1) { p = GetNextCommand(p, &tp, (unsigned char*)"No matching LOOP"); if(*p == cmdtoken) i++; // entered a nested DO or WHILE loop if(*p == cmdLOOP) i--; // exited a nested loop if(i == 0) { // found our matching LOOP or WEND stmt dostack[doindex].loopptr = p; break; } } if(dostack[doindex].evalptr != NULL) { // if this is a DO WHILE ... LOOP statement // search the LOOP statement for a WHILE or UNTIL token (p is pointing to the matching LOOP statement) p++; while (*p && *p < 0x80) p++; if(*p == tokenWHILE) error((char *)"LOOP has a WHILE test"); if(*p == tokenUNTIL) error((char *)"LOOP has an UNTIL test"); } doindex++; // do the evaluation (if there is something to evaluate) and if false go straight to the command after the LOOP or WEND statement if(dostack[doindex - 1].evalptr != NULL && getnumber(dostack[doindex - 1].evalptr) == 0) { doindex--; // remove the entry in the table nextstmt = dostack[doindex].loopptr; // point to the LOOP or WEND statement skipelement(nextstmt); // skip to the next command } } void cmd_loop(void) { unsigned char* p; int tst = 0; // initialise tst to stop the compiler from complaining int i; // search the do table looking for an entry with the same program position as this LOOP statement for (i = 0; i < doindex; i++) { p = dostack[i].loopptr + 1; skipspace(p); if(p == cmdline) { // found a match // first check if the DO statement had a WHILE component // if not find the WHILE statement here and evaluate it if(dostack[i].evalptr == NULL) { // if it was a DO without a WHILE if(*cmdline >= 0x80) { // if there is something if(*cmdline == tokenWHILE) tst = (getnumber(++cmdline) != 0); // evaluate the expression else if(*cmdline == tokenUNTIL) tst = (getnumber(++cmdline) == 0); // evaluate the expression else error((char *)"Syntax"); } else { tst = 1; // and loop forever checkend(cmdline); // make sure that there is nothing else } } else { // if was DO WHILE tst = (getnumber(dostack[i].evalptr) != 0); // evaluate its expression checkend(cmdline); // make sure that there is nothing else } // test the expression value and reset the program pointer if we are still looping // otherwise remove this entry from the do stack if(tst) nextstmt = dostack[i].doptr; // loop again else{ // the loop has terminated // remove the entry in the table, then just let the default nextstmt run and continue on from there doindex = i; // just let the default nextstmt run } return; } } error((char *)"LOOP without a matching DO"); } void cmd_exitfor(void) { if(forindex == 0) error((char *)"No FOR loop is in effect"); nextstmt = forstack[--forindex].nextptr; checkend(cmdline); skipelement(nextstmt); } void cmd_exit(void) { if(doindex == 0) error((char *)"No DO loop is in effect"); nextstmt = dostack[--doindex].loopptr; checkend(cmdline); skipelement(nextstmt); } void cmd_error(void) { char* s, p[STRINGSIZE]; if (*cmdline && *cmdline != '\'') { s = (char *)getCstring(cmdline); if (CurrentX != 0) MMPrintString((char*)"\r\n"); // error message should be on a new line strcpy(p, s); error(p); } else error((char *)""); } void cmd_randomize(void) { int i; getargs(&cmdline, 1, (unsigned char *)","); if(argc == 1)i = (int)getinteger(argv[0]); else { int64_t j; QueryPerformanceCounter((LARGE_INTEGER*)&j); i = (int)(j & 0xFFFFFFFF); } if(i < 0) error((char *)"Number out of bounds"); srand(i); } // this is the Sub or Fun command // it simply skips over text until it finds the end of it void cmd_subfun(void) { unsigned char* p, returntoken, errtoken; if(gosubindex != 0) error((char *)"No matching END declaration"); // we have hit a SUB/FUN while in another SUB or FUN if(cmdtoken == cmdSUB) { returntoken = cmdENDSUB; errtoken = cmdENDFUNCTION; } else { returntoken = cmdENDFUNCTION; errtoken = cmdENDSUB; } p = nextstmt; while (1) { p = GetNextCommand(p, NULL, (unsigned char *)"No matching END declaration"); if(*p == cmdSUB || *p == cmdFUN || *p == errtoken) error((char *)"No matching END declaration"); if(*p == returntoken) { // found the next return skipelement(p); nextstmt = p; // point to the next command break; } } } void cmd_gosub(void) { if(gosubindex >= MAXGOSUB) error((char *)"Too many nested GOSUB"); errorstack[gosubindex] = CurrentLinePtr; gosubstack[gosubindex++] = nextstmt; LocalIndex++; if(isnamestart(*cmdline)) nextstmt = findlabel(cmdline); // must be a label else nextstmt = findline((int)getinteger(cmdline), true); // try for a line number CurrentLinePtr = nextstmt; } void cmd_mid(void) { unsigned char* p; getargs(&cmdline, 5, (unsigned char *)","); findvar(argv[0], V_NOFIND_ERR); if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); if(!(vartbl[VarIndex].type & T_STR)) error((char *)"Not a string"); unsigned char* sourcestring = getstring(argv[0]); int start = (int)getint(argv[2], 1, sourcestring[0]); int num = 0; if(argc == 5)num = (int)getint(argv[4], 1, sourcestring[0]); if(start + num - 1 > sourcestring[0])error((char *)"Selection exceeds length of string"); while (*cmdline && tokenfunction(*cmdline) != op_equal) cmdline++; if(!*cmdline) error((char *)"Syntax"); ++cmdline; if(!*cmdline) error((char *)"Syntax"); char* value = (char*)getstring(cmdline); if(num == 0)num = value[0]; if(num > value[0])error((char *)"Supplied string too short"); p = (unsigned char*)&value[1]; memcpy(&sourcestring[start], p, num); } void cmd_return(void) { checkend(cmdline); if(gosubindex == 0 || gosubstack[gosubindex - 1] == NULL) error((char *)"Nothing to return to"); ClearVars(LocalIndex--); // delete any local variables TempMemoryIsChanged = true; // signal that temporary memory should be checked nextstmt = gosubstack[--gosubindex]; // return to the caller CurrentLinePtr = errorstack[gosubindex]; } void cmd_endfun(void) { checkend(cmdline); if(gosubindex == 0 || gosubstack[gosubindex - 1] != NULL) error((char *)"Nothing to return to"); nextstmt = (unsigned char*)"\0\0\0"; // now terminate this run of ExecuteProgram() } void cmd_read(void) { int i, j, k, len, card; unsigned char *p, datatoken, *lineptr = NULL, *ptr; int vcnt, vidx, num_to_read = 0; if (checkstring(cmdline, (unsigned char*)"SAVE")) { if(restorepointer== MAXRESTORE - 1)error((char*)"Too many saves"); datastore[restorepointer].SaveNextDataLine = NextDataLine; datastore[restorepointer].SaveNextData = NextData; restorepointer++; return; } if (checkstring(cmdline, (unsigned char*)"RESTORE")) { if (!restorepointer)error((char*)"Nothing to restore"); restorepointer--; NextDataLine = datastore[restorepointer].SaveNextDataLine; NextData = datastore[restorepointer].SaveNextData; return; } getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char *)","); // getargs macro must be the first executable stmt in a block if(argc == 0) error((char *)"Syntax"); // first count the elements and do the syntax checking for(vcnt = i = 0; i < argc; i++) { if(i & 0x01) { if(*argv[i] != ',') error((char *)"Syntax"); } else{ findvar(argv[i], V_FIND | V_EMPTY_OK); if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); card = 1; if(emptyarray) { //empty array for(k = 0; k < MAXDIM; k++) { j = (vartbl[VarIndex].dims[k] - OptionBase + 1); if(j)card *= j; } } num_to_read += card; } } char** vtbl = (char **)GetTempMemory(num_to_read * sizeof(char*)); int* vtype = (int *)GetTempMemory(num_to_read * sizeof(int)); int* vsize = (int *)GetTempMemory(num_to_read * sizeof(int)); // step through the arguments and save the pointer and type for(vcnt = i = 0; i < argc; i += 2) { vtbl[vcnt] = (char *)findvar(argv[i], V_FIND | V_EMPTY_OK); ptr = (unsigned char *)vtbl[vcnt]; card = 1; if(emptyarray) { //empty array for (k = 0; k < MAXDIM; k++) { j = (vartbl[VarIndex].dims[k] - OptionBase + 1); if(j)card *= j; } } for (k = 0; k < card; k++) { if(k) { if(vartbl[VarIndex].type & (T_INT | T_NBR))ptr += 8; else ptr += vartbl[VarIndex].size + 1; vtbl[vcnt] = (char*)ptr; } vtype[vcnt] = TypeMask(vartbl[VarIndex].type); vsize[vcnt] = vartbl[VarIndex].size; vcnt++; } } // setup for a search through the whole memory vidx = 0; datatoken = GetCommandValue((unsigned char *)"Data"); p = lineptr = NextDataLine; if(*p == 0xff) error((char *)"No DATA to read"); // error if there is no program // search looking for a DATA statement. We keep returning to this point until all the data is found search_again: while (1) { if(*p == 0) p++; // if it is at the end of an element skip the zero marker if(*p == 0 || *p == 0xff) error((char *)"No DATA to read"); // end of the program and we still need more data if(*p == T_NEWLINE) lineptr = p++; if(*p == T_LINENBR) p += 3; skipspace(p); if(*p == T_LABEL) { // if there is a label here p += p[1] + 2; // skip over the label skipspace(p); // and any following spaces } if(*p == datatoken) break; // found a DATA statement while (*p) p++; // look for the zero marking the start of the next element } NextDataLine = lineptr; p++; // step over the token skipspace(p); if(!*p || *p == '\'') { CurrentLinePtr = lineptr; error((char *)"No DATA to read"); } // we have a DATA statement, first split the line into arguments { // new block, the getargs macro must be the first executable stmt in a block getargs(&p, (MAX_ARG_COUNT * 2) - 1, (unsigned char *)","); if((argc & 1) == 0) { CurrentLinePtr = lineptr; error((char *)"Syntax"); } // now step through the variables on the READ line and get their new values from the argument list // we set the line number to the number of the DATA stmt so that any errors are reported correctly while (vidx < vcnt) { // check that there is some data to read if not look for another DATA stmt if(NextData > argc) { skipline(p); NextData = 0; goto search_again; } CurrentLinePtr = lineptr; if(vtype[vidx] & T_STR) { char* p1, * p2; if(*argv[NextData] == '"') { // if quoted string for (len = 0, p1 = vtbl[vidx], p2 = (char*)argv[NextData] + 1; *p2 && *p2 != '"'; len++, p1++, p2++) { *p1 = *p2; // copy up to the quote } } else { // else if not quoted for (len = 0, p1 = vtbl[vidx], p2 = (char*)argv[NextData]; *p2 && *p2 != '\''; len++, p1++, p2++) { if(*p2 < 0x20 || *p2 >= 0x7f) error((char *)"Invalid character"); *p1 = *p2; // copy up to the comma } } if(len > vsize[vidx]) error((char *)"String too long"); *p1 = 0; // terminate the string CtoM((unsigned char*)vtbl[vidx]); // convert to a MMBasic string } else if(vtype[vidx] & T_INT) *((long long int*)vtbl[vidx]) = getinteger(argv[NextData]); // much easier if integer variable else *((MMFLOAT*)vtbl[vidx]) = getnumber(argv[NextData]); // same for numeric variable vidx++; NextData += 2; } } } void cmd_call(void) { int i; unsigned char* q; unsigned char* p = getCstring(cmdline); //get the command we want to call /* q=p; while(*q){ //convert to upper case for the match *q=mytoupper(*q); q++; }*/ q = cmdline; while (*q) { if(*q == ',' || *q == '\'')break; q++; } if(*q == ',')q++; i = FindSubFun(p, false); // it could be a defined command strcat((char *)p, " "); strcat((char*)p, (const char *)q); // MMPrintString(p);PRet(); if(i >= 0) { // >= 0 means it is a user defined command DefinedSubFun(false, p, i, NULL, NULL, NULL, NULL); } else error((char *)"Unknown user subroutine"); } void cmd_restore(void) { if(*cmdline == 0 || *cmdline == '\'') { NextDataLine = ProgMemory; NextData = 0; } else { skipspace(cmdline); if(*cmdline == '"') { NextDataLine = findlabel(getCstring(cmdline)); NextData = 0; } else if(isdigit(*cmdline) || *cmdline == GetTokenValue((unsigned char*)"+") || *cmdline == GetTokenValue((unsigned char*)"-") || *cmdline == '.') { NextDataLine = findline((int)getinteger(cmdline), true); // try for a line number NextData = 0; } else { void* ptr = findvar(cmdline, V_NOFIND_NULL); if(ptr) { if(vartbl[VarIndex].type & T_NBR) { if(vartbl[VarIndex].dims[0] > 0) { // Not an array error((char *)"Syntax"); } NextDataLine = findline((int)getinteger(cmdline), true); } else if(vartbl[VarIndex].type & T_INT) { if(vartbl[VarIndex].dims[0] > 0) { // Not an array error((char *)"Syntax"); } NextDataLine = findline((int)getinteger(cmdline), true); } else { NextDataLine = findlabel(getCstring(cmdline)); // must be a label } } else if(isnamestart(*cmdline)) { NextDataLine = findlabel(cmdline); // must be a label } NextData = 0; } } } void cmd_lineinput(void) { unsigned char* vp; int i, fnbr; getargs(&cmdline, 3, (unsigned char*)",;"); // this is a macro and must be the first executable stmt if(argc == 0 || argc == 2) error((char *)"Syntax"); i = 0; fnbr = 0; if(argc == 3) { // is the first argument a file number specifier? If so, get it if(*argv[0] == '#' && *argv[1] == ',') { argv[0]++; fnbr = (int)getinteger(argv[0]); } else { // is the first argument a prompt? if so, print it otherwise there are too many arguments if(*argv[1] != ',' && *argv[1] != ';') error((char *)"Syntax"); MMfputs((unsigned char*)getstring(argv[0]), 0); } i = 2; } if(argc - i != 1) error((char *)"Syntax"); vp = (unsigned char*)findvar(argv[i], V_FIND); if(vartbl[VarIndex].type & T_CONST) error((char *)"Cannot change a constant"); if(!(vartbl[VarIndex].type & T_STR)) error((char *)"Invalid variable"); MMgetline(fnbr, (char *)inpbuf); // get the input line if(strlen((char*)inpbuf) > vartbl[VarIndex].size) error((char *)"String too long"); strcpy((char*)vp, (char*)inpbuf); CtoM(vp); // convert to a MMBasic string } void cmd_on(void) { int r; unsigned char ss[4]; // this will be used to split up the argument line unsigned char* p; // first check if this is: ON KEY location p = checkstring(cmdline, (unsigned char*)"KEY"); if(p) { getargs(&p, 3, (unsigned char *)","); if(argc == 1) { if(*argv[0] == '0' && !isdigit(*(argv[0] + 1))) { OnKeyGOSUB = NULL; // the program wants to turn the interrupt off } else { OnKeyGOSUB = GetIntAddress(argv[0]); // get a pointer to the interrupt routine InterruptUsed = true; } return; } else { keyselect = (int)getint(argv[0], 0, 255); if(keyselect == 0) { KeyInterrupt = NULL; // the program wants to turn the interrupt off } else { if(*argv[2] == '0' && !isdigit(*(argv[2] + 1))) { KeyInterrupt = NULL; // the program wants to turn the interrupt off } else { KeyInterrupt = GetIntAddress((unsigned char *)argv[2]); // get a pointer to the interrupt routine InterruptUsed = true; } } return; } } p = checkstring(cmdline, (unsigned char *)"ERROR"); if (p) { if (checkstring(p, (unsigned char*)"ABORT")) { OptionErrorSkip = 0; return; } MMerrno = 0; // clear the error flags *MMErrMsg = 0; if (checkstring(p, (unsigned char*)"CLEAR")) return; if (checkstring(p, (unsigned char*)"IGNORE")) { OptionErrorSkip = -1; return; } if ((p = checkstring(p, (unsigned char*)"SKIP"))) { if (*p == 0 || *p == '\'') OptionErrorSkip = 1; else OptionErrorSkip = (int)getint(p, 1, 10000); return; } error((char*)"Syntax"); } // if we got here the command must be the traditional: ON nbr GOTO|GOSUB line1, line2,... etc ss[0] = tokenGOTO; ss[1] = tokenGOSUB; ss[2] = ','; ss[3] = 0; { // start a new block getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, ss); // getargs macro must be the first executable stmt in a block if(argc < 3 || !(*argv[1] == ss[0] || *argv[1] == ss[1])) error((char *)"Syntax"); if(argc % 2 == 0) error((char *)"Syntax"); r = (int)getint(argv[0], 0, 255); // evaluate the expression controlling the statement if(r == 0 || r > argc / 2) return; // microsoft say that we just go on to the next line if(*argv[1] == ss[1]) { // this is a GOSUB, same as a GOTO but we need to first push the return pointer if(gosubindex >= MAXGOSUB) error((char *)"Too many nested GOSUB"); errorstack[gosubindex] = CurrentLinePtr; gosubstack[gosubindex++] = nextstmt; LocalIndex++; } if(isnamestart(*argv[r * 2])) nextstmt = findlabel(argv[r * 2]); // must be a label else nextstmt = findline((int)getinteger(argv[r * 2]), true); // try for a line number } // IgnorePIN = false; } unsigned char* SetValue(unsigned char* p, int t, void* v) { MMFLOAT f; long long int i64; unsigned char* s; char TempCurrentSubFunName[MAXVARLEN + 1]; strcpy(TempCurrentSubFunName, (char*)CurrentSubFunName); // save the current sub/fun name if(t & T_STR) { p = evaluate(p, &f, &i64, &s, &t, true); Mstrcpy((unsigned char *)v, s); } else if(t & T_NBR) { p = evaluate(p, &f, &i64, &s, &t, false); if(t & T_NBR) (*(MMFLOAT*)v) = f; else (*(MMFLOAT*)v) = (MMFLOAT)i64; } else { p = evaluate(p, &f, &i64, &s, &t, false); if(t & T_INT) (*(long long int*)v) = i64; else (*(long long int*)v) = FloatToInt64(f); } strcpy((char*)CurrentSubFunName, TempCurrentSubFunName); // restore the current sub/fun name return p; } // define a variable // DIM [AS INTEGER|FLOAT|STRING] var[(d1 [,d2,...]] [AS INTEGER|FLOAT|STRING] [, ..., ...] // LOCAL also uses this function the routines only differ in that LOCAL can only be used in a sub/fun void cmd_dim(void) { int i, j, k, type, typeSave, ImpliedType = 0, VIndexSave, StaticVar = false; unsigned char* p, chSave, * chPosit; unsigned char VarName[(MAXVARLEN * 2) + 1]; void* v, * tv; if(*cmdline == tokenAS) cmdline++; // this means that we can use DIM AS INTEGER a, b, etc p = CheckIfTypeSpecified(cmdline, &type, true); // check for DIM FLOAT A, B, ... ImpliedType = type; { // getargs macro must be the first executable stmt in a block getargs(&p, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)(unsigned char *)","); if((argc & 0x01) == 0) error((char *)"Syntax"); for (i = 0; i < argc; i += 2) { p = skipvar(argv[i], false); // point to after the variable while (!(*p == 0 || *p == tokenAS || *p == (unsigned char)'\'' || *p == tokenEQUAL)) p++; // skip over a LENGTH keyword if there and see if we can find "AS" chSave = *p; chPosit = p; *p = 0; // save the char then terminate the string so that LENGTH is evaluated correctly if(chSave == tokenAS) { // are we using Microsoft syntax (eg, AS INTEGER)? if(ImpliedType & T_IMPLIED) error((char *)"Type specified twice"); p++; // step over the AS token p = CheckIfTypeSpecified(p, &type, true); // and get the type if(!(type & T_IMPLIED)) error((char *)"Variable type"); } if(cmdtoken == cmdLOCAL) { if(LocalIndex == 0) error((char *)"Invalid here"); type |= V_LOCAL; // local if defined in a sub/fun } if(cmdtoken == cmdSTATIC) { if(LocalIndex == 0) error((char *)"Invalid here"); // create a unique global name if(*CurrentInterruptName) strcpy((char *)VarName, (const char *)CurrentInterruptName); // we must be in an interrupt sub else strcpy((char*)VarName, (const char*)CurrentSubFunName); // normal sub/fun for (k = 1; k <= MAXVARLEN; k++) if(!isnamechar(VarName[k])) { VarName[k] = 0; // terminate the string on a non valid char break; } strcat((char*)VarName, (const char*)argv[i]); // by prefixing the var name with the sub/fun name StaticVar = true; } else strcpy((char*)VarName, (const char*)argv[i]); v = findvar(VarName, type | V_NOFIND_NULL); // check if the variable exists typeSave = type; VIndexSave = VarIndex; if(v == NULL) { // if not found v = findvar(VarName, type | V_FIND | V_DIM_VAR); // create the variable type = TypeMask(vartbl[VarIndex].type); VIndexSave = VarIndex; *chPosit = chSave; // restore the char previously removed if(vartbl[VarIndex].dims[0] == -1) error((char *)"Array dimensions"); if(vartbl[VarIndex].dims[0] > 0) { DimUsed = true; // prevent OPTION BASE from being used v = vartbl[VarIndex].val.s; } while (*p && *p != '\'' && tokenfunction(*p) != op_equal) p++; // search through the line looking for the equals sign if(tokenfunction(*p) == op_equal) { p++; // step over the equals sign skipspace(p); if(vartbl[VarIndex].dims[0] > 0 && *p == '(') { // calculate the overall size of the array for (j = 1, k = 0; k < MAXDIM && vartbl[VIndexSave].dims[k]; k++) { j *= (vartbl[VIndexSave].dims[k] + 1 - OptionBase); } do { p++; // step over the opening bracket or terminating comma p = SetValue(p, type, v); if(type & T_STR) v = (char*)v + vartbl[VIndexSave].size + 1; if(type & T_NBR) v = (char*)v + sizeof(MMFLOAT); if(type & T_INT) v = (char*)v + sizeof(long long int); skipspace(p); j--; } while (j > 0 && *p == ','); if(*p != ')') error((char *)"Number of initialising values"); if(j != 0) error((char *)"Number of initialising values"); } else SetValue(p, type, v); } type = ImpliedType; } else { if(!StaticVar) error((char *)"$ already declared", VarName); } // if it is a STATIC var create a local var pointing to the global var if(StaticVar) { tv = findvar(argv[i], typeSave | V_LOCAL | V_NOFIND_NULL); // check if the local variable exists if(tv != NULL) error((char *)"$ already declared", argv[i]); tv = findvar(argv[i], typeSave | V_LOCAL | V_FIND | V_DIM_VAR); // create the variable if(vartbl[VIndexSave].dims[0] > 0 || (vartbl[VIndexSave].type & T_STR)) { FreeMemory((unsigned char *)tv); // we don't need the memory allocated to the local vartbl[VarIndex].val.s = vartbl[VIndexSave].val.s; // point to the memory of the global variable } else vartbl[VarIndex].val.ia = &(vartbl[VIndexSave].val.i); // point to the data of the variable vartbl[VarIndex].type = vartbl[VIndexSave].type | T_PTR; // set the type to a pointer vartbl[VarIndex].size = vartbl[VIndexSave].size; // just in case it is a string copy the size for (j = 0; j < MAXDIM; j++) vartbl[VarIndex].dims[j] = vartbl[VIndexSave].dims[j]; // just in case it is an array copy the dimensions } } } } void cmd_const(void) { unsigned char* p; void* v; int i, type; getargs(&cmdline, (MAX_ARG_COUNT * 2) - 1, (unsigned char*)(unsigned char *)","); // getargs macro must be the first executable stmt in a block if((argc & 0x01) == 0) error((char *)"Syntax"); for (i = 0; i < argc; i += 2) { p = skipvar(argv[i], false); // point to after the variable skipspace(p); if(tokenfunction(*p) != op_equal) error((char *)"Syntax"); // must be followed by an equals sign p++; // step over the equals sign type = T_NOTYPE; v = DoExpression(p, &type); // evaluate the constant's value type = TypeMask(type); type |= V_FIND | V_DIM_VAR | T_CONST | T_IMPLIED; if(LocalIndex != 0) type |= V_LOCAL; // local if defined in a sub/fun findvar(argv[i], type); // create the variable if(vartbl[VarIndex].dims[0] != 0) error((char *)"Invalid constant"); if(TypeMask(vartbl[VarIndex].type) != TypeMask(type)) error((char *)"Invalid constant"); else { if(type & T_NBR) vartbl[VarIndex].val.f = *(MMFLOAT*)v; // and set its value if(type & T_INT) vartbl[VarIndex].val.i = *(long long int*)v; if(type & T_STR) Mstrcpy((unsigned char*)vartbl[VarIndex].val.s, (unsigned char*)v); } } } // utility function used by llist() below // it copys a command or function honouring the case selected by the user void strCopyWithCase(unsigned char* d, unsigned char* s) { if(Option.Listcase == CONFIG_LOWER) { while (*s) *d++ = tolower(*s++); } else if(Option.Listcase == CONFIG_UPPER) { while (*s) *d++ = mytoupper(*s++); } else { while (*s) *d++ = *s++; } *d = 0; } // list a line into a buffer (b) given a pointer to the beginning of the line (p). // the returned string is a C style string (terminated with a zero) // this is used by cmd_list(), cmd_edit() and cmd_xmodem() unsigned char* llist(unsigned char* b, unsigned char* p) { int i, firstnonwhite = true; unsigned char* b_start = b; while (1) { if (*p == T_NEWLINE) { p++; firstnonwhite = true; continue; } if (*p == T_LINENBR) { i = (((p[1]) << 8) | (p[2])); // get the line number p += 3; // and step over the number IntToStr((char *)b, i, 10); b += strlen((char*)b); if (*p != ' ') *b++ = ' '; } if (*p == T_LABEL) { // got a label for (i = p[1], p += 2; i > 0; i--) *b++ = *p++; // copy to the buffer *b++ = ':'; // terminate with a colon if (*p && *p != ' ') *b++ = ' '; // and a space if necessary firstnonwhite = true; } // this deliberately drops through in case the label is the only thing on the line if (*p >= C_BASETOKEN) { if (firstnonwhite) { if (*p == GetCommandValue((unsigned char*)"Let")) *b = 0; // use nothing if it LET else { strCopyWithCase(b, commandname(*p)); // expand the command (if it is not LET) b += strlen((char*)b); // update pointer to the end of the buffer if (isalpha(*(b - 1))) *b++ = ' '; // add a space to the end of the command name } firstnonwhite = false; } else { // not a command so must be a token strCopyWithCase(b, tokenname(*p)); // expand the token b += strlen((char*)b); // update pointer to the end of the buffer if (*p == tokenTHEN || *p == tokenELSE) firstnonwhite = true; else firstnonwhite = false; } p++; continue; } // hey, an ordinary char, just copy it to the output if (*p) { *b = *p; // place the char in the buffer if (*p != ' ') firstnonwhite = false; p++; b++; // move the pointers continue; } // at this point the char must be a zero // zero char can mean both a separator or end of line if (!(p[1] == T_NEWLINE || p[1] == 0)) { *b++ = ':'; // just a separator firstnonwhite = true; p++; continue; } // must be the end of a line - so return to the caller while (*(b - 1) == ' ' && b > b_start) --b; // eat any spaces on the end of the line *b = 0; // terminate the output buffer return ++p; } // end while } // get the file name for the RUN, LOAD, SAVE, KILL, COPY, DRIVE, FILES, FONT LOAD, LOADBMP, SAVEBMP, SPRITE LOAD and EDIT commands // this function allows the user to omit the quote marks around a string constant when in immediate mode // the first argument is a pointer to the file name (normally on the command line of the command) // the second argument is a pointer to the LastFile buffer. If this pointer is NULL the LastFile buffer feature will not be used // This returns a temporary string to the filename unsigned char* GetFileName(unsigned char* CmdLinePtr, unsigned char* LastFilePtr) { unsigned char* tp, * t; if(CurrentLinePtr) return getCstring(CmdLinePtr); // if running a program get the filename as an expression // if we reach here we are in immediate mode if(*CmdLinePtr == 0 && LastFilePtr != NULL) return LastFilePtr; // if the command line is empty and we have a pointer to the last file, return that if(strchr((char*)CmdLinePtr, '"') == NULL && strchr((char*)CmdLinePtr, '$') == NULL) {// quotes or a $ symbol indicate that it is an expression tp = (unsigned char*)GetTempMemory(STRINGSIZE); // this will last for the life of the command strcpy((char*)tp, (char*)CmdLinePtr); // save the string t = (unsigned char*)strchr((char*)tp, ' '); if(t) *t = 0; // trim any trailing spaces for (t = tp; *t; t++) if(*t <= ' ' || *t > 'z') error((char *)"Filename must be quoted"); return tp; } else return getCstring(CmdLinePtr); // treat the command line as a string expression and get its value } // lists the program to a specified file handle // this decodes line numbers and tokens and outputs them in plain english // LISTing a program is exactly the same as listing to a file (ie, SAVE) void flist(int fnbr, int fromnbr, int tonbr) { unsigned char* fromp = ProgMemory + 1; unsigned char b[STRINGSIZE]; int i; if(fromnbr != 1) fromp = findline(fromnbr, (fromnbr == tonbr) ? true : false); // set our pointer to the start line ListCnt = 1; while (1) { if(*fromp == T_LINENBR) { i = (((fromp[1]) << 8) | (fromp[2])); // get the line number if(i != NOLINENBR && i > tonbr) break; // end of the listing fromp = llist(b, fromp); // otherwise expand the line MMfputs((unsigned char*)CtoM(b), fnbr); // convert to a MMBasic string and output // #if defined(DOS) // MMfputs((unsigned char *)"\1\n", fnbr); // print the terminating lf // #else MMfputs((unsigned char*)"\2\r\n", fnbr); // print the terminating cr/lf // #endif if(i != NOLINENBR && i >= tonbr) break; // end of the listing // check if it is more than a screenfull if(fnbr == 0 && ListCnt >= VCHARS && !(fromp[0] == 0 && fromp[1] == 0)) { MMPrintString((char*)"PRESS ANY KEY ..."); MMgetchar(); MMPrintString((char*)"\r \r"); ListCnt = 1; } } //else // error((char *)"Internal error in flist()"); // finally, is it the end of the program? if(fromp[0] == 0) break; } if(fnbr != 0) FileClose(fnbr); }
37.102649
201
0.564179
UKTailwind
318739c084517a6d383cd9ac430c2f2687e34845
570
cpp
C++
uva/11498_Division_of_Nlogonia.cpp
st3v3nmw/competitive-programming
581d36c1c128e0e3ee3a0b52628e932ab43821d4
[ "MIT" ]
null
null
null
uva/11498_Division_of_Nlogonia.cpp
st3v3nmw/competitive-programming
581d36c1c128e0e3ee3a0b52628e932ab43821d4
[ "MIT" ]
null
null
null
uva/11498_Division_of_Nlogonia.cpp
st3v3nmw/competitive-programming
581d36c1c128e0e3ee3a0b52628e932ab43821d4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int k = -1, dx, dy, x, y; while (k != 0) { cin >> k; cin >> dx >> dy; for (int i = 0; i < k; i++) { cin >> x >> y; if (x == dx || y == dy) cout << "divisa\n"; else if (x > dx && y > dy) cout << "NE\n"; else if (x > dx && y < dy) cout << "SE\n"; else if (x < dx && y > dy) cout << "NO\n"; else cout << "SO\n"; } } }
24.782609
38
0.301754
st3v3nmw
31891372dd109a0689481337a33e7eaeca6b1be3
6,840
cpp
C++
src/gui/importpackwizard.cpp
Jorch72/CPP-MultiMC4
743b4a91ee1f9b4483a9769c292dbd16736f32d1
[ "Apache-2.0" ]
10
2015-07-28T19:46:19.000Z
2021-11-08T10:21:54.000Z
src/gui/importpackwizard.cpp
Jorch72/CPP-MultiMC4
743b4a91ee1f9b4483a9769c292dbd16736f32d1
[ "Apache-2.0" ]
1
2015-04-26T13:48:13.000Z
2015-04-26T13:48:13.000Z
src/gui/importpackwizard.cpp
Jorch72/CPP-MultiMC4
743b4a91ee1f9b4483a9769c292dbd16736f32d1
[ "Apache-2.0" ]
5
2015-01-25T13:25:25.000Z
2022-03-15T13:53:13.000Z
// // Copyright 2012 MultiMC Contributors // // 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 "importpackwizard.h" #include <wx/gbsizer.h> #include <wx/wfstream.h> #include <wx/zipstrm.h> #include "mainwindow.h" #include "minecraftversiondialog.h" #include "utils/apputils.h" #include "utils/fsutils.h" #include "stdinstance.h" #include <memory> ImportPackWizard::ImportPackWizard(MainWindow *parent, ConfigPack *pack) : wxWizard(parent, -1, _("Import Config Pack")) { auto sizer = GetPageAreaSizer(); this->m_pack = pack; this->m_mainWin = parent; this->SetPageSize(wxSize(400, 300)); wxFont titleFont(12, wxSWISS, wxNORMAL, wxNORMAL); packInfoPage = new wxWizardPageSimple(this); sizer->Add(packInfoPage); auto infoPageSz = new wxBoxSizer(wxVERTICAL); packInfoPage->SetSizer(infoPageSz); wxStaticText *infoTitleLabel = new wxStaticText(packInfoPage, -1, m_pack->GetPackName(), wxDefaultPosition, wxDefaultSize); infoTitleLabel->SetFont(titleFont); infoPageSz->Add(infoTitleLabel, 0, wxALIGN_CENTER | wxALL, 4); packNotesTextbox = new wxTextCtrl(packInfoPage, -1, m_pack->GetPackNotes(), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY); infoPageSz->Add(packNotesTextbox, 1, wxEXPAND | wxALL, 4); findModFilesPage = new wxWizardPageSimple(this, packInfoPage); packInfoPage->SetNext(findModFilesPage); wxGridBagSizer *configPageSz = new wxGridBagSizer(); findModFilesPage->SetSizer(configPageSz); wxStaticText *configTitleLabel = new wxStaticText(findModFilesPage, -1, _("Please add the mods listed below to your central mods folder and click refresh.")); configPageSz->Add(configTitleLabel, wxGBPosition(0, 0), wxGBSpan(1, 3), wxALIGN_CENTER | wxALL, 4); wxArrayString configList; missingModsList = new wxListBox(findModFilesPage, -1, wxDefaultPosition, wxDefaultSize, configList); configPageSz->Add(missingModsList, wxGBPosition(1, 0), wxGBSpan(1, 3), wxALIGN_CENTER | wxALL | wxEXPAND, 4); wxButton *viewCentralModsFolderButton = new wxButton(findModFilesPage, ID_ViewCentralModsFolder, _("&View Central Mods Folder")); configPageSz->Add(viewCentralModsFolderButton, wxGBPosition(2, 0), wxGBSpan(1, 1), wxALIGN_CENTER | wxALL, 4); wxButton *refreshButton = new wxButton(findModFilesPage, ID_RefreshList, _("&Refresh")); configPageSz->Add(refreshButton, wxGBPosition(2, 2), wxGBSpan(1, 1), wxALIGN_CENTER | wxALL | wxEXPAND, 4); configPageSz->AddGrowableCol(1, 0); configPageSz->AddGrowableRow(1, 0); UpdateMissingModList(); } bool ImportPackWizard::Start() { if (RunWizard(packInfoPage)) { // Install the mod pack. wxString instName; wxString instDirName; if (!m_mainWin->GetNewInstName(&instName, &instDirName, _("Import config pack"))) return false; wxString IntendedVersion = m_pack->GetMinecraftVersion(); if(IntendedVersion == "Unknown") { MinecraftVersionDialog dlg(this); dlg.CenterOnParent(); if(dlg.ShowModal() != wxID_OK) { wxLogError(_("Cannot create a Minecraft instance with no Minecraft version.")); return false; } MCVersion * ver = dlg.GetSelectedVersion(); IntendedVersion = ver->GetDescriptor(); } wxString instDir = Path::Combine(settings->GetInstDir(), instDirName); Instance *inst = new StdInstance(instDir); inst->SetName(instName); inst->SetIntendedVersion(IntendedVersion); inst->SetShouldUpdate(true); m_mainWin->AddInstance(inst); ModList *centralModList = m_mainWin->GetCentralModList(); // Add jar mods... for (auto iter = m_pack->GetJarModList()->begin(); iter != m_pack->GetJarModList()->end(); ++iter) { Mod *mod = centralModList->FindByID(iter->m_id, iter->m_version); if (mod == nullptr) { wxLogError(_("Missing jar mod %s."), iter->m_id.c_str()); } else { inst->GetModList()->InsertMod(inst->GetModList()->size(), mod->GetFileName().GetFullPath()); } } // Add mod loader mods... for (auto iter = m_pack->GetMLModList()->begin(); iter != m_pack->GetMLModList()->end(); ++iter) { Mod *mod = centralModList->FindByID(iter->m_id, iter->m_version); if (mod == nullptr) { wxLogError(_("Missing modloader mod %s."), iter->m_id.c_str()); } else { inst->GetMLModList()->InsertMod(0, mod->GetFileName().GetFullPath()); } } // Add core mods... for (auto iter = m_pack->GetCoreModList()->begin(); iter != m_pack->GetCoreModList()->end(); ++iter) { Mod *mod = centralModList->FindByID(iter->m_id, iter->m_version); if (mod == nullptr) { wxLogError(_("Missing modloader mod %s."), iter->m_id.c_str()); } else { inst->GetCoreModList()->InsertMod(0, mod->GetFileName().GetFullPath()); } } // Extract config files wxFFileInputStream fileIn(m_pack->GetFileName()); fsutils::ExtractZipArchive(fileIn, instDir); return true; } return false; } void ImportPackWizard::UpdateMissingModList() { missingModsList->Clear(); m_mainWin->LoadCentralModList(); ModList *centralModList = m_mainWin->GetCentralModList(); for (auto iter = m_pack->GetJarModList()->begin(); iter != m_pack->GetJarModList()->end(); ++iter) { if (centralModList->FindByID(iter->m_id, iter->m_version) == nullptr) { missingModsList->Append(wxString::Format("%s %s", iter->m_id.c_str(), iter->m_version.c_str())); } } for (auto iter = m_pack->GetMLModList()->begin(); iter != m_pack->GetMLModList()->end(); ++iter) { if (centralModList->FindByID(iter->m_id, iter->m_version) == nullptr) { missingModsList->Append(wxString::Format("%s %s", iter->m_id.c_str(), iter->m_version.c_str())); } } for (auto iter = m_pack->GetCoreModList()->begin(); iter != m_pack->GetCoreModList()->end(); ++iter) { if (centralModList->FindByID(iter->m_id, iter->m_version) == nullptr) { missingModsList->Append(wxString::Format("%s %s", iter->m_id.c_str(), iter->m_version.c_str())); } } } void ImportPackWizard::UpdateMissingModList(wxCommandEvent& event) { UpdateMissingModList(); } void ImportPackWizard::ViewFolderClicked(wxCommandEvent& event) { Utils::OpenFolder(settings->GetModsDir()); } BEGIN_EVENT_TABLE(ImportPackWizard, wxWizard) EVT_BUTTON(ID_RefreshList, ImportPackWizard::UpdateMissingModList) EVT_BUTTON(ID_ViewCentralModsFolder, ImportPackWizard::ViewFolderClicked) END_EVENT_TABLE()
31.962617
111
0.712281
Jorch72
318c6ebd7514a2f693cd89e691ad21183b611873
289
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_CreateUnnamedNs.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_CreateUnnamedNs.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_CreateUnnamedNs.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_CreateUnnamedNs.cpp // #include "smtc_CreateUnnamedNs.h" // semantic #include "smtc_UnnamedNs.h" #define LZZ_INLINE inline namespace smtc { NsPtr createUnnamedNs (NsPtr const & encl_ns, util::Loc const & loc) { return new UnnamedNs (encl_ns, loc); } } #undef LZZ_INLINE
18.0625
70
0.730104
SuperDizor
318d069fc3f208237efcde7f2b6d3cbc02f4c724
1,474
hpp
C++
lib/geometry/circle_intersection.hpp
hareku/cpp-algorithm
455339645d5797f0e6b211694345e1a221fc131c
[ "Apache-2.0" ]
null
null
null
lib/geometry/circle_intersection.hpp
hareku/cpp-algorithm
455339645d5797f0e6b211694345e1a221fc131c
[ "Apache-2.0" ]
null
null
null
lib/geometry/circle_intersection.hpp
hareku/cpp-algorithm
455339645d5797f0e6b211694345e1a221fc131c
[ "Apache-2.0" ]
null
null
null
#ifndef LIB_GEOMETRY_CIRCLE_INTERSECTION #define LIB_GEOMETRY_CIRCLE_INTERSECTION 1 #include <bits/stdc++.h> namespace lib::geometry { // circles_cross checks whether circle a and circle b intersect. template <class T> bool circles_cross(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) { T d = std::abs(a - b); return (ar + br - d) > eps; }; // circles_circumscribed checks whether is a or b circle is circumscribed in the other circle. template <class T> bool circles_circumscribed(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) { T d = std::abs(a - b); return std::abs(ar + br - d) < eps; }; // circles_inscribed checks whether is a or b circle is inscribed in the other circle. template <class T> bool circles_inscribed(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) { T d = std::abs(a - b); return std::abs(std::abs(ar - br) - d) < eps; }; // circle_includes checks whether does circle include other circle. template <class T> bool circle_includes(std::complex<T> a, T ar, std::complex<T> b, T br, const T eps = std::numeric_limits<T>::epsilon()) { // set the small circle to a if(ar > br) { std::swap(a, b); std::swap(ar, br); } return br - (std::abs(a - b) + ar) >- eps; }; } // namespace lib::geometry #endif // LIB_GEOMETRY_CIRCLE_INTERSECTION
36.85
146
0.661465
hareku
3194ae5c521496fbfaa45774e10505c6011afb62
15,222
cpp
C++
SoftbodySimulation/src/Scenario/ObstacleCourseScenario.cpp
GitDaroth/SoftbodySimulation
21b32dfb7a72be1f2fe54de8d2863bbf6a100288
[ "MIT" ]
3
2021-02-28T23:48:17.000Z
2021-11-02T15:08:34.000Z
SoftbodySimulation/src/Scenario/ObstacleCourseScenario.cpp
GitDaroth/SoftbodySimulation
21b32dfb7a72be1f2fe54de8d2863bbf6a100288
[ "MIT" ]
null
null
null
SoftbodySimulation/src/Scenario/ObstacleCourseScenario.cpp
GitDaroth/SoftbodySimulation
21b32dfb7a72be1f2fe54de8d2863bbf6a100288
[ "MIT" ]
null
null
null
#include "Scenario/ObstacleCourseScenario.h" #include <Constraint/BoxConstraint.h> #include <Constraint/RigidShapeConstraint.h> #include <Constraint/SoftShapeLinearConstraint.h> #include <Constraint/SoftShapeQuadraticConstraint.h> const QString ObstacleCourseScenario::NAME = "ObstacleCourse"; ObstacleCourseScenario::ObstacleCourseScenario() { } ObstacleCourseScenario::~ObstacleCourseScenario() { } void ObstacleCourseScenario::onInitialize() { m_dynamicObstacles.clear(); m_elapsedTime = 0.f; std::shared_ptr<ShapeConstraint> shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/bunny_normal.pts", "assets/meshes/bunny_normal.obj"); shapeConstraint->initialize(true); shapeConstraint->setStartPosition(QVector3D(-8.f, 15.f, 0.f)); m_pbdSolver->addConstraint(shapeConstraint); for (auto particle : shapeConstraint->getParticles()) m_pbdSolver->addParticle(particle); shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/dragon.pts", "assets/meshes/dragon.obj"); shapeConstraint->initialize(true); shapeConstraint->setStartPosition(QVector3D(-8.f, 15.f, 2.f)); m_pbdSolver->addConstraint(shapeConstraint); for (auto particle : shapeConstraint->getParticles()) m_pbdSolver->addParticle(particle); shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/armadillo.pts", "assets/meshes/armadillo.obj"); shapeConstraint->initialize(true); shapeConstraint->setStartPosition(QVector3D(-8.f, 17.f, -2.f)); m_pbdSolver->addConstraint(shapeConstraint); for (auto particle : shapeConstraint->getParticles()) m_pbdSolver->addParticle(particle); shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/patrick.pts", "assets/meshes/patrick.obj"); shapeConstraint->initialize(true); shapeConstraint->setStartPosition(QVector3D(-8.f, 16.5f, 0.f)); m_pbdSolver->addConstraint(shapeConstraint); for (auto particle : shapeConstraint->getParticles()) m_pbdSolver->addParticle(particle); shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/octopus2.pts", "assets/meshes/octopus2.obj"); shapeConstraint->initialize(true); shapeConstraint->setStartPosition(QVector3D(-8.f, 16.5f, 2.f)); m_pbdSolver->addConstraint(shapeConstraint); for (auto particle : shapeConstraint->getParticles()) m_pbdSolver->addParticle(particle); shapeConstraint = std::make_shared<SoftShapeLinearConstraint>("assets/points/bunny_big.pts", "assets/meshes/bunny_big.obj"); shapeConstraint->initialize(true); shapeConstraint->setStartPosition(QVector3D(-8.f, 15.f, -2.f)); m_pbdSolver->addConstraint(shapeConstraint); for (auto particle : shapeConstraint->getParticles()) m_pbdSolver->addParticle(particle); std::shared_ptr<BoxConstraint> boxBoundaryConstraint = std::make_shared<BoxConstraint>(QVector3D(-0.5f, 2.5f, 0.f), QVector3D(9.75f, 17.5f, 15.25f)); boxBoundaryConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxBoundaryConstraint->setIsBoundary(true); m_pbdSolver->addConstraint(boxBoundaryConstraint); // moving wall 1 ----------------------------------------- std::shared_ptr<BoxConstraint> boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-8.f, 14.f, 0.f), QVector3D(2.f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-9.75f, 17.125f, 0.f), QVector3D(0.25f, 2.87f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // ------------------------------------------------------- // moving wall 2 ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -3.5f, -11.25f), QVector3D(7.25f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -1.22f, -19.25f), QVector3D(7.25f, 2.f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // ------------------------------------------------------- // moving wall 3 ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -3.5f, 11.25f), QVector3D(7.25f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -1.22f, 19.25f), QVector3D(7.25f, 2.f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // ------------------------------------------------------- // ramp 1 ----------------------------------------- QVector3D rampPosition = QVector3D(-2.661f, 12.033f, 0.f); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition, QVector3D(4.f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(0.381f, 0.617f, 3.8f), QVector3D(4.f, 1.f, 0.25f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(0.381f, 0.617f, -3.8f), QVector3D(4.f, 1.f, 0.25f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); // ------------------------------------------------ // ramp 2 ----------------------------------------- rampPosition = QVector3D(5.f, 3.f, -3.4f); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition, QVector3D(4.f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(3.8f, 0.617f, -0.381f), QVector3D(0.25, 1.f, 4.f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(-3.8f, 0.617f, -0.381f), QVector3D(0.25, 1.f, 4.f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); // ------------------------------------------------ // ramp 3 ----------------------------------------- rampPosition = QVector3D(5.f, 3.f, 3.4f); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition, QVector3D(4.f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(3.8f, 0.617f, 0.381f), QVector3D(0.25, 1.f, 4.f)); boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(rampPosition + QVector3D(-3.8f, 0.617f, 0.381f), QVector3D(0.25, 1.f, 4.f)); boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); // ------------------------------------------------ // funnel ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(6.5f, -5.f, 0.f), QVector3D(3.f, 0.25f, 7.f)); boxObstacleConstraint->setRotation(30.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-2.5f, -5.f, 0.f), QVector3D(3.f, 0.25f, 7.f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(1.95f, -5.f, -4.55f), QVector3D(7.f, 0.25f, 3.f)); boxObstacleConstraint->setRotation(30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(1.95f, -5.f, 4.55f), QVector3D(7.f, 0.25f, 3.f)); boxObstacleConstraint->setRotation(-30.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(9.f, -5.f, 0.f), QVector3D(0.25f, 1.75f, 7.25f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(-5.f, -5.f, 0.f), QVector3D(0.25f, 1.75f, 7.25f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -5.f, 7.f), QVector3D(7.25f, 1.75f, 0.25f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -5.f, -7.f), QVector3D(7.25f, 1.75f, 0.25f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); // ------------------------------------------------ // spinning box 1 ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.5f, 10.f, 0.f), QVector3D(1.5f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(0.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.5f, 10.f, 0.f), QVector3D(1.5f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(90.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // -------------------------------------------------------- // spinning box 2 ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(5.f, 8.f, 0.f), QVector3D(1.5f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(67.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(5.f, 8.f, 0.f), QVector3D(1.5f, 0.25f, 4.f)); boxObstacleConstraint->setRotation(90.f + 67.f, QVector3D(0.f, 0.f, 1.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // -------------------------------------------------------- // spinning box 3 ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, 1.7f), QVector3D(3.f, 0.25f, 1.5f)); boxObstacleConstraint->setRotation(0.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, 1.7f), QVector3D(3.f, 0.25f, 1.5f)); boxObstacleConstraint->setRotation(90.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // -------------------------------------------------------- // spinning box 4 ----------------------------------------- boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, -1.7f), QVector3D(3.f, 0.25f, 1.5f)); boxObstacleConstraint->setRotation(0.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); boxObstacleConstraint = std::make_shared<BoxConstraint>(QVector3D(2.f, -8.5f, -1.7f), QVector3D(3.f, 0.25f, 1.5f)); boxObstacleConstraint->setRotation(90.f, QVector3D(1.f, 0.f, 0.f)); boxObstacleConstraint->setIsBoundary(false); m_pbdSolver->addConstraint(boxObstacleConstraint); m_dynamicObstacles.push_back(boxObstacleConstraint); // -------------------------------------------------------- } void ObstacleCourseScenario::onUpdate(float deltaTime) { m_elapsedTime += deltaTime; m_dynamicObstacles[0]->setPosition(3.5f * 0.5f * (-cosf(m_elapsedTime) + 1.f) * QVector3D(1.f, 0.f, 0.f) + QVector3D(-9.75f, 17.125f, 0.f)); m_dynamicObstacles[1]->setPosition(8.f * 0.5f * (-cosf(m_elapsedTime) + 1.f) * QVector3D(0.f, 0.f, 1.f) + QVector3D(2.f, -1.22f, -19.25f)); m_dynamicObstacles[2]->setPosition(-8.f * 0.5f * (-cosf(m_elapsedTime) + 1.f) * QVector3D(0.f, 0.f, 1.f) + QVector3D(2.f, -1.22f, 19.25f)); m_dynamicObstacles[3]->setRotation(-100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f)); m_dynamicObstacles[4]->setRotation(90.f - 100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f)); m_dynamicObstacles[5]->setRotation(67.f + 100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f)); m_dynamicObstacles[6]->setRotation(90.f + 67.f + 100.f * m_elapsedTime, QVector3D(0.f, 0.f, 1.f)); m_dynamicObstacles[7]->setRotation(-100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f)); m_dynamicObstacles[8]->setRotation(90.f - 100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f)); m_dynamicObstacles[9]->setRotation(100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f)); m_dynamicObstacles[10]->setRotation(90.f + 100.f * m_elapsedTime, QVector3D(1.f, 0.f, 0.f)); }
54.953069
164
0.711207
GitDaroth
31a0e82c183ddbd4f362b3e337c2012618805a63
6,676
cpp
C++
src/prod/src/ServiceModel/ServicePackagePoliciesDescription.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/ServiceModel/ServicePackagePoliciesDescription.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/ServiceModel/ServicePackagePoliciesDescription.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; ServicePackagePoliciesDescription::ServicePackagePoliciesDescription() : RunAsPolicies(), SecurityAccessPolicies(), EndPointBindingPolicies(), ResourceGovernancePolicies(), ResourceGovernanceDescription() { } ServicePackagePoliciesDescription::ServicePackagePoliciesDescription(ServicePackagePoliciesDescription const & other) : RunAsPolicies(other.RunAsPolicies), SecurityAccessPolicies(other.SecurityAccessPolicies), PackageSharingPolicies(other.PackageSharingPolicies), EndPointBindingPolicies(other.EndPointBindingPolicies), ResourceGovernancePolicies(other.ResourceGovernancePolicies), ResourceGovernanceDescription(other.ResourceGovernanceDescription) { } ServicePackagePoliciesDescription::ServicePackagePoliciesDescription(ServicePackagePoliciesDescription && other) : RunAsPolicies(move(other.RunAsPolicies)), SecurityAccessPolicies(move(other.SecurityAccessPolicies)), PackageSharingPolicies(move(other.PackageSharingPolicies)), EndPointBindingPolicies(move(other.EndPointBindingPolicies)), ResourceGovernancePolicies(move(other.ResourceGovernancePolicies)), ResourceGovernanceDescription(move(other.ResourceGovernanceDescription)) { } ServicePackagePoliciesDescription const & ServicePackagePoliciesDescription::operator = (ServicePackagePoliciesDescription const & other) { if (this != &other) { this->RunAsPolicies = other.RunAsPolicies; this->SecurityAccessPolicies = other.SecurityAccessPolicies; this->PackageSharingPolicies = other.PackageSharingPolicies; this->EndPointBindingPolicies = other.EndPointBindingPolicies; this->ResourceGovernancePolicies = other.ResourceGovernancePolicies; this->ResourceGovernanceDescription = other.ResourceGovernanceDescription; } return *this; } ServicePackagePoliciesDescription const & ServicePackagePoliciesDescription::operator = (ServicePackagePoliciesDescription && other) { if (this != &other) { this->RunAsPolicies = move(other.RunAsPolicies); this->SecurityAccessPolicies = move(other.SecurityAccessPolicies); this->PackageSharingPolicies = move(other.PackageSharingPolicies); this->EndPointBindingPolicies = move(other.EndPointBindingPolicies); this->ResourceGovernancePolicies = move(other.ResourceGovernancePolicies); this->ResourceGovernanceDescription = move(other.ResourceGovernanceDescription); } return *this; } void ServicePackagePoliciesDescription::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("ServicePackagePoliciesDescription { "); w.Write("ResourceGovernanceDescription = {{0}}", ResourceGovernanceDescription); w.Write("RunAsPolicies = {"); for(auto iter = RunAsPolicies.cbegin(); iter != RunAsPolicies.cend(); ++ iter) { w.Write("{0},",*iter); } w.Write("}"); w.Write("SecurityAccessPolicies = {"); for(auto iter = SecurityAccessPolicies.cbegin(); iter != SecurityAccessPolicies.cend(); ++ iter) { w.Write("{0},",*iter); } w.Write("}"); w.Write("PackageSharingPolicies = {"); for(auto iter = PackageSharingPolicies.cbegin(); iter != PackageSharingPolicies.cend(); ++ iter) { w.Write("{0},",*iter); } w.Write("}"); w.Write("EndPointBindingPolicies = {"); for (auto iter = EndPointBindingPolicies.cbegin(); iter != EndPointBindingPolicies.cend(); ++iter) { w.Write("{0},", *iter); } w.Write("}"); w.Write("ResourceGovernancePolicies = {"); for (auto iter = ResourceGovernancePolicies.cbegin(); iter != ResourceGovernancePolicies.cend(); ++iter) { w.Write("{0},", *iter); } w.Write("}"); w.Write("}"); } void ServicePackagePoliciesDescription::ReadFromXml( XmlReaderUPtr const & xmlReader) { // <Policies> xmlReader->StartElement( *SchemaNames::Element_Policies, *SchemaNames::Namespace, false); if (xmlReader->IsEmptyElement()) { // <Policies /> xmlReader->ReadElement(); return; } xmlReader->ReadStartElement(); bool done = false; while(!done) { done = true; if (xmlReader->IsStartElement( *SchemaNames::Element_RunAsPolicy, *SchemaNames::Namespace)) { RunAsPolicyDescription runAsPolicy; runAsPolicy.ReadFromXml(xmlReader); RunAsPolicies.push_back(runAsPolicy); done = false; } if (xmlReader->IsStartElement( *SchemaNames::Element_SecurityAccessPolicy, *SchemaNames::Namespace)) { SecurityAccessPolicyDescription securityAccessPolicy; securityAccessPolicy.ReadFromXml(xmlReader); SecurityAccessPolicies.push_back(securityAccessPolicy); done = false; } if (xmlReader->IsStartElement( *SchemaNames::Element_PackageSharingPolicy, *SchemaNames::Namespace)) { PackageSharingPolicyDescription packageSharingPolicy; packageSharingPolicy.ReadFromXml(xmlReader); PackageSharingPolicies.push_back(packageSharingPolicy); done = false; } if (xmlReader->IsStartElement( *SchemaNames::Element_EndpointBindingPolicy, *SchemaNames::Namespace)) { EndpointBindingPolicyDescription endpointBinding; endpointBinding.ReadFromXml(xmlReader); EndPointBindingPolicies.push_back(endpointBinding); done = false; } if (xmlReader->IsStartElement( *SchemaNames::Element_ResourceGovernancePolicy, *SchemaNames::Namespace)) { ResourceGovernancePolicyDescription description; description.ReadFromXml(xmlReader); ResourceGovernancePolicies.push_back(description); done = false; } if (xmlReader->IsStartElement( *SchemaNames::Element_ServicePackageResourceGovernancePolicy, *SchemaNames::Namespace)) { ResourceGovernanceDescription.ReadFromXml(xmlReader); } } // </Policies> xmlReader->ReadEndElement(); }
33.547739
137
0.67121
gridgentoo
31a3007006c300ec6792a78c2a3059f5c75f6f85
1,373
hpp
C++
example-react-native/ExampleProject/cpp/DemoModuleImpl.hpp
vmednonogov/djinni-react-native
17aaf19984656c6492ebc4e90b574a18caae2100
[ "Apache-2.0" ]
51
2018-03-10T03:17:13.000Z
2022-02-14T13:04:32.000Z
example-react-native/ExampleProject/cpp/DemoModuleImpl.hpp
vmednonogov/djinni-react-native
17aaf19984656c6492ebc4e90b574a18caae2100
[ "Apache-2.0" ]
1
2018-06-29T17:48:24.000Z
2018-06-29T17:49:54.000Z
example-react-native/ExampleProject/cpp/DemoModuleImpl.hpp
vmednonogov/djinni-react-native
17aaf19984656c6492ebc4e90b574a18caae2100
[ "Apache-2.0" ]
15
2018-01-30T02:37:57.000Z
2021-12-17T11:52:45.000Z
#include "DemoModule.hpp" class JobQueueImpl; class JobDispatcher; class DemoModuleImpl : public DemoModule { public: static std::shared_ptr<DemoModule> create(const std::shared_ptr<::ReactBridge> & bridge); DemoModuleImpl(const std::shared_ptr<::ReactBridge> & bridge); ~DemoModuleImpl(); void testPromise(const std::shared_ptr<::JavascriptPromise> & promise) override; void testCallback(const std::shared_ptr<::JavascriptCallback> & callback) override; void testMap(const std::shared_ptr<::JavascriptMap> & map, const std::shared_ptr<::JavascriptPromise> & promise) override; void testArray(const std::shared_ptr<::JavascriptArray> & array, const std::shared_ptr<::JavascriptCallback> & callback) override; void testBool(bool value, const std::shared_ptr<::JavascriptPromise> & promise) override; void testPrimitives(int32_t i, double d, const std::shared_ptr<::JavascriptCallback> & callback) override; void testString(const std::string & value, const std::shared_ptr<::JavascriptPromise> & promise) override; void testEventWithArray(const std::shared_ptr<::JavascriptArray> & value) override; void testEventWithMap(const std::shared_ptr<::JavascriptMap> & value) override; private: std::shared_ptr<ReactBridge> mBridge; std::shared_ptr<JobQueueImpl> mQueue; std::shared_ptr<JobDispatcher> mDispatcher; };
50.851852
134
0.75528
vmednonogov
31a3bbb19f7237f7fcbc1cb927d8dbe1ea752321
10,109
cpp
C++
catboost/private/libs/feature_estimator/text_feature_estimators.cpp
PallHaraldsson/catboost
f4b86aae0acb853f0216081518d490e52722ad88
[ "Apache-2.0" ]
null
null
null
catboost/private/libs/feature_estimator/text_feature_estimators.cpp
PallHaraldsson/catboost
f4b86aae0acb853f0216081518d490e52722ad88
[ "Apache-2.0" ]
null
null
null
catboost/private/libs/feature_estimator/text_feature_estimators.cpp
PallHaraldsson/catboost
f4b86aae0acb853f0216081518d490e52722ad88
[ "Apache-2.0" ]
null
null
null
#include "text_feature_estimators.h" #include "base_text_feature_estimator.h" #include <catboost/private/libs/text_features/text_feature_calcers.h> #include <catboost/private/libs/text_processing/embedding.h> #include <catboost/private/libs/options/enum_helpers.h> #include <util/generic/set.h> using namespace NCB; namespace { class TNaiveBayesEstimator final: public TBaseEstimator<TMultinomialNaiveBayes, TNaiveBayesVisitor> { public: TNaiveBayesEstimator( TTextClassificationTargetPtr target, TTextDataSetPtr learnTexts, TArrayRef<TTextDataSetPtr> testText) : TBaseEstimator(std::move(target), std::move(learnTexts), testText) { } TEstimatedFeaturesMeta FeaturesMeta() const override { TEstimatedFeaturesMeta meta; meta.FeaturesCount = TMultinomialNaiveBayes::BaseFeatureCount(GetTarget().NumClasses); meta.Type.resize(meta.FeaturesCount, EFeatureCalcerType::NaiveBayes); return meta; } TMultinomialNaiveBayes CreateFeatureCalcer() const override { return TMultinomialNaiveBayes(Id(), GetTarget().NumClasses); } TNaiveBayesVisitor CreateCalcerVisitor() const override { return TNaiveBayesVisitor(); }; }; class TBM25Estimator final: public TBaseEstimator<TBM25, TBM25Visitor> { public: TBM25Estimator( TTextClassificationTargetPtr target, TTextDataSetPtr learnTexts, TArrayRef<TTextDataSetPtr> testText) : TBaseEstimator(std::move(target), std::move(learnTexts), testText) { } TEstimatedFeaturesMeta FeaturesMeta() const override { TEstimatedFeaturesMeta meta; meta.FeaturesCount = TBM25::BaseFeatureCount(GetTarget().NumClasses); meta.Type.resize(meta.FeaturesCount, EFeatureCalcerType::BM25); return meta; } TBM25 CreateFeatureCalcer() const override { return TBM25(Id(), GetTarget().NumClasses); } TBM25Visitor CreateCalcerVisitor() const override { return TBM25Visitor(); }; }; class TEmbeddingOnlineFeaturesEstimator final: public TBaseEstimator<TEmbeddingOnlineFeatures, TEmbeddingFeaturesVisitor> { public: TEmbeddingOnlineFeaturesEstimator( TEmbeddingPtr embedding, TTextClassificationTargetPtr target, TTextDataSetPtr learnTexts, TArrayRef<TTextDataSetPtr> testText, const TSet<EFeatureCalcerType>& enabledTypes) : TBaseEstimator(std::move(target), std::move(learnTexts), std::move(testText)) , Embedding(std::move(embedding)) , ComputeCosDistance(enabledTypes.contains(EFeatureCalcerType::CosDistanceWithClassCenter)) , ComputeGaussianHomoscedatic(enabledTypes.contains(EFeatureCalcerType::GaussianHomoscedasticModel)) , ComputeGaussianHeteroscedatic(enabledTypes.contains(EFeatureCalcerType::GaussianHeteroscedasticModel)) {} TEstimatedFeaturesMeta FeaturesMeta() const override { TEstimatedFeaturesMeta meta; meta.FeaturesCount = TEmbeddingOnlineFeatures::BaseFeatureCount( GetTarget().NumClasses, ComputeCosDistance, ComputeGaussianHomoscedatic, ComputeGaussianHeteroscedatic ); for (ui32 classIdx = 0; classIdx < GetTarget().NumClasses; ++classIdx) { if (ComputeCosDistance) { meta.Type.push_back(EFeatureCalcerType::CosDistanceWithClassCenter); } if (ComputeGaussianHomoscedatic) { meta.Type.push_back(EFeatureCalcerType::GaussianHomoscedasticModel); } if (ComputeGaussianHeteroscedatic) { meta.Type.push_back(EFeatureCalcerType::GaussianHeteroscedasticModel); } } return meta; } TEmbeddingOnlineFeatures CreateFeatureCalcer() const override { return TEmbeddingOnlineFeatures( Id(), GetTarget().NumClasses, Embedding, ComputeCosDistance, ComputeGaussianHomoscedatic, ComputeGaussianHeteroscedatic ); } TEmbeddingFeaturesVisitor CreateCalcerVisitor() const override { return TEmbeddingFeaturesVisitor(GetTarget().NumClasses, Embedding->Dim()); } private: TEmbeddingPtr Embedding; bool ComputeCosDistance = false; bool ComputeGaussianHomoscedatic = false; bool ComputeGaussianHeteroscedatic = false; }; class TBagOfWordsEstimator final : public IFeatureEstimator { public: TBagOfWordsEstimator( TTextDataSetPtr learnTexts, TArrayRef<TTextDataSetPtr> testTexts) : LearnTexts({learnTexts}) , TestTexts(testTexts.begin(), testTexts.end()) , Dictionary(learnTexts->GetDictionary()) {} TEstimatedFeaturesMeta FeaturesMeta() const override { const ui32 featureCount = Dictionary.Size(); TEstimatedFeaturesMeta meta; meta.Type = TVector<EFeatureCalcerType>(featureCount, EFeatureCalcerType::BoW); meta.FeaturesCount = featureCount; meta.UniqueValuesUpperBoundHint = TVector<ui32>(featureCount, 2); return meta; } void ComputeFeatures(TCalculatedFeatureVisitor learnVisitor, TConstArrayRef<TCalculatedFeatureVisitor> testVisitors, NPar::TLocalExecutor* executor) const override { Calc(*executor, MakeConstArrayRef(LearnTexts), {learnVisitor}); Calc(*executor, MakeConstArrayRef(TestTexts), testVisitors); } TGuid Id() const override { return Guid; } THolder<IFeatureCalcer> MakeFinalFeatureCalcer( TConstArrayRef<ui32> featureIndices, NPar::TLocalExecutor* executor) const override { Y_UNUSED(executor); TBagOfWordsCalcer calcer(Id(), Dictionary.Size()); calcer.TrimFeatures(featureIndices); return MakeHolder<TBagOfWordsCalcer>(std::move(calcer)); } protected: void Calc(NPar::TLocalExecutor& executor, TConstArrayRef<TTextDataSetPtr> dataSets, TConstArrayRef<TCalculatedFeatureVisitor> visitors) const { const ui32 featuresCount = Dictionary.Size(); // TODO(d-kruchinin, noxoomo) better implementation: // add MaxRam option + bit mask compression for block on m features // estimation of all features in one pass for (ui32 id = 0; id < dataSets.size(); ++id) { const auto& ds = *dataSets[id]; const ui64 samplesCount = ds.SamplesCount(); //one-by-one, we don't want to acquire unnecessary RAM for very sparse features TVector<float> singleFeature(samplesCount); for (ui32 tokenId = 0; tokenId < featuresCount; ++tokenId) { NPar::ParallelFor( executor, 0, samplesCount, [&](ui32 line) { const bool hasToken = ds.GetText(line).Has(TTokenId(tokenId)); singleFeature[line] = static_cast<float>(hasToken); } ); visitors[id](tokenId, singleFeature); } } } private: TVector<TTextDataSetPtr> LearnTexts; TVector<TTextDataSetPtr> TestTexts; const TDictionaryProxy& Dictionary; const TGuid Guid = CreateGuid(); }; } TVector<TOnlineFeatureEstimatorPtr> NCB::CreateEstimators( TConstArrayRef<NCatboostOptions::TFeatureCalcerDescription> featureCalcerDescription, TEmbeddingPtr embedding, TTextClassificationTargetPtr target, TTextDataSetPtr learnTexts, TArrayRef<TTextDataSetPtr> testText) { TSet<EFeatureCalcerType> typesSet; for (auto& calcerDescription: featureCalcerDescription) { typesSet.insert(calcerDescription.CalcerType); } TVector<TOnlineFeatureEstimatorPtr> estimators; if (typesSet.contains(EFeatureCalcerType::NaiveBayes)) { estimators.push_back(new TNaiveBayesEstimator(target, learnTexts, testText)); } if (typesSet.contains(EFeatureCalcerType::BM25)) { estimators.push_back(new TBM25Estimator(target, learnTexts, testText)); } TSet<EFeatureCalcerType> embeddingEstimators = { EFeatureCalcerType::GaussianHomoscedasticModel, EFeatureCalcerType::GaussianHeteroscedasticModel, EFeatureCalcerType::CosDistanceWithClassCenter }; TSet<EFeatureCalcerType> enabledEmbeddingCalculators; SetIntersection( typesSet.begin(), typesSet.end(), embeddingEstimators.begin(), embeddingEstimators.end(), std::inserter(enabledEmbeddingCalculators, enabledEmbeddingCalculators.end())); if (!enabledEmbeddingCalculators.empty()) { estimators.push_back(new TEmbeddingOnlineFeaturesEstimator(embedding, target, learnTexts, testText, enabledEmbeddingCalculators)); } return estimators; } TVector<TFeatureEstimatorPtr> NCB::CreateEstimators( TConstArrayRef<NCatboostOptions::TFeatureCalcerDescription> featureCalcerDescription, TEmbeddingPtr embedding, TTextDataSetPtr learnTexts, TArrayRef<TTextDataSetPtr> testText) { Y_UNUSED(embedding); TSet<EFeatureCalcerType> typesSet; for (auto& calcerDescription: featureCalcerDescription) { typesSet.insert(calcerDescription.CalcerType); } TVector<TFeatureEstimatorPtr> estimators; if (typesSet.contains(EFeatureCalcerType::BoW)) { estimators.push_back(new TBagOfWordsEstimator(learnTexts, testText)); } return estimators; }
38.583969
138
0.651499
PallHaraldsson
31a5ff702f960fee81fcf44662d4581fe0f5620a
1,414
cpp
C++
src/io/github/technicalnotes/programming/basics/47-parameterpassing.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
src/io/github/technicalnotes/programming/basics/47-parameterpassing.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
src/io/github/technicalnotes/programming/basics/47-parameterpassing.cpp
chiragbhatia94/programming-cpp
efd6aa901deacf416a3ab599e6599845a8111eac
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" using namespace std; // here a & b are formal parameters void swapByValue(int a, int b); void swapByReference(int &a, int &b); void swapByPointer(int *a, int *b); int main(int argc, char **argv) { // here i & j are actual parameters int i = 10, j = 20; cout << "Initial value: " << "i = " << i << " & j = " << j << endl; cout << "Call by value:" << endl; swapByValue(i, j); cout << "i = " << i << " & j = " << j << endl; cout << "Call by reference:" << endl; swapByReference(i, j); cout << "i = " << i << " & j = " << j << endl; cout << "Call by pointer:" << endl; swapByPointer(&i, &j); cout << "&i = " << &i << " & &j = " << &j << endl; cout << "i = " << i << " & j = " << j << endl; } void swapByValue(int a, int b) { int c = b; b = a; a = c; cout << "a = " << a << " & b = " << b << endl; } void swapByReference(int &a, int &b) { int c = b; b = a; a = c; cout << "a = " << a << " & b = " << b << endl; } void swapByPointer(int *a, int *b) { // Pass by pointer is actually pass by value itself as the value of a & b are the addresses of i & j but their addresses are different, and we are just manipulating the pointers to swap the values int c = *b; *b = *a; *a = c; cout << "*a = " << *a << " & *b = " << *b << endl; cout << "&a = " << &a << " & &b = " << &b << endl; cout << "a = " << a << " & b = " << b << endl; }
27.192308
198
0.483027
chiragbhatia94
31aa3f0bd9ddc9a5b2a36cb268a119be9267a82e
2,086
cpp
C++
src/ShadowVolumeRender.cpp
Loic-Corenthy/miniGL
47976ea80e253e115eafae5934ec3ebdd2275d16
[ "MIT" ]
1
2021-08-18T03:54:22.000Z
2021-08-18T03:54:22.000Z
src/ShadowVolumeRender.cpp
Loic-Corenthy/miniGL
47976ea80e253e115eafae5934ec3ebdd2275d16
[ "MIT" ]
null
null
null
src/ShadowVolumeRender.cpp
Loic-Corenthy/miniGL
47976ea80e253e115eafae5934ec3ebdd2275d16
[ "MIT" ]
null
null
null
//===============================================================================================// /*! * \file ShadowVolumeRender.cpp * \author Loïc Corenthy * \version 1.0 */ //===============================================================================================// #include "ShadowVolumeRender.hpp" #include "Shader.hpp" #include "Exceptions.hpp" using miniGL::ShadowVolumeRender; using miniGL::Exceptions; ShadowVolumeRender::~ShadowVolumeRender(void) { } void ShadowVolumeRender::init(void) { // Create, load and compile a vertex shader Shader lVS(Shader::ETYPE::VERTEX); lVS.loadText("./Shaders/ShadowVolume.vert"); lVS.compile(); // Create, load and compile a geometry shader Shader lGS(Shader::ETYPE::GEOMETRY); lGS.loadText("./Shaders/ShadowVolume.geom"); lGS.compile(); // Create, load and compile a fragment shader Shader lFS(Shader::ETYPE::FRAGMENT); lFS.loadText("./Shaders/ShadowVolume.frag"); lFS.compile(); // Load the vertex and fragment shader into our program and link attachShader(lVS); attachShader(lGS); attachShader(lFS); link(); detachAndDeleteShader(lVS); detachAndDeleteShader(lGS); detachAndDeleteShader(lFS); // Use our program use(); mWVPLocation = Program::uniformLocation("uWVP"); mLightPosLocation = Program::uniformLocation("uLightPos"); // Check if we correctly initialized the uniform variables if (!checkUniformLocations()) throw Exceptions("Not all uniform locations were updated", __FILE__, __LINE__); } void ShadowVolumeRender::WVP(const mat4f & pWVP) { glUniformMatrix4fv(mWVPLocation, 1, GL_TRUE, const_cast<mat4f &>(pWVP).data()); } void ShadowVolumeRender::lightPosition(const vec3f & pPos) { glUniform3f(mLightPosLocation, pPos.x(), pPos.y(), pPos.z()); } bool ShadowVolumeRender::checkUniformLocations(void) const { return (mWVPLocation != Constants::invalidUniformLocation<GLuint>() && mLightPosLocation != Constants::invalidUniformLocation<GLuint>()); }
26.74359
99
0.630393
Loic-Corenthy
b3b2fcaedcdec99dcfd783dcd5e7dc76ff931fa4
24,335
cpp
C++
src/com_port.cpp
SammyEnigma/_nayk-COM-Port-Geo-Graph-Log-Console-File-Http-Server-Client
9fd01cf89ce16d129b5b96f68135cf8f71d1bd9c
[ "MIT" ]
null
null
null
src/com_port.cpp
SammyEnigma/_nayk-COM-Port-Geo-Graph-Log-Console-File-Http-Server-Client
9fd01cf89ce16d129b5b96f68135cf8f71d1bd9c
[ "MIT" ]
null
null
null
src/com_port.cpp
SammyEnigma/_nayk-COM-Port-Geo-Graph-Log-Console-File-Http-Server-Client
9fd01cf89ce16d129b5b96f68135cf8f71d1bd9c
[ "MIT" ]
1
2019-11-22T05:40:33.000Z
2019-11-22T05:40:33.000Z
/**************************************************************************** ** Copyright (c) 2019 Evgeny Teterin (nayk) <sutcedortal@gmail.com> ** All right reserved. ** ** 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 <QCoreApplication> #include <QSerialPortInfo> #include <QSettings> // #include "convert.h" #include "system_utils.h" // #include "com_port.h" namespace nayk { //======================================================================================================= //======================================================================================================= ComPort::ComPort(QObject *parent, bool autoRead) : QObject(parent) { _autoRead = autoRead; connect(&port, &QSerialPort::readyRead, this, &ComPort::on_ReadyRead); connect(&port, &QSerialPort::readyRead, this, &ComPort::readyRead); connect(&port, &QSerialPort::errorOccurred, this, &ComPort::on_Error); connect(&port, &QSerialPort::errorOccurred, this, &ComPort::errorOccurred); } //======================================================================================================= ComPort::~ComPort() { close(); } //======================================================================================================= void ComPort::on_Error(QSerialPort::SerialPortError error) { switch (error) { case QSerialPort::DeviceNotFoundError: emit toLog(LogError, tr("Порт %1: Устройство не найдено.").arg(port.portName())); break; case QSerialPort::PermissionError: emit toLog(LogError, tr("Порт %1: Ошибка доступа.").arg(port.portName())); break; case QSerialPort::OpenError: emit toLog(LogError, tr("Порт %1: Ошибка при открытии.").arg(port.portName())); break; case QSerialPort::ParityError: emit toLog(LogError, tr("Порт %1: Ошибка четности.").arg(port.portName())); break; case QSerialPort::FramingError: emit toLog(LogError, tr("Порт %1: Ошибка кадрирования.").arg(port.portName())); break; case QSerialPort::BreakConditionError: emit toLog(LogError, tr("Порт %1: Ошибка условия прерывания.").arg(port.portName())); break; case QSerialPort::WriteError: emit toLog(LogError, tr("Порт %1: Ошибка записи.").arg(port.portName())); break; case QSerialPort::ReadError: emit toLog(LogError, tr("Порт %1: Ошибка чтения.").arg(port.portName())); break; case QSerialPort::ResourceError: emit toLog(LogError, tr("Порт %1: Ошибка ресурса.").arg(port.portName())); break; case QSerialPort::UnsupportedOperationError: emit toLog(LogError, tr("Порт %1: Неподдерживаемая операция.").arg(port.portName())); break; case QSerialPort::UnknownError: emit toLog(LogError, tr("Порт %1: Неизвестная ошибка.").arg(port.portName())); break; case QSerialPort::TimeoutError: emit toLog(LogError, tr("Порт %1: Таймаут.").arg(port.portName())); break; case QSerialPort::NotOpenError: emit toLog(LogError, tr("Порт %1: Не открыт.").arg(port.portName())); break; default: break; } } //======================================================================================================= void ComPort::on_ReadyRead() { if(!_autoRead) return; QByteArray buf = readAll(); if(!buf.isEmpty()) emit rxBytes(buf); } //======================================================================================================= QByteArray ComPort::readAll() { if(!port.isOpen()) { _lastError = tr("Порт %1: Ошибка чтения - порт закрыт.").arg(port.portName()); emit toLog(LogError, _lastError); return QByteArray(); } QByteArray buf = port.readAll(); if(!buf.isEmpty()) { QString str = ""; for(auto i=0; i<buf.size(); ++i) str += Convert::intToHex( static_cast<quint8>( buf.at(i) ), 2, false ) + " "; emit toLog(LogIn, tr("Порт %1: %2").arg(port.portName()).arg(str)); } return buf; } //======================================================================================================= qint64 ComPort::write(const QByteArray &data) { if(!port.isOpen()) { _lastError = tr("Порт %1: Ошибка записи - порт закрыт.").arg(port.portName()); emit toLog(LogError, _lastError); return 0; } qint32 startIndx = 0; int n = 0; qint32 dataLen = 0; while( (dataLen < data.size()) && (n<4)) { qint64 len = port.write(data.right( data.size() - startIndx )); if(len < 0) { _lastError = tr("Порт %1: Ошибка записи. %2.").arg(port.portName().arg(port.errorString())); emit toLog(LogError, _lastError); return dataLen; } else if(len > 0) { QString str = ""; for(auto i=0; i<len; ++i) str += Convert::intToHex( static_cast<quint8>( data.at(startIndx+i) ), 2, false ) + " "; emit toLog(LogOut, tr("Порт %1: %2").arg(port.portName()).arg(str)); } dataLen += len; startIndx += len; } return dataLen; } //======================================================================================================= bool ComPort::open(QIODevice::OpenMode openMode) { if(port.isOpen() && (port.openMode() == openMode)) return true; if(!close()) return false; emit beforeOpen(); if(!port.open( openMode )) { _lastError = tr("Порт %1: Ошибка при открытии. %2.").arg( port.portName() ).arg( port.errorString()); emit toLog(LogError, _lastError); return false; } emit afterOpen(); emit toLog(LogInfo, tr("Порт %1: Открыт.").arg(port.portName()) ); return true; } //======================================================================================================= bool ComPort::close() { if(!port.isOpen()) return true; emit beforeClose(); port.close(); if(port.isOpen()) { _lastError = tr("Порт %1: Ошибка при закрытии.").arg( port.portName() ); emit toLog(LogError, _lastError); return false; } emit afterClose(); emit toLog(LogInfo, tr("Порт %1: Закрыт.").arg(port.portName()) ); return true; } //======================================================================================================= bool ComPort::setPortSettings( const PortSettingsStruct &portSettings ) { return (setPortName(portSettings.portName) && setBaudRate(portSettings.baudRate) && setDataBits(portSettings.dataBits) && setStopBits(portSettings.stopBits) && setParity(portSettings.parity) && setBufferSize(portSettings.bufSize) ); } //======================================================================================================= bool ComPort::setPortSettings(const QString &portName, qint32 baudRate, QSerialPort::DataBits dataBits, QSerialPort::StopBits stopBits, QSerialPort::Parity parity, qint64 bufSize) { return (setPortName(portName) && setBaudRate(baudRate) && setDataBits(dataBits) && setStopBits(stopBits) && setParity(parity) && setBufferSize(bufSize) ); } //======================================================================================================= bool ComPort::setBufferSize(qint64 bufSize) { port.setReadBufferSize( bufSize ); toLog(LogInfo, tr("Порт %1: Установлен размер буфера %2.").arg(port.portName()).arg(bufSize)); return true; } //======================================================================================================= bool ComPort::setPortName(const QString &portName) { QString oldName = port.portName(); port.setPortName(portName); emit toLog(LogInfo, tr("Порт %1: Изменение имени на %2.").arg(oldName).arg(port.portName())); return true; } //======================================================================================================= bool ComPort::setBaudRate(qint32 baudRate) { if(!port.setBaudRate(baudRate)) { _lastError = tr("Порт %1: Ошибка при установке скорости %2.").arg( port.portName() ).arg(baudRate); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Установлена скорость %2.").arg(port.portName()).arg(baudRate)); return true; } //======================================================================================================= bool ComPort::setDataBits(QSerialPort::DataBits dataBits) { QString str = dataBitsToStr(dataBits); if(!port.setDataBits(dataBits)) { _lastError = tr("Порт %1: Ошибка при установке бит данных %2.").arg( port.portName() ).arg(str); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Установлены биты данных %2.").arg(port.portName()).arg(str)); return true; } //======================================================================================================= bool ComPort::setStopBits(QSerialPort::StopBits stopBits) { QString str = stopBitsToStr(stopBits); if(!port.setStopBits(stopBits)) { _lastError = tr("Порт %1: Ошибка при установке стоповых бит %2.").arg( port.portName() ).arg(str); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Установлены стоповые биты %2.").arg(port.portName()).arg(str)); return true; } //======================================================================================================= bool ComPort::setParity(QSerialPort::Parity parity) { QString str = parityToStr(parity); if(!port.setParity(parity)) { _lastError = tr("Порт %1: Ошибка при установке четности %2.").arg( port.portName() ).arg(str); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Установлена четность %2.").arg(port.portName()).arg(str)); return true; } //======================================================================================================= bool ComPort::setDtr(bool on) { QString str = on ? "вкл" : "выкл"; if(!port.setDataTerminalReady(on)) { _lastError = tr("Порт %1: Ошибка при установке DTR = %2.").arg( port.portName() ).arg(str); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Установлен DTR = %2.").arg(port.portName()).arg(str)); return true; } //======================================================================================================= bool ComPort::setRts(bool on) { QString str = on ? "вкл" : "выкл"; if(!port.setRequestToSend(on)) { _lastError = tr("Порт %1: Ошибка при установке RTS = %2.").arg( port.portName() ).arg(str); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Установлен RTS = %2.").arg(port.portName()).arg(str)); return true; } //======================================================================================================= bool ComPort::clear(QSerialPort::Directions directions) { QString str = ((directions & QSerialPort::Input) == QSerialPort::Input) ? "входящий" : ""; if((directions & QSerialPort::Output) == QSerialPort::Output) { if(!str.isEmpty()) str += " и "; str += "исходящий"; } if(!port.clear(directions)) { _lastError = tr("Порт %1: Ошибка при очистке буфера %2.").arg( port.portName() ).arg(str); emit toLog(LogError, _lastError); return false; } emit toLog(LogInfo, tr("Порт %1: Очищен буфер %2.").arg(port.portName()).arg(str)); return true; } //======================================================================================================= QString ComPort::dataBitsToStr(QSerialPort::DataBits dataBits) { return (dataBits == QSerialPort::UnknownDataBits) ? "Unknown" : QString("%1").arg(dataBits); } //======================================================================================================= QString ComPort::stopBitsToStr(QSerialPort::StopBits stopBits) { switch (stopBits) { case QSerialPort::OneStop: return "1"; case QSerialPort::OneAndHalfStop: return "1.5"; case QSerialPort::TwoStop: return "2"; default: break; } return "Unknown"; } //======================================================================================================= QString ComPort::parityToStr(QSerialPort::Parity parity) { switch (parity) { case QSerialPort::NoParity: return "No"; case QSerialPort::EvenParity: return "Even"; case QSerialPort::OddParity: return "Odd"; case QSerialPort::SpaceParity: return "Space"; case QSerialPort::MarkParity: return "Mark"; default: break; } return "Unknown"; } //======================================================================================================= QSerialPort::DataBits ComPort::strToDataBits(const QString &dataBitsStr) { int n = Convert::strToIntDef(dataBitsStr, -1); if((n<5) || (n>8)) return QSerialPort::UnknownDataBits; return static_cast<QSerialPort::DataBits>(n); } //======================================================================================================= QSerialPort::StopBits ComPort::strToStopBits(const QString &stopBitsStr) { if(stopBitsStr == "1") return QSerialPort::OneStop; if(stopBitsStr == "1.5") return QSerialPort::OneAndHalfStop; if(stopBitsStr == "2") return QSerialPort::TwoStop; return QSerialPort::UnknownStopBits; } //======================================================================================================= QSerialPort::Parity ComPort::strToParity(const QString &parityStr) { if(parityStr.toLower() == "no") return QSerialPort::NoParity; if(parityStr.toLower() == "even") return QSerialPort::EvenParity; if(parityStr.toLower() == "odd") return QSerialPort::OddParity; if(parityStr.toLower() == "space") return QSerialPort::SpaceParity; if(parityStr.toLower() == "mark") return QSerialPort::MarkParity; return QSerialPort::UnknownParity; } //======================================================================================================= PortSettingsStruct ComPort::readSettingsFromFile(const QString &fileName, const QString &sectionName, const PortSettingsStruct &defaultSettings) { PortSettingsStruct res; QSettings ini(fileName, QSettings::IniFormat); ini.setIniCodec("UTF-8"); res.portName = ini.value( QString("%1/portname").arg(sectionName), defaultSettings.portName).toString(); res.baudRate = ini.value( QString("%1/baudrate").arg(sectionName), defaultSettings.baudRate).toInt(); res.bufSize = ini.value( QString("%1/bufsize").arg(sectionName), defaultSettings.bufSize).toInt(); res.dataBits = strToDataBits( ini.value( QString("%1/databits").arg(sectionName), dataBitsToStr(defaultSettings.dataBits)).toString() ); res.stopBits = strToStopBits( ini.value( QString("%1/stopbits").arg(sectionName), stopBitsToStr(defaultSettings.stopBits)).toString() ); res.parity = strToParity( ini.value( QString("%1/parity").arg(sectionName), parityToStr(defaultSettings.parity)).toString() ); res.dtr = ini.value( QString("%1/dtr").arg(sectionName), defaultSettings.dtr).toBool(); res.rts = ini.value( QString("%1/rts").arg(sectionName), defaultSettings.rts).toBool(); return res; } //======================================================================================================== bool ComPort::writeSettingsToFile(const QString &fileName, const QString &sectionName, const PortSettingsStruct &portSettings) { QSettings ini(fileName, QSettings::IniFormat); ini.setIniCodec("UTF-8"); ini.setValue( QString("%1/portname").arg(sectionName), portSettings.portName); ini.setValue( QString("%1/baudrate").arg(sectionName), portSettings.baudRate); ini.setValue( QString("%1/bufsize").arg(sectionName), portSettings.bufSize); ini.setValue( QString("%1/databits").arg(sectionName), dataBitsToStr(portSettings.dataBits)); ini.setValue( QString("%1/stopbits").arg(sectionName), stopBitsToStr(portSettings.stopBits)); ini.setValue( QString("%1/parity").arg(sectionName), parityToStr(portSettings.parity)); ini.setValue( QString("%1/dtr").arg(sectionName), portSettings.dtr); ini.setValue( QString("%1/rts").arg(sectionName), portSettings.rts); ini.sync(); return (ini.status() == QSettings::NoError); } //======================================================================================================== PortSettingsStruct ComPort::parseSettingsFromString(const QString &settingsString) { PortSettingsStruct s; s.portName = #ifdef Q_OS_WIN32 "COM1"; #else "/dev/ttyS0"; #endif s.baudRate = 9600; s.bufSize = 1024; s.dataBits = QSerialPort::Data8; s.stopBits = QSerialPort::OneStop; s.parity = QSerialPort::NoParity; s.dtr = false; s.rts = false; QStringList lst = settingsString.split(":"); int indx = 0; if(lst.size() > 0) { QString str = lst.at(indx++); bool ok; qint32 n = str.toInt(&ok); if(ok) { s.baudRate = n; } else { s.portName = str; if(indx < lst.size()) { str = lst.at(indx++); n = str.toInt(&ok); if(ok) { s.baudRate = n; } } } if(indx < lst.size()) { s.dataBits = strToDataBits( lst.at(indx++) ); } if(indx < lst.size()) { s.stopBits = strToStopBits( lst.at(indx++) ); } if(indx < lst.size()) { s.parity = strToParity( lst.at(indx++) ); } } return s; } //======================================================================================================== QString ComPort::settingsString(const PortSettingsStruct &portSettings, bool withPortName) { return QString( (withPortName ? portSettings.portName + ":" : "") + QString::number(portSettings.baudRate) + ":" + dataBitsToStr(portSettings.dataBits) + ":" + stopBitsToStr(portSettings.stopBits) + ":" + parityToStr(portSettings.parity) ); } //======================================================================================================== PortSettingsStruct ComPort::portSettings() { PortSettingsStruct res; res.portName = port.portName(); res.baudRate = port.baudRate(); res.bufSize = static_cast<qint32>(port.readBufferSize()); res.dataBits = port.dataBits(); res.stopBits = port.stopBits(); res.parity = port.parity(); res.dtr = port.isDataTerminalReady(); res.rts = port.isRequestToSend(); return res; } //======================================================================================================== #ifdef QT_GUI_LIB //======================================================================================================== void ComPort::fillPortNameBox(QComboBox *box, const QString &defaultPortName) { if(!box) return; box->clear(); int indx = 0; QSerialPortInfo info; for(auto i=0; i<info.availablePorts().size(); ++i) { QString portName = info.availablePorts().at(i).portName(); box->addItem( portName ); if(portName == defaultPortName) indx = i; } if(indx < box->count()) box->setCurrentIndex(indx); if(box->isEditable() && !defaultPortName.isEmpty() && (box->currentText() != defaultPortName)) box->setCurrentText(defaultPortName); } //======================================================================================================== void ComPort::fillBaudRateBox(QComboBox *box, qint32 defaultBaudRate) { if(!box) return; box->clear(); box->addItem( "300", 300); box->addItem( "600", 600); box->addItem( "1200", 1200); box->addItem( "2400", 2400); box->addItem( "4800", 4800); box->addItem( "9600", 9600); box->addItem( "19200", 19200); box->addItem( "38400", 38400); box->addItem( "57600", 57600); box->addItem( "115200", 115200); for(auto i=0; i<box->count(); ++i) { if(box->itemData(i).toInt() == defaultBaudRate) { box->setCurrentIndex(i); break; } } } //======================================================================================================== void ComPort::fillDataBitsBox(QComboBox *box, QSerialPort::DataBits defaultDataBits) { if(!box) return; box->clear(); int indx = 0; for(auto i=5; i<=8; ++i) { QSerialPort::DataBits d = static_cast<QSerialPort::DataBits>(i); box->addItem( dataBitsToStr(d), d ); if(d == defaultDataBits) indx = box->count()-1; } if(indx < box->count()) box->setCurrentIndex(indx); } //======================================================================================================== void ComPort::fillStopBitsBox(QComboBox *box, QSerialPort::StopBits defaultStopBits) { if(!box) return; box->clear(); box->addItem( stopBitsToStr(QSerialPort::OneStop), QSerialPort::OneStop); box->addItem( stopBitsToStr(QSerialPort::OneAndHalfStop), QSerialPort::OneAndHalfStop); box->addItem( stopBitsToStr(QSerialPort::TwoStop), QSerialPort::TwoStop); for(auto i=0; i<box->count(); ++i) { if(box->itemData(i).toInt() == static_cast<int>(defaultStopBits)) { box->setCurrentIndex(i); break; } } } //======================================================================================================== void ComPort::fillParityBox(QComboBox *box, QSerialPort::Parity defaultParity) { if(!box) return; box->clear(); box->addItem( parityToStr(QSerialPort::NoParity), QSerialPort::NoParity); box->addItem( parityToStr(QSerialPort::EvenParity), QSerialPort::EvenParity); box->addItem( parityToStr(QSerialPort::OddParity), QSerialPort::OddParity); box->addItem( parityToStr(QSerialPort::SpaceParity), QSerialPort::SpaceParity); box->addItem( parityToStr(QSerialPort::MarkParity), QSerialPort::MarkParity); for(auto i=0; i<box->count(); ++i) { if(box->itemData(i).toInt() == static_cast<int>(defaultParity)) { box->setCurrentIndex(i); break; } } } //======================================================================================================== #endif //======================================================================================================== } // namespace nayk
43.689408
145
0.514855
SammyEnigma
b3b4c439f875d44e9c0e00a049a5a161a4f7b5d9
7,403
cpp
C++
src/postprocess/VrHooks.cpp
fholger/openvr_foveated
542768df39864386deebf260e73cf5158851fb9c
[ "BSD-3-Clause" ]
76
2021-12-22T23:52:06.000Z
2022-03-30T05:52:02.000Z
src/postprocess/VrHooks.cpp
fholger/openvr_foveated
542768df39864386deebf260e73cf5158851fb9c
[ "BSD-3-Clause" ]
10
2021-12-23T05:46:18.000Z
2022-01-15T11:43:31.000Z
src/postprocess/VrHooks.cpp
fholger/openvr_foveated
542768df39864386deebf260e73cf5158851fb9c
[ "BSD-3-Clause" ]
3
2021-12-23T00:55:40.000Z
2022-03-02T12:08:16.000Z
#include "VrHooks.h" #include "Config.h" #include "PostProcessor.h" #include <openvr.h> #include <MinHook.h> #include <unordered_map> #include <unordered_set> namespace { std::unordered_map<void*, void*> hooksToOriginal; bool ivrSystemHooked = false; bool ivrCompositorHooked = false; ID3D11DeviceContext *hookedContext = nullptr; ID3D11Device *device = nullptr; vr::PostProcessor postProcessor; void InstallVirtualFunctionHook(void *instance, uint32_t methodPos, void *hookFunction) { LPVOID* vtable = *((LPVOID**)instance); LPVOID pTarget = vtable[methodPos]; LPVOID pOriginal = nullptr; MH_CreateHook(pTarget, hookFunction, &pOriginal); MH_EnableHook(pTarget); hooksToOriginal[hookFunction] = pOriginal; } template<typename T> T CallOriginal(T hookFunction) { return (T)hooksToOriginal[hookFunction]; } void IVRSystem_GetRecommendedRenderTargetSize(vr::IVRSystem *self, uint32_t *pnWidth, uint32_t *pnHeight) { CallOriginal(IVRSystem_GetRecommendedRenderTargetSize)(self, pnWidth, pnHeight); if (pnWidth == nullptr || pnHeight == nullptr) { return; } } vr::EVRCompositorError IVRCompositor_Submit(vr::IVRCompositor *self, vr::EVREye eEye, const vr::Texture_t *pTexture, const vr::VRTextureBounds_t *pBounds, vr::EVRSubmitFlags nSubmitFlags) { void *origHandle = pTexture->handle; postProcessor.Apply(eEye, pTexture, pBounds, nSubmitFlags); vr::EVRCompositorError error = CallOriginal(IVRCompositor_Submit)(self, eEye, pTexture, pBounds, nSubmitFlags); if (error != vr::VRCompositorError_None) { if (Config::Instance().debugMode) Log() << "Error when submitting for eye " << eEye << ": " << error << std::endl; } const_cast<vr::Texture_t*>(pTexture)->handle = origHandle; return error; } vr::EVRCompositorError IVRCompositor_Submit_008(vr::IVRCompositor *self, vr::EVREye eEye, unsigned int eTextureType, void *pTexture, const vr::VRTextureBounds_t *pBounds, vr::EVRSubmitFlags nSubmitFlags) { if (eTextureType == 0) { // texture type is DirectX vr::Texture_t texture; texture.eType = vr::TextureType_DirectX; texture.eColorSpace = vr::ColorSpace_Auto; texture.handle = pTexture; postProcessor.Apply(eEye, &texture, pBounds, nSubmitFlags); pTexture = texture.handle; } return CallOriginal(IVRCompositor_Submit_008)(self, eEye, eTextureType, pTexture, pBounds, nSubmitFlags); } vr::EVRCompositorError IVRCompositor_Submit_007(vr::IVRCompositor *self, vr::EVREye eEye, unsigned int eTextureType, void *pTexture, const vr::VRTextureBounds_t *pBounds) { if (eTextureType == 0) { // texture type is DirectX vr::Texture_t texture; texture.eType = vr::TextureType_DirectX; texture.eColorSpace = vr::ColorSpace_Auto; texture.handle = pTexture; postProcessor.Apply(eEye, &texture, pBounds, vr::Submit_Default); pTexture = texture.handle; } return CallOriginal(IVRCompositor_Submit_007)(self, eEye, eTextureType, pTexture, pBounds); } using Microsoft::WRL::ComPtr; HRESULT D3D11Context_ClearDepthStencilView(ID3D11DeviceContext *self, ID3D11DepthStencilView *pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) { HRESULT ret = CallOriginal(D3D11Context_ClearDepthStencilView)(self, pDepthStencilView, ClearFlags, Depth, Stencil); if (ClearFlags & D3D11_CLEAR_DEPTH) postProcessor.ApplyFixedFoveatedRendering(pDepthStencilView, Depth, Stencil); return ret; } void D3D11Context_OMSetRenderTargets( ID3D11DeviceContext *self, UINT NumViews, ID3D11RenderTargetView * const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView) { CallOriginal(D3D11Context_OMSetRenderTargets)(self, NumViews, ppRenderTargetViews, pDepthStencilView); postProcessor.OnRenderTargetChange( NumViews, ppRenderTargetViews ); } void D3D11Context_OMSetRenderTargetsAndUnorderedAccessViews( ID3D11DeviceContext *self, UINT NumRTVs, ID3D11RenderTargetView * const *ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView, UINT UAVStartSlot, UINT NumUAVs, ID3D11UnorderedAccessView * const *ppUnorderedAccessViews, const UINT *pUAVInitialCounts) { CallOriginal(D3D11Context_OMSetRenderTargetsAndUnorderedAccessViews)(self, NumRTVs, ppRenderTargetViews, pDepthStencilView, UAVStartSlot, NumUAVs, ppUnorderedAccessViews, pUAVInitialCounts); postProcessor.OnRenderTargetChange( NumRTVs, ppRenderTargetViews ); } } void InitHooks() { Log() << "Initializing hooks...\n"; MH_Initialize(); } void ShutdownHooks() { Log() << "Shutting down hooks...\n"; MH_Uninitialize(); hooksToOriginal.clear(); ivrSystemHooked = false; ivrCompositorHooked = false; hookedContext = nullptr; device = nullptr; postProcessor.Reset(); } void HookVRInterface(const char *version, void *instance) { // Only install hooks once, for the first interface version encountered to avoid duplicated hooks // This is necessary because vrclient.dll may create an internal instance with a different version // than the application to translate older versions, which with hooks installed for both would cause // an infinite loop Log() << "Requested interface " << version << "\n"; // ----------------------- // - Hooks for IVRSystem - // ----------------------- unsigned int system_version = 0; if (!ivrSystemHooked && std::sscanf(version, "IVRSystem_%u", &system_version)) { // The 'IVRSystem::GetRecommendedRenderTargetSize' function definition has been the same since the initial // release of OpenVR; however, in early versions there was an additional method in front of it. uint32_t methodPos = (system_version >= 9 ? 0 : 1); Log() << "Injecting GetRecommendedRenderTargetSize into " << version << std::endl; InstallVirtualFunctionHook(instance, methodPos, IVRSystem_GetRecommendedRenderTargetSize); ivrSystemHooked = true; } // --------------------------- // - Hooks for IVRCompositor - // --------------------------- unsigned int compositor_version = 0; if (!ivrCompositorHooked && std::sscanf(version, "IVRCompositor_%u", &compositor_version)) { if (compositor_version >= 9) { Log() << "Injecting Submit into " << version << std::endl; uint32_t methodPos = compositor_version >= 12 ? 5 : 4; InstallVirtualFunctionHook(instance, methodPos, IVRCompositor_Submit); ivrCompositorHooked = true; } else if (compositor_version == 8) { Log() << "Injecting Submit into " << version << std::endl; InstallVirtualFunctionHook(instance, 6, IVRCompositor_Submit_008); ivrCompositorHooked = true; } else if (compositor_version == 7) { Log() << "Injecting Submit into " << version << std::endl; InstallVirtualFunctionHook(instance, 6, IVRCompositor_Submit_007); ivrCompositorHooked = true; } } } void HookD3D11Context( ID3D11DeviceContext *context, ID3D11Device *pDevice ) { device = pDevice; if (context != hookedContext) { Log() << "Injecting ClearDepthStencilView into D3D11DeviceContext" << std::endl; InstallVirtualFunctionHook(context, 53, D3D11Context_ClearDepthStencilView); Log() << "Injecting OMSetRenderTargets into D3D11DeviceContext" << std::endl; InstallVirtualFunctionHook(context, 33, D3D11Context_OMSetRenderTargets); Log() << "Injecting OMSetRenderTargetsAndUnorderedAccessViews into D3D11DeviceContext" << std::endl; InstallVirtualFunctionHook(context, 34, D3D11Context_OMSetRenderTargetsAndUnorderedAccessViews); hookedContext = context; } }
38.963158
206
0.749021
fholger
b3b59670970b0825a6e0861126e8a9bc9b177aa0
17,708
cpp
C++
Minimap Source/Minimap/j1Map.cpp
OscarHernandezG/MinimapTestbed
4c06210c0e67af037232de95e02fbe44ec900cbc
[ "MIT" ]
null
null
null
Minimap Source/Minimap/j1Map.cpp
OscarHernandezG/MinimapTestbed
4c06210c0e67af037232de95e02fbe44ec900cbc
[ "MIT" ]
null
null
null
Minimap Source/Minimap/j1Map.cpp
OscarHernandezG/MinimapTestbed
4c06210c0e67af037232de95e02fbe44ec900cbc
[ "MIT" ]
null
null
null
#include <math.h> #include "Brofiler\Brofiler.h" #include "Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Render.h" #include "j1Textures.h" #include "j1Collision.h" #include "j1Scene.h" #include "j1Audio.h" #include "j1Map.h" #include "j1Window.h" j1Map::j1Map() : j1Module(), isMapLoaded(false) { name.assign("map"); } // Destructor j1Map::~j1Map() {} // Called before render is available bool j1Map::Awake(pugi::xml_node& config) { LOG("Loading Map Parser"); bool ret = true; folder.assign(config.child("folder").childValue()); blitOffset = config.child("general").child("blit").attribute("offset").as_int(); cameraBlit = config.child("general").child("cameraBlit").attribute("value").as_bool(); culingOffset = config.child("general").child("culing").attribute("value").as_int(); return ret; } void j1Map::Draw() { BROFILER_CATEGORY("Draw(notAbove)", Profiler::Color::Azure); if (!isMapLoaded) return; // Prepare the loop to draw all tilesets + Blit for (list<MapLayer*>::const_iterator layer = data.layers.begin(); layer != data.layers.end(); ++layer) { if ((*layer)->index != LAYER_TYPE_ABOVE) { for (int i = 0; i < (*layer)->width; ++i) { for (int j = 0; j < (*layer)->height; ++j) { int tile_id = (*layer)->Get(i, j); if (tile_id > 0) { TileSet* tileset = GetTilesetFromTileId(tile_id); SDL_Rect rect = tileset->GetTileRect(tile_id); SDL_Rect* section = &rect; iPoint world = MapToWorld(i, j); App->render->Blit(tileset->texture, world.x, world.y, section, (*layer)->speed); } }//for }//for } } } TileSet* j1Map::GetTilesetFromTileId(int id) const { list<TileSet*>::const_iterator item = data.tilesets.begin(); TileSet* set = *item; while (item != data.tilesets.end()) { if (id < (*item)->firstgid) { set = *(item--); break; } set = *item; item++; } return set; } iPoint j1Map::MapToWorld(int x, int y) const { iPoint ret; if (data.type == MAPTYPE_ORTHOGONAL) { ret.x = x * data.tileWidth; ret.y = y * data.tileHeight; } else if (data.type == MAPTYPE_ISOMETRIC) { ret.x = (x - y) * (data.tileWidth * 0.5f); ret.y = (x + y) * (data.tileHeight * 0.5f); } else { LOG("Unknown map type"); ret.x = x; ret.y = y; } return ret; } iPoint j1Map::WorldToMap(int x, int y) const { iPoint ret(0, 0); if (data.type == MAPTYPE_ORTHOGONAL) { ret.x = x / data.tileWidth; ret.y = y / data.tileHeight; } else if (data.type == MAPTYPE_ISOMETRIC) { float half_width = data.tileWidth * 0.5f; float half_height = data.tileHeight * 0.5f; ret.x = int((x / half_width + y / half_height) / 2) - 1; ret.y = int((y / half_height - (x / half_width)) / 2); } else { LOG("Unknown map type"); ret.x = x; ret.y = y; } return ret; } SDL_Rect TileSet::GetTileRect(int id) const { int relativeId = id - firstgid; SDL_Rect rect; rect.w = tileWidth; rect.h = tileHeight; rect.x = margin + ((rect.w + spacing) * (relativeId % numTilesWidth)); rect.y = margin + ((rect.h + spacing) * (relativeId / numTilesWidth)); return rect; } // Called before quitting bool j1Map::CleanUp() { bool ret = true; LOG("Unloading map"); // Remove all objectGroups list<ObjectGroup*>::const_iterator objectGroup; objectGroup = data.objectGroups.begin(); while (objectGroup != data.objectGroups.end()) { // Remove all objects inside the objectGroup list<Object*>::const_iterator object; object = (*objectGroup)->objects.begin(); while (object != (*objectGroup)->objects.end()) { delete (*object); object++; } (*objectGroup)->objects.clear(); // Remove the objectGroup delete (*objectGroup); objectGroup++; } data.objectGroups.clear(); // Remove all tilesets list<TileSet*>::const_iterator item; item = data.tilesets.begin(); while (item != data.tilesets.end()) { delete *item; item++; } data.tilesets.clear(); // Remove all layers list<MapLayer*>::const_iterator item1; item1 = data.layers.begin(); while (item1 != data.layers.end()) { delete *item1; item1++; } data.layers.clear(); delete collisionLayer; delete aboveLayer; collisionLayer = nullptr; aboveLayer = nullptr; // Clean up the pugui tree mapFile.reset(); return ret; } // Unload map bool j1Map::UnLoad() { bool ret = true; LOG("Unloading map"); // Remove all objectGroups list<ObjectGroup*>::const_iterator objectGroup; objectGroup = data.objectGroups.begin(); while (objectGroup != data.objectGroups.end()) { // Remove all objects inside the objectGroup list<Object*>::const_iterator object; object = (*objectGroup)->objects.begin(); while (object != (*objectGroup)->objects.end()) { delete (*object); object++; } (*objectGroup)->objects.clear(); // Remove the objectGroup delete (*objectGroup); objectGroup++; } data.objectGroups.clear(); // Remove all tilesets list<TileSet*>::const_iterator item; item = data.tilesets.begin(); while (item != data.tilesets.end()) { delete *item; item++; } data.tilesets.clear(); // Remove all layers list<MapLayer*>::const_iterator item1; item1 = data.layers.begin(); while (item1 != data.layers.end()) { delete *item1; item1++; } data.layers.clear(); delete collisionLayer; delete aboveLayer; collisionLayer = nullptr; aboveLayer = nullptr; return ret; } // Load map general properties bool j1Map::LoadMap() { bool ret = true; pugi::xml_node map = mapFile.child("map"); if (map == NULL) { LOG("Error parsing map xml file: Cannot find 'map' tag."); ret = false; } else { data.width = map.attribute("width").as_int(); data.height = map.attribute("height").as_int(); data.tileWidth = map.attribute("tilewidth").as_int(); data.tileHeight = map.attribute("tileheight").as_int(); string backgroundColor(map.attribute("backgroundcolor").as_string()); data.backgroundColor.r = 0; data.backgroundColor.g = 0; data.backgroundColor.b = 0; data.backgroundColor.a = 0; if (backgroundColor.size() > 0) { string red, green, blue; red = backgroundColor.substr(1, 2); green = backgroundColor.substr(3, 4); blue = backgroundColor.substr(5, 6); int v = 0; sscanf_s(red.data(), "%x", &v); if (v >= 0 && v <= 255) data.backgroundColor.r = v; sscanf_s(green.data(), "%x", &v); if (v >= 0 && v <= 255) data.backgroundColor.g = v; sscanf_s(blue.data(), "%x", &v); if (v >= 0 && v <= 255) data.backgroundColor.b = v; } string orientation(map.attribute("orientation").as_string()); if (orientation == "orthogonal") { data.type = MAPTYPE_ORTHOGONAL; } else if (orientation == "isometric") { data.type = MAPTYPE_ISOMETRIC; } else if (orientation == "staggered") { data.type = MAPTYPE_STAGGERED; } else { data.type = MAPTYPE_UNKNOWN; } } return ret; } bool j1Map::LoadTilesetDetails(pugi::xml_node& tilesetNode, TileSet* set) { bool ret = true; set->name.assign(tilesetNode.attribute("name").as_string()); set->firstgid = tilesetNode.attribute("firstgid").as_int(); set->tileWidth = tilesetNode.attribute("tilewidth").as_int(); set->tileHeight = tilesetNode.attribute("tileheight").as_int(); set->margin = tilesetNode.attribute("margin").as_int(); set->spacing = tilesetNode.attribute("spacing").as_int(); pugi::xml_node offset = tilesetNode.child("tileoffset"); if (offset != NULL) { set->offsetX = offset.attribute("x").as_int(); set->offsetY = offset.attribute("y").as_int(); } else { set->offsetX = 0; set->offsetY = 0; } return ret; } // Load new map bool j1Map::Load(const char* fileName) { bool ret = true; string tmp = folder.data(); tmp += fileName; pugi::xml_parse_result result = mapFile.loadFile(tmp.data()); if (result == NULL) { LOG("Could not load map xml file %s. pugi error: %s", fileName, result.description()); ret = false; } // Load general info ---------------------------------------------- if (ret) { ret = LoadMap(); } // Load all tilesets info ---------------------------------------------- pugi::xml_node tileset; for (tileset = mapFile.child("map").child("tileset"); tileset && ret; tileset = tileset.next_sibling("tileset")) { TileSet* set = new TileSet(); if (ret) { ret = LoadTilesetDetails(tileset, set); } if (ret) { ret = LoadTilesetImage(tileset, set); } data.tilesets.push_back(set); } // Iterate all layers and load each of them // Load layer info ---------------------------------------------- pugi::xml_node layer; for (layer = mapFile.child("map").child("layer"); layer && ret; layer = layer.next_sibling("layer")) { MapLayer* set = new MapLayer(); if (ret) { ret = LoadLayer(layer, set); } data.layers.push_back(set); } // Load ObjectGroups and GameObjects pugi::xml_node objectGroup; pugi::xml_node object; for (objectGroup = mapFile.child("map").child("objectgroup"); objectGroup && ret; objectGroup = objectGroup.next_sibling("objectgroup")) { ObjectGroup* set = new ObjectGroup(); if (ret) { ret = LoadObjectGroupDetails(objectGroup, set); } for (object = objectGroup.child("object"); object && ret; object = object.next_sibling("object")) { Object* set1 = new Object(); if (ret) { ret = LoadObject(object, set1); } set->objects.push_back(set1); } data.objectGroups.push_back(set); } if (ret) { LOG("Successfully parsed map XML file: %s", fileName); LOG("width: %d height: %d", data.width, data.height); LOG("tile_width: %d tileHeight: %d", data.tileWidth, data.tileHeight); list<TileSet*>::const_iterator item = data.tilesets.begin(); while (item != data.tilesets.end()) { TileSet* s = *item; LOG("Tileset ----"); LOG("name: %s firstgid: %d", s->name.data(), s->firstgid); LOG("tile width: %d tile height: %d", s->tileWidth, s->tileHeight); LOG("spacing: %d margin: %d", s->spacing, s->margin); item++; } // Add info here about your loaded layers // Adapt this vcode with your own variables list<MapLayer*>::const_iterator item_layer = data.layers.begin(); while (item_layer != data.layers.end()) { MapLayer* l = *item_layer; LOG("Layer ----"); LOG("name: %s", l->name.data()); LOG("tile width: %d tile height: %d", l->width, l->height); item_layer++; } // Info about ObjectGroups and GameObjects list<ObjectGroup*>::const_iterator item_group = data.objectGroups.begin(); while (item_group != data.objectGroups.end()) { ObjectGroup* s = *item_group; LOG("Object Group ----"); LOG("name: %s", s->name.data()); list<Object*>::const_iterator item_object = (*item_group)->objects.begin(); while (item_object != (*item_group)->objects.end()) { Object* s = *item_object; LOG("Object ----"); LOG("name: %s", s->name.data()); LOG("id: %d", s->id); LOG("x: %d y: %d", s->x, s->y); LOG("width: %d height: %d", s->width, s->height); item_object++; } item_group++; } } isMapLoaded = ret; return ret; } bool j1Map::LoadTilesetImage(pugi::xml_node& tilesetNode, TileSet* set) { bool ret = true; pugi::xml_node image = tilesetNode.child("image"); if (image == NULL) { LOG("Error parsing tileset xml file: Cannot find 'image' tag."); ret = false; } else { set->texture = App->tex->Load(PATH(folder.data(), image.attribute("source").as_string())); int w, h; SDL_QueryTexture(set->texture, NULL, NULL, &w, &h); set->texWidth = image.attribute("width").as_int(); if (set->texWidth <= 0) { set->texWidth = w; } set->texHeight = image.attribute("height").as_int(); if (set->texHeight <= 0) { set->texHeight = h; } set->numTilesWidth = set->texWidth / set->tileWidth; set->numTilesHeight = set->texHeight / set->tileHeight; } return ret; } // Create the definition for a function that loads a single layer bool j1Map::LoadLayer(pugi::xml_node& node, MapLayer* layer) { bool ret = true; layer->name = node.attribute("name").as_string(); // Set layer index if (layer->name == "Collision") { collisionLayer = layer; layer->index = LAYER_TYPE_COLLISION; } else if (layer->name == "Above") { aboveLayer = layer; layer->index = LAYER_TYPE_ABOVE; } else if (layer->name == "Parallax") { layer->index = LAYER_TYPE_PARALLAX; } layer->width = node.attribute("width").as_uint(); layer->height = node.attribute("height").as_uint(); LoadProperties(node, layer->properties); layer->data = new uint[layer->width * layer->height]; memset(layer->data, 0, layer->width * layer->height); int i = 0; for (pugi::xml_node tileGid = node.child("data").child("tile"); tileGid; tileGid = tileGid.next_sibling("tile")) { layer->data[i++] = tileGid.attribute("gid").as_uint(); } // Read layer properties pugi::xml_node speed = node.child("properties").child("property"); if (speed != nullptr) { string name = speed.attribute("name").as_string(); if (name == "Speed") layer->speed = speed.attribute("value").as_float(); } return ret; } inline uint MapLayer::Get(int x, int y) const { return data[width * y + x]; } // Load a group of properties from a node and fill a list with it bool j1Map::LoadProperties(pugi::xml_node& node, Properties& properties) { bool ret = false; pugi::xml_node data = node.child("properties"); if (data != NULL) { pugi::xml_node prop; for (prop = data.child("property"); prop; prop = prop.next_sibling("property")) { Properties::Property* p = new Properties::Property(); p->name = prop.attribute("name").as_string(); p->value = prop.attribute("value").as_bool(); properties.properties.push_back(p); } } return ret; } bool j1Map::CreateWalkabilityMap(int& width, int& height, uchar** buffer) const { bool ret = false; list<MapLayer*>::const_iterator item; item = data.layers.begin(); for (item; item != data.layers.end(); ++item) { MapLayer* layer = *item; if (!layer->properties.GetProperty("Navigation", false)) continue; uchar* map = new uchar[layer->width*layer->height]; memset(map, 1, layer->width*layer->height); for (int y = 0; y < data.height; ++y) { for (int x = 0; x < data.width; ++x) { int i = (y*layer->width) + x; int tile_id = layer->Get(x, y); TileSet* tileset = (tile_id > 0) ? GetTilesetFromTileId(tile_id) : NULL; if (tileset != NULL) { map[i] = (tile_id - tileset->firstgid) > 0 ? 0 : 1; /*TileType* ts = tileset->GetTileType(tile_id); if(ts != NULL) { map[i] = ts->properties.Get("walkable", 1); }*/ } } } *buffer = map; width = data.width; height = data.height; ret = true; break; } return ret; } bool Properties::GetProperty(const char* value, bool default_value) const { list<Property*>::const_iterator item = properties.begin(); while (item != properties.end()) { if ((*item)->name == value) return (*item)->value; item++; } return default_value; } bool j1Map::LoadObjectGroupDetails(pugi::xml_node& objectGroupNode, ObjectGroup* objectGroup) { bool ret = true; objectGroup->name.assign(objectGroupNode.attribute("name").as_string()); return ret; } bool j1Map::LoadObject(pugi::xml_node& objectNode, Object* object) { bool ret = true; object->name = objectNode.attribute("name").as_string(); object->id = objectNode.attribute("id").as_uint(); object->width = objectNode.attribute("width").as_uint(); object->height = objectNode.attribute("height").as_uint(); object->x = objectNode.attribute("x").as_uint(); object->y = objectNode.attribute("y").as_uint(); object->type = objectNode.attribute("type").as_uint(); return ret; } fPoint MapData::GetObjectPosition(string groupObject, string object) { fPoint pos = { 0,0 }; list<ObjectGroup*>::const_iterator item; item = objectGroups.begin(); int ret = true; while (item != objectGroups.end() && ret) { if ((*item)->name == groupObject) { list<Object*>::const_iterator item1; item1 = (*item)->objects.begin(); while (item1 != (*item)->objects.end() && ret) { if ((*item1)->name == object) { pos.x = (*item1)->x; pos.y = (*item1)->y; ret = false; } item1++; } } item++; } return pos; } fPoint MapData::GetObjectSize(string groupObject, string object) { fPoint size = { 0,0 }; list<ObjectGroup*>::const_iterator item; item = objectGroups.begin(); int ret = true; while (item != objectGroups.end() && ret) { if ((*item)->name == groupObject) { list<Object*>::const_iterator item1; item1 = (*item)->objects.begin(); while (item1 != (*item)->objects.end() && ret) { if ((*item1)->name == object) { size.x = (*item1)->width; size.y = (*item1)->height; ret = false; } item1++; } } item++; } return size; } Object* MapData::GetObjectByName(string groupObject, string object) { Object* obj = nullptr; list<ObjectGroup*>::const_iterator item; item = objectGroups.begin(); int ret = true; while (item != objectGroups.end() && ret) { if ((*item)->name == groupObject) { list<Object*>::const_iterator item1; item1 = (*item)->objects.begin(); while (item1 != (*item)->objects.end() && ret) { if ((*item1)->name == object) { obj = *item1; ret = false; } item1++; } } item++; } return obj; } bool MapData::CheckIfEnter(string groupObject, string object, fPoint position) { fPoint objectPos = GetObjectPosition(groupObject, object); fPoint objectSize = GetObjectSize(groupObject, object); return (objectPos.x < position.x + 1 && objectPos.x + objectSize.x > position.x && objectPos.y < position.y + 1 && objectSize.y + objectPos.y > position.y); }
21.516403
157
0.63508
OscarHernandezG
b3b668b8797a8ff65a370f2bfaa392c52bc2462a
20,305
cpp
C++
src/CompressibleInterface.cpp
StephanLenz/Gas-Kinetic-Scheme
bb92a9640cd95ac9342adf8c31c4800414d5950a
[ "MIT" ]
2
2018-03-05T07:51:01.000Z
2021-10-30T08:44:41.000Z
src/CompressibleInterface.cpp
StephanLenz/Gas-Kinetic-Scheme
bb92a9640cd95ac9342adf8c31c4800414d5950a
[ "MIT" ]
null
null
null
src/CompressibleInterface.cpp
StephanLenz/Gas-Kinetic-Scheme
bb92a9640cd95ac9342adf8c31c4800414d5950a
[ "MIT" ]
1
2021-03-28T12:42:15.000Z
2021-03-28T12:42:15.000Z
#include "Interface.h" #include "CompressibleInterface.h" #include <sstream> CompressibleInterface::CompressibleInterface() { } CompressibleInterface::CompressibleInterface(Cell* negCell, Cell* posCell, float2 center, float2 normal, FluidParameter fluidParam, InterfaceBC* BC) : Interface(negCell, posCell, center, normal, fluidParam, BC) { } CompressibleInterface::~CompressibleInterface() { } void CompressibleInterface::computeTimeDerivative(double * prim, double * MomentU, double * MomentV, double * MomentXi, double* a, double* b, double * timeGrad) { // ======================================================================== timeGrad[0] = a[0] * MomentU[1] * MomentV[0] + a[1] * MomentU[2] * MomentV[0] + a[2] * MomentU[1] * MomentV[1] + a[3] * 0.5 * ( MomentU[3] * MomentV[0] + MomentU[1] * MomentV[2] + MomentU[1] * MomentV[0] * MomentXi[2] ) + b[0] * MomentU[0] * MomentV[1] + b[1] * MomentU[1] * MomentV[1] + b[2] * MomentU[0] * MomentV[2] + b[3] * 0.5 * ( MomentU[2] * MomentV[1] + MomentU[0] * MomentV[3] + MomentU[0] * MomentV[1] * MomentXi[2] ) // this part comes from the inclusion of the forcing into the flux computation //+ 2.0 * prim[3] * ( MomentU[0]*MomentV[0] * prim[1] - MomentU[1]*MomentV[0] ) * this->fluidParam.Force.x //+ 2.0 * prim[3] * ( MomentU[0]*MomentV[0] * prim[2] - MomentU[0]*MomentV[1] ) * this->fluidParam.Force.y ; // ======================================================================== // ======================================================================== timeGrad[1] = a[0] * MomentU[2] * MomentV[0] + a[1] * MomentU[3] * MomentV[0] + a[2] * MomentU[2] * MomentV[1] + a[3] * 0.5 * ( MomentU[4] * MomentV[0] + MomentU[2] * MomentV[2] + MomentU[2] * MomentV[0] * MomentXi[2] ) + b[0] * MomentU[1] * MomentV[1] + b[1] * MomentU[2] * MomentV[1] + b[2] * MomentU[1] * MomentV[2] + b[3] * 0.5 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] ) // this part comes from the inclusion of the forcing into the flux computation //+ 2.0 * prim[3] * ( MomentU[1]*MomentV[0] * prim[1] - MomentU[2]*MomentV[0] ) * this->fluidParam.Force.x //+ 2.0 * prim[3] * ( MomentU[1]*MomentV[0] * prim[2] - MomentU[1]*MomentV[1] ) * this->fluidParam.Force.y ; // ======================================================================== // ======================================================================== timeGrad[2] = a[0] * MomentU[1] * MomentV[1] + a[1] * MomentU[2] * MomentV[1] + a[2] * MomentU[1] * MomentV[2] + a[3] * 0.5 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] ) + b[0] * MomentU[0] * MomentV[2] + b[1] * MomentU[1] * MomentV[2] + b[2] * MomentU[0] * MomentV[3] + b[3] * 0.5 * ( MomentU[2] * MomentV[2] + MomentU[0] * MomentV[4] + MomentU[0] * MomentV[2] * MomentXi[2] ) // this part comes from the inclusion of the forcing into the flux computation //+ 2.0 * prim[3] * ( MomentU[0]*MomentV[1] * prim[1] - MomentU[1]*MomentV[1] ) * this->fluidParam.Force.x //+ 2.0 * prim[3] * ( MomentU[0]*MomentV[1] * prim[2] - MomentU[0]*MomentV[2] ) * this->fluidParam.Force.y ; // ======================================================================== // ======================================================================== timeGrad[3] = a[0] * 0.50 * ( MomentU[3] * MomentV[0] + MomentU[1] * MomentV[2] + MomentU[1] * MomentV[0] * MomentXi[2] ) + a[1] * 0.50 * ( MomentU[4] * MomentV[0] + MomentU[2] * MomentV[2] + MomentU[2] * MomentV[0] * MomentXi[2] ) + a[2] * 0.50 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] ) + a[3] * 0.25 * ( MomentU[5] + MomentU[1]* ( MomentV[4] + MomentXi[4] ) + 2.0 * MomentU[3] * MomentV[2] + 2.0 * MomentU[3] * MomentXi[2] + 2.0 * MomentU[1] * MomentV[2] * MomentXi[2] ) + b[0] * 0.50 * ( MomentU[2] * MomentV[1] + MomentU[0] * MomentV[3] + MomentU[0] * MomentV[1] * MomentXi[2] ) + b[1] * 0.50 * ( MomentU[3] * MomentV[1] + MomentU[1] * MomentV[3] + MomentU[1] * MomentV[1] * MomentXi[2] ) + b[2] * 0.50 * ( MomentU[2] * MomentV[2] + MomentU[0] * MomentV[4] + MomentU[0] * MomentV[2] * MomentXi[2] ) + b[3] * 0.25 * ( MomentV[5] + MomentV[1] * ( MomentU[4] + MomentXi[4] ) + 2.0 * MomentU[2] * MomentV[3] + 2.0 * MomentU[2] * MomentV[1] * MomentXi[2] + 2.0 * MomentV[3] * MomentXi[2] ) // this part comes from the inclusion of the forcing into the flux computation //+ prim[3] * ( ( MomentU[2] + MomentV[2] + MomentXi[2] ) * prim[1] // - ( MomentU[3] * MomentV[0] + MomentU[1] * MomentV[2] + MomentU[1] * MomentV[0] * MomentXi[2] ) // ) * this->fluidParam.Force.x //+ prim[3] * ( ( MomentU[2] + MomentV[2] + MomentXi[2] ) * prim[2] // - ( MomentU[2] * MomentV[1] + MomentU[0] * MomentV[3] + MomentU[0] * MomentV[1] * MomentXi[2] ) // ) * this->fluidParam.Force.y ; // ======================================================================== timeGrad[0] *= -1.0; timeGrad[1] *= -1.0; timeGrad[2] *= -1.0; timeGrad[3] *= -1.0; } void CompressibleInterface::assembleFlux(double * MomentU, double * MomentV, double * MomentXi, double * a, double * b, double * A, double * timeCoefficients, double dy, double* prim, double tau) { double Flux_1[4]; double Flux_2[4]; double Flux_3[4]; int u = 1; int v = 0; // ======================================================================== Flux_1[0] = MomentU[0+u] * MomentV[0+v]; Flux_1[1] = MomentU[1+u] * MomentV[0+v]; Flux_1[2] = MomentU[0+u] * MomentV[1+v]; Flux_1[3] = 0.5 * ( MomentU[2+u] * MomentV[0+v] + MomentU[0+u] * MomentV[2+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[2] ); // ======================================================================== // ================================================================================================================================================ // ================================================================================================================================================ // ================================================================================================================================================ // ======================================================================== Flux_2[0] = ( a[0] * MomentU[1+u] * MomentV[0+v] + a[1] * MomentU[2+u] * MomentV[0+v] + a[2] * MomentU[1+u] * MomentV[1+v] + a[3] * 0.5 * ( MomentU[3+u] * MomentV[0+v] + MomentU[1+u] * MomentV[2+v] + MomentU[1+u] * MomentV[0+v] * MomentXi[2] ) + b[0] * MomentU[0+u] * MomentV[1+v] + b[1] * MomentU[1+u] * MomentV[1+v] + b[2] * MomentU[0+u] * MomentV[2+v] + b[3] * 0.5 * ( MomentU[2+u] * MomentV[1+v] + MomentU[0+u] * MomentV[3+v] + MomentU[0+u] * MomentV[1+v] * MomentXi[2] ) ) // this part comes from the inclusion of the forcing into the flux computation //+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[0+v] * prim[1] - MomentU[1+u]*MomentV[0+v] ) * this->fluidParam.Force.x //+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[0+v] * prim[2] - MomentU[0+u]*MomentV[1+v] ) * this->fluidParam.Force.y ; // ======================================================================== // ======================================================================== Flux_2[1] = ( a[0] * MomentU[2+u] * MomentV[0+v] + a[1] * MomentU[3+u] * MomentV[0+v] + a[2] * MomentU[2+u] * MomentV[1+v] + a[3] * 0.5 * ( MomentU[4+u] * MomentV[0+v] + MomentU[2+u] * MomentV[2+v] + MomentU[2+u] * MomentV[0+v] * MomentXi[2] ) + b[0] * MomentU[1+u] * MomentV[1+v] + b[1] * MomentU[2+u] * MomentV[1+v] + b[2] * MomentU[1+u] * MomentV[2+v] + b[3] * 0.5 * ( MomentU[3+u] * MomentV[1+v] + MomentU[1+u] * MomentV[3+v] + MomentU[1+u] * MomentV[1+v] * MomentXi[2] ) ) // this part comes from the inclusion of the forcing into the flux computation //+ 2.0 * prim[3] * ( MomentU[1+u]*MomentV[0+v] * prim[1] - MomentU[2+u]*MomentV[0+v] ) * this->fluidParam.Force.x //+ 2.0 * prim[3] * ( MomentU[1+u]*MomentV[0+v] * prim[2] - MomentU[1+u]*MomentV[1+v] ) * this->fluidParam.Force.y ; // ======================================================================== // ======================================================================== Flux_2[2] = ( a[0] * MomentU[1+u] * MomentV[1+v] + a[1] * MomentU[2+u] * MomentV[1+v] + a[2] * MomentU[1+u] * MomentV[2+v] + a[3] * 0.5 * ( MomentU[3+u] * MomentV[1+v] + MomentU[1+u] * MomentV[3+v] + MomentU[1+u] * MomentV[1+v] * MomentXi[2] ) + b[0] * MomentU[0+u] * MomentV[2+v] + b[1] * MomentU[1+u] * MomentV[2+v] + b[2] * MomentU[0+u] * MomentV[3+v] + b[3] * 0.5 * ( MomentU[2+u] * MomentV[2+v] + MomentU[0+u] * MomentV[4+v] + MomentU[0+u] * MomentV[2+v] * MomentXi[2] ) ) // this part comes from the inclusion of the forcing into the flux computation //+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[1+v] * prim[1] - MomentU[1+u]*MomentV[1+v] ) * this->fluidParam.Force.x //+ 2.0 * prim[3] * ( MomentU[0+u]*MomentV[1+v] * prim[2] - MomentU[0+u]*MomentV[2+v] ) * this->fluidParam.Force.y ; // ======================================================================== // ======================================================================== Flux_2[3] = 0.5 * ( a[0] * ( MomentU[3+u] * MomentV[0+v] + MomentU[1+u] * MomentV[2+v] + MomentU[1+u] * MomentV[0+v] * MomentXi[2] ) + a[1] * ( MomentU[4+u] * MomentV[0+v] + MomentU[2+u] * MomentV[2+v] + MomentU[2+u] * MomentV[0+v] * MomentXi[2] ) + a[2] * ( MomentU[3+u] * MomentV[1+v] + MomentU[1+u] * MomentV[3+v] + MomentU[1+u] * MomentV[1+v] * MomentXi[2] ) + a[3] * ( 0.5 * ( MomentU[5+u] * MomentV[0+v] + MomentU[1+u] * MomentV[4+v] + MomentU[1+u] * MomentV[0+v] * MomentXi[4] ) + ( MomentU[3+u] * MomentV[2+v] + MomentU[3+u] * MomentV[0+v] * MomentXi[2] + MomentU[1+u] * MomentV[2+v] * MomentXi[2] ) ) + b[0] * ( MomentU[2+u] * MomentV[1+v] + MomentU[0+u] * MomentV[3+v] + MomentU[0+u] * MomentV[1+v] * MomentXi[2] ) + b[1] * ( MomentU[3+u] * MomentV[1+v] + MomentU[1+u] * MomentV[3+v] + MomentU[1+u] * MomentV[1+v] * MomentXi[2] ) + b[2] * ( MomentU[2+u] * MomentV[2+v] + MomentU[0+u] * MomentV[4+v] + MomentU[0+u] * MomentV[2+v] * MomentXi[2] ) + b[3] * ( 0.5 * ( MomentU[4+u] * MomentV[1+v] + MomentU[0+u] * MomentV[5+v] + MomentU[0+u] * MomentV[1+v] * MomentXi[4] ) + ( MomentU[2+u] * MomentV[3+v] + MomentU[2+u] * MomentV[1+v] * MomentXi[2] + MomentU[0+u] * MomentV[3+v] * MomentXi[2] ) ) ) // this part comes from the inclusion of the forcing into the flux computation //+ prim[3] * ( ( MomentU[2+u] * MomentV[0+v] + MomentU[0+u] * MomentV[2+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[2] ) * prim[1] // - ( MomentU[3+u] * MomentV[0+v] + MomentU[1+u] * MomentV[2+v] + MomentU[1+u] * MomentV[0+v] * MomentXi[2] ) // ) * this->fluidParam.Force.x //+ prim[3] * ( ( MomentU[2+u] * MomentV[0+v] + MomentU[0+u] * MomentV[2+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[2] ) * prim[2] // - ( MomentU[2+u] * MomentV[1+v] + MomentU[0+u] * MomentV[3+v] + MomentU[0+u] * MomentV[1+v] * MomentXi[2] ) // ) * this->fluidParam.Force.y ; // ======================================================================== // ================================================================================================================================================ // ================================================================================================================================================ // ================================================================================================================================================ // ======================================================================== Flux_3[0] = ( A[0] * MomentU[0+u] * MomentV[0+v] + A[1] * MomentU[1+u] * MomentV[0+v] + A[2] * MomentU[0+u] * MomentV[1+v] + A[3] * 0.5 * ( MomentU[2+u]*MomentV[0+v] + MomentU[0+u]*MomentV[2+v] + MomentU[0+u]*MomentV[0+v]*MomentXi[2] ) ); // ======================================================================== // ======================================================================== Flux_3[1] = ( A[0] * MomentU[1+u] * MomentV[0+v] + A[1] * MomentU[2+u] * MomentV[0+v] + A[2] * MomentU[1+u] * MomentV[1+v] + A[3] * 0.5 * ( MomentU[3+u]*MomentV[0+v] + MomentU[1+u]*MomentV[2+v] + MomentU[1+u]*MomentV[0+v]*MomentXi[2] ) ); // ======================================================================== // ======================================================================== Flux_3[2] = ( A[0] * MomentU[0+u] * MomentV[1+v] + A[1] * MomentU[1+u] * MomentV[1+v] + A[2] * MomentU[0+u] * MomentV[2+v] + A[3] * 0.5 * ( MomentU[2+u]*MomentV[1+v] + MomentU[0+u]*MomentV[3+v] + MomentU[0+u]*MomentV[1+v]*MomentXi[2] ) ); // ======================================================================== // ======================================================================== Flux_3[3] = 0.5 * ( A[0] * ( MomentU[2+u] * MomentV[0+v] + MomentU[0+u] * MomentV[2+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[2] ) + A[1] * ( MomentU[3+u] * MomentV[0+v] + MomentU[1+u] * MomentV[2+v] + MomentU[1+u] * MomentV[0+v] * MomentXi[2] ) + A[2] * ( MomentU[2+u] * MomentV[1+v] + MomentU[0+u] * MomentV[3+v] + MomentU[0+u] * MomentV[1+v] * MomentXi[2] ) + A[3] * ( 0.5 * ( MomentU[4+u] * MomentV[0+v] + MomentU[0+u] * MomentV[4+v] + MomentU[0+u] * MomentV[0+v] * MomentXi[4] ) + ( MomentU[2+u] * MomentV[2+v] + MomentU[2+u] * MomentV[0+v] * MomentXi[2] + MomentU[0+u] * MomentV[2+v] * MomentXi[2] ) ) ); // ======================================================================== // ================================================================================================================================================ // ================================================================================================================================================ // ================================================================================================================================================ // ======================================================================== for ( int i = 0; i < 4; i++ ) { this->timeIntegratedFlux[i] = ( timeCoefficients[0] * Flux_1[i] + timeCoefficients[1] * Flux_2[i] + timeCoefficients[2] * Flux_3[i] ) * dy * prim[0]; // The Flux density in the Flux per unit area of the interface at one instant in time this->FluxDensity[i] = ( Flux_1[i] - tau*( Flux_2[i] + Flux_3[i] ) ) * prim[0]; } // ======================================================================== int i = 1; } void CompressibleInterface::computeMicroSlope(double * prim, double * macroSlope, double * microSlope) { // this method computes the micro slopes from the slopes of the conservative variables // the resulting microslopes contain the density, since they are computed from the slopes // of the conservative variables, which are rho, rhoU, rhoV and rhoE double A, B, C, E; // ======================================================================== // this is 2 times the total energy density 2 E = 2 rhoE / rho E = prim[1] * prim[1] + prim[2] * prim[2] + ( this->fluidParam.K + 2.0 ) / ( 2.0*prim[3] ); // ======================================================================== // ======================================================================== // the product rule of derivations is used here! A = 2.0*macroSlope[3] - E * macroSlope[0]; // = 2 rho dE/dx B = macroSlope[1] - prim[1] * macroSlope[0]; // = rho dU/dx C = macroSlope[2] - prim[2] * macroSlope[0]; // = rho dV/dx // ======================================================================== // compute micro slopes of primitive variables from macro slopes of conservatice variables microSlope[3] = ( 4.0 * prim[3] * prim[3] ) / ( this->fluidParam.K + 2.0 ) * ( A - 2.0*prim[1] * B - 2.0*prim[2] * C ); microSlope[2] = 2.0 * prim[3] * C - prim[2] * microSlope[3]; microSlope[1] = 2.0 * prim[3] * B - prim[1] * microSlope[3]; microSlope[0] = macroSlope[0] - prim[1] * microSlope[1] - prim[2] * microSlope[2] - 0.5 * E* microSlope[3]; }
62.094801
195
0.353854
StephanLenz
b3b7aaa2b00acae002d611fa18456c61092e7c1e
7,472
cpp
C++
lib/d6502/SimpleAsm.cpp
tmikov/apple2tc
2a0f203d74d4be1677e109dfa841f143aa582657
[ "Zlib", "MIT" ]
6
2021-12-13T21:16:47.000Z
2022-03-20T14:53:16.000Z
lib/d6502/SimpleAsm.cpp
tmikov/apple2c
2a0f203d74d4be1677e109dfa841f143aa582657
[ "Zlib", "MIT" ]
2
2022-01-27T01:38:51.000Z
2022-01-31T03:52:54.000Z
lib/d6502/SimpleAsm.cpp
tmikov/apple2c
2a0f203d74d4be1677e109dfa841f143aa582657
[ "Zlib", "MIT" ]
1
2022-03-20T14:53:17.000Z
2022-03-20T14:53:17.000Z
/* * Copyright (c) Tzvetan Mikov. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "apple2tc/SimpleAsm.h" #include "apple2tc/d6502.h" #include "apple2tc/support.h" #include <cstdarg> #include <functional> #include <optional> #include <string_view> static const char *skip(const char *s) { while (isspace(*s)) ++s; return s; } void SimpleAsm::error(const char *where, const char *msg, ...) { va_list ap; va_start(ap, msg); errorCB_(where, vformat(msg, ap).c_str()); va_end(ap); } /// Parse a number or label. /// \param emit: if true, labels must be defined. const char *SimpleAsm::parseExpr2(ExprResult *res, const char *s, bool emit) { s = skip(s); if (*s == '%') { // Binary. ++s; res->value = 0; const char *start = s; for (; *s == '0' || *s == '1'; ++s) { if (s - start == 16) error(s, "binary number overflow"); else if (s - start < 16) res->value = (res->value << 1) + (*s - '0'); } if (s == start) error(s, "invalid binary number"); res->width = res->value > 255; } else if (*s == '$') { // Hex. ++s; res->value = 0; const char *start = s; for (; isxdigit(*s); ++s) { if (s - start == 4) error(s, "binary number overflow"); else if (s - start < 4) res->value = (res->value << 4) + parseXDigit(*s); } if (s == start) error(s, "invalid hex number"); res->width = res->value > 255 ? 2 : 1; } else if (isdigit(*s)) { res->value = 0; const char *start = s; bool ovf = false; for (; isdigit(*s); ++s) { if (ovf) continue; uint32_t tmp = (uint32_t)res->value * 10 + *s - '0'; if (tmp > 0xFFFF) { ovf = true; error(s, "decimal number overflow"); } else { res->value = (uint16_t)tmp; } } res->width = res->value > 255 ? 2 : 1; } else if (*s == '\'') { ++s; res->width = 1; res->value = (uint8_t)*s; if (!*s || s[1] != '\'') { error(s, "unterminated character"); } else { s += 2; } } else { // By default we assume labels are 16-bit. res->value = 0; res->width = 2; const char *start = s; for (; *s && (isalnum(*s) || strchr(LABEL_CHARS, *s)); ++s) ; if (s == start) { error(s, "missing label"); } else { auto label = std::string_view(start, s - start); if (auto labValue = resolveSymbol_(label)) { *res = *labValue; } else if (emit) { error(start, "undefined label '%s'", std::string(label).c_str()); } } } return s; } /// Parse additions. const char *SimpleAsm::parseExpr1(ExprResult *res, const char *s, bool emit) { s = skip(parseExpr2(res, s, emit)); while (*s == '+' || *s == '-' || *s == '|') { char op = *s; ExprResult tmp; s = skip(parseExpr2(&tmp, s + 1, emit)); switch (op) { case '+': res->value += tmp.value; break; case '-': res->value -= tmp.value; break; case '|': res->value |= tmp.value; break; } res->width = std::max(res->width, tmp.width); } return s; } // < low byte // > high byte // #X+1 const char *SimpleAsm::parseExpr(ExprResult *res, const char *s, bool emit) { s = skip(s); if (*s == '<') { s = parseExpr1(res, s + 1, emit); res->width = 1; res->value &= 0xFF; } else if (*s == '>') { s = parseExpr1(res, s + 1, emit); res->width = 1; res->value >>= 8; } else { s = parseExpr1(res, s, emit); } return skip(s); } std::optional<CPUAddrMode> SimpleAsm::parseInstOperand(ExprResult *res, const char *s, bool emit) { const char *start = s; if (*s == 0) return CPUAddrMode::Implied; if (eqci(s, "A")) return CPUAddrMode::A; if (*s == '#') { s = skip(parseExpr(res, s + 1, emit)); if (*s) { error(s, "invalid expression"); return std::nullopt; } if (res->width == 2) { error(start, "16-bit immediate value"); return std::nullopt; } return CPUAddrMode::Imm; } if (*s == '(') { s = skip(parseExpr(res, s + 1, emit)); if (*s == ',') { s = skip(s + 1); if (!eqci(s, "X)")) { error(s, "X) expected"); return std::nullopt; } return CPUAddrMode::X_Ind; } if (*s != ')') { error(s, ") expected"); return std::nullopt; } s = skip(s + 1); if (*s == 0) return CPUAddrMode::Ind; if (*s != ',') { error(s, ", expected"); return std::nullopt; } s = skip(s + 1); if (!eqci(s, "Y")) { error(s, "Y expected"); return std::nullopt; } return CPUAddrMode::Ind_Y; } s = skip(parseExpr(res, s, emit)); if (*s == ',') { s = skip(s + 1); if (eqci(s, "X")) { return res->width == 2 ? CPUAddrMode::Abs_X : CPUAddrMode::Zpg_X; } else if (eqci(s, "Y")) { return res->width == 2 ? CPUAddrMode::Abs_Y : CPUAddrMode::Zpg_Y; } else { error(s, "X or Y expected"); return std::nullopt; } } if (*s) { error(s, "invalid expression"); return std::nullopt; } return res->width == 2 ? CPUAddrMode::Abs : CPUAddrMode::Zpg; } std::optional<uint8_t> SimpleAsm::assemble( ThreeBytes *bytes, uint16_t pc, const char *middle, const char *right, bool emit) { auto optKind = findInstKind(middle); if (!optKind) { error(middle, "Unknown instruction '%s'", middle); return std::nullopt; } ExprResult res; std::optional<uint8_t> encoding; auto optAm = parseInstOperand(&res, right, emit); if (!optAm) return std::nullopt; CPUAddrMode am = *optAm; encoding = encodeInst(CPUOpcode{.kind = *optKind, .addrMode = am}); if (!encoding) { bool tryIt = true; switch (am) { case CPUAddrMode::Zpg: am = CPUAddrMode::Abs; break; case CPUAddrMode::Zpg_X: am = CPUAddrMode::Abs_X; break; case CPUAddrMode::Zpg_Y: am = CPUAddrMode::Abs_Y; break; default: tryIt = false; break; } if (tryIt) encoding = encodeInst(CPUOpcode{.kind = *optKind, .addrMode = am}); } if (!encoding && am == CPUAddrMode::Abs) { am = CPUAddrMode::Rel; encoding = encodeInst(CPUOpcode{.kind = *optKind, .addrMode = am}); } if (!encoding && *optKind == CPUInstKind::BRK && am == CPUAddrMode::Implied) { // BRK is also recognized as a 1-byte instruction. encoding = 0; } if (!encoding) { error(*right ? right : middle, "unsupported address mode for '%s'", middle); return std::nullopt; } if (emit) { bytes->d[0] = encoding.value(); switch (am) { default: case CPUAddrMode::A: case CPUAddrMode::Implied: break; case CPUAddrMode::Abs: case CPUAddrMode::Ind: case CPUAddrMode::Abs_X: case CPUAddrMode::Abs_Y: bytes->d[1] = res.value; bytes->d[2] = res.value >> 8; break; case CPUAddrMode::Rel: { int32_t d = (int32_t)res.value - pc - 2; if (d < INT8_MIN || d > INT8_MAX) error(right, "relative branch out of range"); bytes->d[1] = d; break; } case CPUAddrMode::Imm: case CPUAddrMode::X_Ind: case CPUAddrMode::Ind_Y: case CPUAddrMode::Zpg: case CPUAddrMode::Zpg_X: case CPUAddrMode::Zpg_Y: bytes->d[1] = res.value; break; } } return cpuInstSize(am); }
23.948718
99
0.536001
tmikov
b3b97a30803d2bc621aef28a121d57acba5b28f9
45,560
cpp
C++
musicplayer_player_decoding.cpp
albertz/music-player-core
83dd7ae3a291ae932452f9c60f919187ac370418
[ "BSD-2-Clause" ]
56
2015-04-21T05:35:38.000Z
2021-02-16T13:42:45.000Z
musicplayer_player_decoding.cpp
albertz/music-player-core
83dd7ae3a291ae932452f9c60f919187ac370418
[ "BSD-2-Clause" ]
13
2015-05-09T17:36:27.000Z
2020-02-13T17:44:59.000Z
musicplayer_player_decoding.cpp
albertz/music-player-core
83dd7ae3a291ae932452f9c60f919187ac370418
[ "BSD-2-Clause" ]
27
2015-06-15T14:54:58.000Z
2021-07-22T09:59:40.000Z
// ffmpeg player decoding // part of MusicPlayer, https://github.com/albertz/music-player // Copyright (c) 2012, Albert Zeyer, www.az2000.de // All rights reserved. // This code is under the 2-clause BSD license, see License.txt in the root directory of this project. // INT64_MIN and co #define __STDC_LIMIT_MACROS #include <stdint.h> #include "musicplayer.h" #include "PyUtils.h" #include "Log.hpp" #include "PythonHelpers.h" #include "Py3Compat.h" extern "C" { #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswresample/swresample.h> } #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1) #define av_frame_alloc avcodec_alloc_frame #define av_frame_unref avcodec_get_frame_defaults #endif #include <math.h> #include <unistd.h> #include <dlfcn.h> #include <vector> #include <set> #define PROCESS_SIZE (BUFFER_CHUNK_SIZE * 10) // how much data to proceed in processInStream() #define BUFFER_FILL_SECS 10 #define BUFFER_FILL_SIZE (48000 * 2 * OUTSAMPLEBYTELEN * BUFFER_FILL_SECS) // 10 secs for 48kHz,stereo - around 2MB #define PEEKSTREAM_NUM 3 Log workerLog("Worker"); Log mainLog("Main"); static int ffmpeg_lockmgr(void **mtx, enum AVLockOp op) { switch(op) { case AV_LOCK_CREATE: *mtx = new PyMutex; if(!*mtx) return 1; return 0; case AV_LOCK_OBTAIN: static_cast<PyMutex*>(*mtx)->lock(); return 0; case AV_LOCK_RELEASE: static_cast<PyMutex*>(*mtx)->unlock(); return 0; case AV_LOCK_DESTROY: delete static_cast<PyMutex*>(*mtx); return 0; } return 1; } int initPlayerDecoder() { av_log_set_level(0); av_lockmgr_register(ffmpeg_lockmgr); avcodec_register_all(); av_register_all(); return 0; } void SmoothClipCalc::setX(float x1, float x2) { SmoothClipCalc* s = this; if(x1 < 0) x1 = 0; if(x1 > 1) x1 = 1; if(x2 < x1) x2 = x1; s->x1 = x1; s->x2 = x2; if(x1 == x2) { s->a = 0; s->b = 0; s->c = 1; s->d = 0; return; } s->a = ((x1 + x2 - 2.) / pow(x2 - x1, 3.)); s->b = ((- (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((7. * pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - 1.) / (4. * x2 - 4.)); s->c = (1. / 2.) * ((((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) + ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - ((4. * (- (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((7. * pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - 1.)) / (4. * x2 - 4.)) + 1.); s->d = (1. / 4.) * ((((x1 + x2 - 2.) * pow(x1, 3.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((pow(x2, 2.) * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((2. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + x1 - ((pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((4. * (- (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((7. * pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - 1.)) / (4. * x2 - 4.)) + 1.); } static int player_read_packet(PlayerInStream* is, uint8_t* buf, int buf_size) { // We assume that we don't have the PlayerObject lock at this point and not the Python GIL. //printf("player_read_packet %i\n", buf_size); if(is->player == NULL) return -1; PyObject* song = NULL; bool skipPyExceptions = false;; { PyScopedLock lock(is->player->lock); PyScopedGIL gstate; song = is->song; if(song == NULL) return -1; Py_INCREF(song); skipPyExceptions = is->player->skipPyExceptions; } PyScopedGIL gstate; Py_ssize_t ret = -1; PyObject *readPacketFunc = NULL, *args = NULL, *retObj = NULL; readPacketFunc = PyObject_GetAttrString(song, "readPacket"); if(readPacketFunc == NULL) goto final; args = PyTuple_New(1); PyTuple_SetItem(args, 0, PyLong_FromLong(buf_size)); retObj = PyObject_CallObject(readPacketFunc, args); if(retObj == NULL) goto final; if(!PyBytes_Check(retObj)) { printf("song.readPacket didn't returned a byteobj but a %s\n", retObj->ob_type->tp_name); goto final; } ret = PyBytes_Size(retObj); if(ret > buf_size) { printf("song.readPacket returned more than buf_size\n"); ret = buf_size; } if(ret < 0) { ret = -1; goto final; } memcpy(buf, PyBytes_AsString(retObj), ret); final: Py_XDECREF(retObj); Py_XDECREF(args); Py_XDECREF(readPacketFunc); Py_XDECREF(song); if(skipPyExceptions && PyErr_Occurred()) PyErr_Print(); return (int) ret; } static int64_t player_seek(PlayerInStream* is, int64_t offset, int whence) { // We assume that we don't have the PlayerObject lock at this point and not the Python GIL. //printf("player_seek %lli %i\n", offset, whence); if(is->player == NULL) return -1; PyObject* song = NULL; bool skipPyExceptions = false;; { PyScopedLock lock(is->player->lock); PyScopedGIL gstate; song = is->song; if(song == NULL) return -1; Py_INCREF(song); skipPyExceptions = is->player->skipPyExceptions; } PyScopedGIL gstate; int64_t ret = -1; PyObject *seekRawFunc = NULL, *args = NULL, *retObj = NULL; if(whence == AVSEEK_SIZE) goto final; // Ignore and return -1. This is supported by FFmpeg. if(whence & AVSEEK_FORCE) whence &= ~AVSEEK_FORCE; // Can be ignored. if(whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) { printf("player_seek: invalid whence in params offset:%lli whence:%i\n", offset, whence); goto final; } if(whence == SEEK_SET && offset < 0) { // This is a bug in FFmpeg: https://trac.ffmpeg.org/ticket/4038 goto final; } seekRawFunc = PyObject_GetAttrString(song, "seekRaw"); if(seekRawFunc == NULL) goto final; args = PyTuple_New(2); if(args == NULL) goto final; PyTuple_SetItem(args, 0, PyLong_FromLongLong(offset)); PyTuple_SetItem(args, 1, PyLong_FromLong(whence)); retObj = PyObject_CallObject(seekRawFunc, args); if(retObj == NULL) goto final; // pass through any Python exception // NOTE: I don't really know what would be the best strategy in case of overflow... if(PyInt_Check(retObj)) ret = (int) PyInt_AsLong(retObj); else if(PyLong_Check(retObj)) ret = (int) PyLong_AsLong(retObj); else { printf("song.seekRaw didn't returned an int but a %s\n", retObj->ob_type->tp_name); goto final; } final: Py_XDECREF(retObj); Py_XDECREF(args); Py_XDECREF(seekRawFunc); Py_XDECREF(song); if(skipPyExceptions && PyErr_Occurred()) PyErr_Print(); return ret; } static int _player_av_read_packet(void *opaque, uint8_t *buf, int buf_size) { return player_read_packet((PlayerInStream*)opaque, buf, buf_size); } static int64_t _player_av_seek(void *opaque, int64_t offset, int whence) { return player_seek((PlayerInStream*)opaque, offset, whence); } static AVIOContext* initIoCtx(PlayerInStream* is) { int buffer_size = 1024 * 4; unsigned char* buffer = (unsigned char*)av_malloc(buffer_size); AVIOContext* io = avio_alloc_context( buffer, buffer_size, 0, // writeflag is, // opaque _player_av_read_packet, NULL, // write_packet _player_av_seek ); return io; } static AVFormatContext* initFormatCtx(PlayerInStream* is) { AVFormatContext* fmt = avformat_alloc_context(); if(!fmt) return NULL; fmt->pb = initIoCtx(is); if(!fmt->pb) { printf("initIoCtx failed\n"); } fmt->flags |= AVFMT_FLAG_CUSTOM_IO; return fmt; } static void player_resetStreamPackets(PlayerInStream* player) { av_free_packet(&player->audio_pkt); memset(&player->audio_pkt, 0, sizeof(player->audio_pkt)); memset(&player->audio_pkt_temp, 0, sizeof(player->audio_pkt_temp)); } void PlayerInStream::resetBuffers() { this->do_flush = true; this->readerHitEnd = false; this->outBuffer.clear(); player_resetStreamPackets(this); } void PlayerInStream::seekAbs(double pos) { // We expect to have the stream lock and not the PyGIL. if(pos < 0) pos = 0; // No clever logic when we can omit this seek. // We might also call it just to force a buffer reset. resetBuffers(); playerStartedPlaying = false; double incr = playerTimePos - pos; playerTimePos = readerTimePos = pos; int64_t seek_target = int64_t(pos * AV_TIME_BASE); int64_t seek_min = (incr > 0) ? (seek_target - int64_t(incr * AV_TIME_BASE) + 2) : 0; int64_t seek_max = (incr < 0) ? (seek_target - int64_t(incr * AV_TIME_BASE) - 2) : INT64_MAX; if(seek_target < 0) seek_target = INT64_MAX; if(seek_min < 0) seek_min = 0; if(seek_max < 0) seek_max = INT64_MAX; int ret = avformat_seek_file( ctx, -1, // stream seek_min, seek_target, seek_max, 0 //flags ); if(ret < 0) printf("(%s) seekAbs(%f): seek failed\n", debugName.c_str(), pos); } void PlayerObject::resetBuffers() { PyScopedUnlock unlock(this->lock); for(PlayerInStream& is : inStreams) { PyScopedLock lock(is.lock); is.seekAbs(is.playerTimePos); // simple way to reset } } void PlayerObject::seekSong(double pos, bool relativePos) { outOfSync = true; PlayerObject* pl = this; InStreams::ItemPtr isptr = pl->getInStream(); if(!isptr.get()) return; PlayerInStream* is = &isptr->value; PyScopedUnlock unlock(pl->lock); { PyScopedLock lock(is->lock); if(relativePos) pos += is->playerTimePos; if(is->playerStartedPlaying && pl->fader.sampleFactor() != 0) { // Let it fade out. pl->fader.change(-1, pl->outSamplerate, false); // Delay seek. The worker-proc will handle it. // This will also fade it in again. is->seekPos = std::max(pos, 0.0); } // No fading. else is->seekAbs(pos); } isptr.reset(); // must be reset in unlocked scope } PyObject* PlayerObject::curSongMetadata() const { InStreams::ItemPtr is = getInStream(); if(is.get()) return is->value.metadata; return NULL; } double PlayerObject::curSongPos() const { InStreams::ItemPtr is = getInStream(); if(is.get()) return is->value.playerTimePos; return 0; } double PlayerObject::curSongLen() const { InStreams::ItemPtr is = getInStream(); if(is.get()) return is->value.timeLen; return -1; } float PlayerObject::curSongGainFactor() const { InStreams::ItemPtr is = getInStream(); if(is.get()) return is->value.gainFactor; return 1; } /* open a given stream. Return 0 if OK */ // called by player_openInputStream() static int stream_component_open(PlayerInStream *is, AVFormatContext* ic, int stream_index) { AVCodecContext *avctx; AVCodec *codec; // AVDictionaryEntry *t = NULL; if(stream_index < 0 || stream_index >= ic->nb_streams) return -1; avctx = ic->streams[stream_index]->codec; codec = avcodec_find_decoder(avctx->codec_id); if(!codec) { printf("(%s) avcodec_find_decoder failed (%s)\n", is->debugName.c_str(), ic->iformat->name); return -1; } //avctx->workaround_bugs = workaround_bugs; //avctx->lowres = lowres; if(avctx->lowres > codec->max_lowres) { av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n", codec->max_lowres); avctx->lowres= codec->max_lowres; } //avctx->idct_algo = idct; //avctx->skip_frame = skip_frame; //avctx->skip_idct = skip_idct; //avctx->skip_loop_filter = skip_loop_filter; //avctx->error_concealment = error_concealment; //if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE; // CODEC_FLAG_EMU_EDGE is deprecated //if (fast) avctx->flags2 |= AV_CODEC_FLAG2_FAST; //if(codec->capabilities & AV_CODEC_CAP_DR1) avctx->flags |= CODEC_FLAG_EMU_EDGE; // CODEC_FLAG_EMU_EDGE is deprecated if (avcodec_open2(avctx, codec, NULL /*opts*/) < 0) { printf("(%s) avcodec_open2 failed (%s) (%s)\n", is->debugName.c_str(), ic->iformat->name, codec->name); return -1; } /* prepare audio output */ //if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) { // is->audio_tgt = is->audio_src; //} ic->streams[stream_index]->discard = AVDISCARD_DEFAULT; switch (avctx->codec_type) { case AVMEDIA_TYPE_AUDIO: is->audio_stream = stream_index; is->audio_st = ic->streams[stream_index]; /* init averaging filter */ //is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB); //is->audio_diff_avg_count = 0; /* since we do not have a precise anough audio fifo fullness, we correct audio sync only if larger than this threshold */ //is->audio_diff_threshold = 2.0 * is->audio_hw_buf_size / av_samples_get_buffer_size(NULL, is->audio_tgt.channels, is->audio_tgt.freq, is->audio_tgt.fmt, 1); player_resetStreamPackets(is); //packet_queue_start(&is->audioq); //SDL_PauseAudio(0); break; default: printf("(%s) stream_component_open: not an audio stream\n", is->debugName.c_str()); return -1; } return 0; } static void player_setSongMetadata(PlayerInStream* player) { Py_XDECREF(player->metadata); player->metadata = NULL; if(!player->ctx) return; if(!player->ctx->metadata) return; AVDictionary* m = player->ctx->metadata; player->metadata = PyDict_New(); assert(player->metadata); AVDictionaryEntry* tag = NULL; while((tag = av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) { if(strcmp("language", tag->key) == 0) continue; PyDict_SetItemString_retain(player->metadata, tag->key, PyString_FromString(tag->value)); } if(player->timeLen > 0) { PyDict_SetItemString_retain(player->metadata, "duration", PyFloat_FromDouble(player->timeLen)); } else if(PyDict_GetItemString(player->metadata, "duration")) { // we have an earlier duration metadata which is a string now. // convert it to float. PyObject* floatObj = PyFloat_FromString(PyDict_GetItemString(player->metadata, "duration")); if(!floatObj) { PyErr_Clear(); PyDict_DelItemString(player->metadata, "duration"); } else { PyDict_SetItemString_retain(player->metadata, "duration", floatObj); } } } static void closeInputStream(AVFormatContext* formatCtx) { if(formatCtx->pb) { if(formatCtx->pb->buffer) { av_free(formatCtx->pb->buffer); formatCtx->pb->buffer = NULL; } // avformat_close_input freeing this indirectly? I got a crash here in avio_close //av_free(formatCtx->pb); //formatCtx->pb = NULL; } for(int i = 0; i < formatCtx->nb_streams; ++i) { avcodec_close(formatCtx->streams[i]->codec); } avformat_close_input(&formatCtx); } PlayerInStream::~PlayerInStream() { PlayerInStream* is = this; player_resetStreamPackets(is); if(is->ctx) { closeInputStream(is->ctx); is->ctx = NULL; } if(is->frame) { av_free(is->frame); is->frame = NULL; } if(is->swr_ctx) { swr_free(&is->swr_ctx); is->swr_ctx = NULL; } { PyScopedGIL gstate; Py_XDECREF(song); song = NULL; Py_XDECREF(metadata); metadata = NULL; } } bool PlayerInStream::open(PlayerObject* pl, PyObject* song) { // We assume to not have the PlayerObject lock and neither the GIL. assert(song != NULL); if(this->player == NULL) this->player = pl; else { assert(this->player == pl); } { PyScopedLock lock(pl->lock); while(pl->openStreamLock) { PyScopedUnlock(pl->lock); usleep(100); } pl->openStreamLock = true; } { PyScopedGIL glock; Py_XDECREF(this->song); // if there is any old song Py_INCREF(song); } this->song = song; PlayerInStream* player = this; int ret = 0; AVFormatContext* formatCtx = NULL; debugName = objAttrStr(song, "url"); // the url is just for debugging, the song object provides its own IO { size_t f = debugName.rfind('/'); if(f != std::string::npos) debugName = debugName.substr(f + 1); } const char* fileExt = NULL; { size_t f = debugName.rfind('.'); if(f != std::string::npos) fileExt = &debugName[f+1]; } AVInputFormat* fmts[] = { fileExt ? av_find_input_format(fileExt) : NULL, NULL, av_find_input_format("mp3") }; for(size_t i = 0; i < sizeof(fmts)/sizeof(fmts[0]); ++i) { if(i == 1 && fmts[0] == NULL) continue; // we already tried NULL AVInputFormat* fmt = fmts[i]; if(formatCtx) closeInputStream(formatCtx); player_seek(this, 0, SEEK_SET); formatCtx = initFormatCtx(this); if(!formatCtx) { printf("(%s) initFormatCtx failed\n", debugName.c_str()); goto final; } ret = av_probe_input_buffer(formatCtx->pb, &fmt, debugName.c_str(), NULL, 0, formatCtx->probesize); if(ret < 0) { printf("(%s) av_probe_input_buffer failed (%s)\n", debugName.c_str(), fmt ? fmt->name : "<NULL>"); continue; } ret = avformat_open_input(&formatCtx, debugName.c_str(), fmt, NULL); if(ret != 0) { printf("(%s) avformat_open_input (%s) failed\n", debugName.c_str(), fmt->name); continue; } ret = avformat_find_stream_info(formatCtx, NULL); if(ret < 0) { printf("(%s) avformat_find_stream_info (%s) failed\n", debugName.c_str(), fmt->name); continue; } #ifdef DEBUG av_dump_format(formatCtx, 0, debugName.c_str(), 0); #endif if(formatCtx->nb_streams == 0) { printf("(%s) no streams found in song (%s)\n", debugName.c_str(), fmt->name); continue; } ret = av_find_best_stream(formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0); if(ret < 0) { const char* errorMsg = "unkown error"; if(ret == AVERROR_STREAM_NOT_FOUND) errorMsg = "stream not found"; else if(ret == AVERROR_DECODER_NOT_FOUND) errorMsg = "decoder not found"; printf("(%s) no audio stream found in song (%s): %s\n", debugName.c_str(), fmt->name, errorMsg); int oldloglevel = av_log_get_level(); av_log_set_level(AV_LOG_INFO); av_dump_format(formatCtx, 0, debugName.c_str(), 0); av_log_set_level(oldloglevel); continue; } player->audio_stream = ret; ret = stream_component_open(player, formatCtx, player->audio_stream); if(ret < 0) { printf("(%s) cannot open audio stream (%s)\n", debugName.c_str(), fmt->name); continue; } if(i > 0) printf("(%s) fallback open succeeded (%s)\n", debugName.c_str(), fmt->name); goto success; } printf("(%s) opening failed\n", debugName.c_str()); goto final; success: player->ctx = formatCtx; formatCtx = NULL; // Get the song len: There is formatCtx.duration in AV_TIME_BASE // and there is stream.duration in stream time base. assert(player->audio_st); this->timeLen = av_q2d(player->audio_st->time_base) * player->audio_st->duration; //if(player->timeLen < 0) { // happens in some cases, e.g. some flac files // player->timeLen = av_q2d(AV_TIME_BASE_Q) * formatCtx->duration; // doesnt make it better though... //} if(this->timeLen < 0) this->timeLen = -1; { PyScopedGIL glock; player_setSongMetadata(this); this->gainFactor = 1; if(PyObject_HasAttrString(song, "gain")) { PyObject* gainObj = PyObject_GetAttrString(song, "gain"); if(gainObj) { float gain = 0; if(!PyArg_Parse(gainObj, "f", &gain)) printf("(%s) song.gain is not a float\n", debugName.c_str()); else this->gainFactor = pow(10, gain / 20); Py_DECREF(gainObj); } else { // !gainObj // strange. reset any errors... if(PyErr_Occurred()) PyErr_Print(); } } // TODO: maybe alternatively try to read gain from metatags? if(PyObject_HasAttrString(song, "startOffset")) { PyObject* obj = PyObject_GetAttrString(song, "startOffset"); if(obj) { double pos = 0; if(!PyArg_Parse(obj, "d", &pos)) printf("(%s) song.startOffset is not a double\n", debugName.c_str()); else { PyScopedGIUnlock gunlock; seekAbs(pos); } Py_DECREF(obj); } else { // strange. reset any errors... if(PyErr_Occurred()) PyErr_Print(); } } } final: if(formatCtx) closeInputStream(formatCtx); pl->openStreamLock = false; if(this->ctx) return true; return false; } bool PlayerObject::openInStream() { assert(this->curSong != NULL); if(tryOvertakePeekInStream()) return true; outOfSync = true; // new input stream PyScopedGIUnlock gunlock; InStreams::ItemPtr is; { PyScopedUnlock unlock(this->lock); is.reset(new InStreams::Item()); if(!is->value.open(this, this->curSong)) { PyScopedLock lock(this->lock); if(!this->nextSongOnEof) { PyScopedGIL gstate; // This means that the failure of opening is fatal because we wont skip to the next song. // This mode is also only used in the calc* specific functions. if(!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError, "failed to open file"); } return false; } } inStreams.push_front(is); return true; } /* return the wanted number of samples to get better sync if sync_type is video * or external master clock */ static int synchronize_audio(PlayerInStream *is, int nb_samples) { int wanted_nb_samples = nb_samples; return wanted_nb_samples; } bool PlayerObject::volumeAdjustNeeded(PlayerInStream *is) const { if(!volumeAdjustEnabled) return false; if(fader.sampleFactor() != 1) return true; if(this->volume != 1) return true; if(this->volumeSmoothClip.x1 != this->volumeSmoothClip.x2) return true; if(!is && this->curSongGainFactor() != 1) return true; if(is && is->gainFactor != 1) return true; return false; } template<typename T> struct AVOutFormat{}; template<> struct AVOutFormat<int16_t> { static const enum AVSampleFormat format = AV_SAMPLE_FMT_S16; }; template<> struct AVOutFormat<float32_t> { static const enum AVSampleFormat format = AV_SAMPLE_FMT_FLT; }; // called from PlayerObject::workerProc() // decode one audio frame and returns its uncompressed size // return <0 means that we must change some state for this function to work again. e.g. we could have EOF, the song is not correctly opened, the player is in stopped-state or so. an invalid frame will not cause this! // note that even with <0, there might have been some data written to outBuffer. // tries to return at least len bytes. but might return more. if something fails, also less. static long audio_decode_frame(PlayerObject* player, PlayerInStream *is, long len) { // We assume that we don't have the PlayerObject lock at this point and neither the Python GIL. if(is->ctx == NULL) return -1; if(is->audio_st == NULL) return -1; if(is->readerHitEnd) return -1; assert(av_get_bytes_per_sample(AVOutFormat<OUTSAMPLE_t>::format) == OUTSAMPLEBYTELEN); PyScopedGIUnlock gunlock; // be sure that we don't have it. the av-callbacks (read/seek) must not have it. AVPacket *pkt_temp = &is->audio_pkt_temp; AVPacket *pkt = &is->audio_pkt; AVCodecContext *dec = is->audio_st->codec; int len2, data_size, resampled_data_size; int64_t dec_channel_layout; int flush_complete = 0; int wanted_nb_samples; long count = 0; for (;;) { int outSamplerate = 0, outNumChannels = 0; { PyScopedLock lock(player->lock); if(is->do_flush) { avcodec_flush_buffers(dec); flush_complete = 0; is->do_flush = false; count = 0; } outSamplerate = player->outSamplerate; outNumChannels = player->outNumChannels; } /* NOTE: the audio packet can contain several frames */ while (pkt_temp->size > 0) { if (!is->frame) { if (!(is->frame = av_frame_alloc())) return AVERROR(ENOMEM); } else av_frame_unref(is->frame); if (flush_complete) break; int got_frame = 0; int len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp); if (len1 < 0) { pkt_temp->size = 0; // warning only at pos 0. this seems too common and i don't like a spammy log... if(is->readerTimePos == 0) printf("(%s) avcodec_decode_audio4 error at pos 0\n", is->debugName.c_str()); // Earlier, we just breaked. but I encountered some audio files // which only have garbage following and the user should never // listen to that. // Other musicplayers also skip that part. // TODO: what files? examples... // However, there are other files which have a decode error right at the beginning, e.g. ~/rpi-issue-62/sofa.mp3. // see https://github.com/albertz/music-player/issues/32 // That file even has errors after that, so we cannot // break just at readerTimePos>0. //if(is->readerTimePos > 0) { // is->readerHitEnd = true; // return count; //} break; } //printf("avcodec_decode_audio4: %i\n", len1); pkt_temp->data += len1; pkt_temp->size -= len1; if (!got_frame) { /* stop sending empty packets if the decoder is finished */ if (!pkt_temp->data && dec->codec->capabilities & AV_CODEC_CAP_DELAY) flush_complete = 1; continue; } data_size = av_samples_get_buffer_size(NULL, dec->channels, is->frame->nb_samples, dec->sample_fmt, 1); dec_channel_layout = (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ? dec->channel_layout : av_get_default_channel_layout(dec->channels); wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples); if (dec->sample_fmt != is->audio_src.fmt || dec_channel_layout != is->audio_src.channel_layout || dec->sample_rate != is->audio_src.freq || (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx) || is->audio_tgt.freq != outSamplerate || is->audio_tgt.channels != outNumChannels) { swr_free(&is->swr_ctx); is->audio_tgt.fmt = AVOutFormat<OUTSAMPLE_t>::format; is->audio_tgt.freq = outSamplerate; is->audio_tgt.channels = outNumChannels; is->audio_tgt.channel_layout = av_get_default_channel_layout(player->outNumChannels); is->swr_ctx = swr_alloc_set_opts ( NULL, is->audio_tgt.channel_layout, AVOutFormat<OUTSAMPLE_t>::format, outSamplerate, dec_channel_layout, dec->sample_fmt, dec->sample_rate, 0, NULL); if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) { fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n", dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels, outSamplerate, av_get_sample_fmt_name(AVOutFormat<OUTSAMPLE_t>::format), outNumChannels); break; } is->audio_src.channel_layout = dec_channel_layout; is->audio_src.channels = dec->channels; is->audio_src.freq = dec->sample_rate; is->audio_src.fmt = dec->sample_fmt; /*printf("conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n", dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels, is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);*/ } if (is->swr_ctx) { const uint8_t **in = (const uint8_t **)is->frame->extended_data; uint8_t *out[] = {is->audio_buf2}; int out_count = sizeof(is->audio_buf2) / outNumChannels / OUTSAMPLEBYTELEN; if (wanted_nb_samples != is->frame->nb_samples) { if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * outSamplerate / dec->sample_rate, wanted_nb_samples * outSamplerate / dec->sample_rate) < 0) { fprintf(stderr, "swr_set_compensation() failed\n"); break; } } len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples); if (len2 < 0) { fprintf(stderr, "swr_convert() failed\n"); break; } if (len2 == out_count) { fprintf(stderr, "warning: audio buffer is probably too small\n"); swr_init(is->swr_ctx); } is->audio_buf = is->audio_buf2; resampled_data_size = len2 * outNumChannels * OUTSAMPLEBYTELEN; } else { is->audio_buf = is->frame->data[0]; resampled_data_size = data_size; } { PyScopedLock lock(player->lock); is->outBuffer.push(is->audio_buf, resampled_data_size); } /* if no pts, then compute it */ is->readerTimePos += (double)data_size / (dec->channels * dec->sample_rate * av_get_bytes_per_sample(dec->sample_fmt)); /*{ static double last_clock; printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n", is->audio_clock - last_clock, is->audio_clock, pts); last_clock = is->audio_clock; }*/ count += resampled_data_size; if(count >= len) return count; } /* free the current packet */ av_free_packet(pkt); memset(pkt_temp, 0, sizeof(*pkt_temp)); while(1) { int ret = av_read_frame(is->ctx, pkt); if (ret < 0) { if(is->readerTimePos == 0) printf("(%s) av_read_frame error at pos 0\n", is->debugName.c_str()); //if (ic->pb && ic->pb->error) // printf("av_read_frame error\n"); //if (ret == AVERROR_EOF || url_feof(is->ctx->pb)) // no matter what, set hitEnd because we want to proceed with the next song and don't know what to do here otherwise. is->readerHitEnd = true; return count; } if(pkt->stream_index == is->audio_stream) break; av_free_packet(pkt); } *pkt_temp = *pkt; /* if update the audio clock with the pts */ if (pkt->pts != AV_NOPTS_VALUE) { PyScopedLock lock(player->lock); is->readerTimePos = av_q2d(is->audio_st->time_base)*pkt->pts; if(is->outBuffer.empty()) is->playerTimePos = is->readerTimePos; } } } static bool _buffersFullEnough(PlayerInStream* is) { if(is->readerHitEnd) return true; if(is->outBuffer.size() >= BUFFER_FILL_SIZE) return true; return false; } static bool _processInStream(PlayerObject* player, PlayerInStream* is) { is->outBuffer.cleanup(); return audio_decode_frame(player, is, PROCESS_SIZE) >= 0; } bool PlayerObject::processInStream() { InStreams::ItemPtr is = getInStream(); if(!is.get()) return false; PyScopedUnlock unlock(this->lock); PyScopedLock lock(is->value.lock); return _processInStream(this, &is->value); } bool PlayerObject::isInStreamOpened() const { InStreams::ItemPtr is = getInStream(); if(is.get() == NULL) return false; if(!is->value.isOpened()) return false; return true; } Buffer* PlayerObject::inStreamBuffer() { InStreams::ItemPtr is = getInStream(); if(is.get()) return &is->value.outBuffer; return NULL; } PlayerObject::InStreams::ItemPtr PlayerObject::getInStream() const { return inStreams.front(); } static bool pushPeekInStream(PlayerObject::InStreams::ItemPtr& startAfter, PyObject* song, bool& found) { found = false; PlayerObject::InStreams::ItemPtr foundIs = NULL; { PlayerObject::InStreams::Iterator it(startAfter->next); for(; !it.isEnd(); ++it) { PlayerObject::InStreams::ItemPtr is = it.ptr; assert(is); assert(is->value.song != NULL); { PyScopedGIL gstate; if(PyObject_RichCompareBool(song, is->value.song, Py_EQ) == 1) { foundIs = is; found = true; } // pass through any Python errors if(PyErr_Occurred()) PyErr_Print(); if(found) break; } } } if(!found) return false; std::vector<PlayerObject::InStreams::ItemPtr> popped; { found = false; PlayerObject::InStreams::Iterator it(startAfter->next); for(; !it.isEnd(); ++it) { PlayerObject::InStreams::ItemPtr is = it.ptr; assert(is); assert(is->value.song != NULL); if(is == foundIs) { startAfter = is; found = true; break; } is->popOut(); popped.push_back(is); } assert(found); } { PlayerObject::InStreams::ItemPtr insertAfterMe = startAfter; for(PlayerObject::InStreams::ItemPtr& isp : popped) { bool res = insertAfterMe->insertAfter(isp); assert(res); insertAfterMe = isp; } } return !popped.empty(); } struct PeekItem { PyObject* song; bool valid; PeekItem(PyObject* _song = NULL) : song(_song), valid(true) {} }; static std::vector<PeekItem> queryPeekItems(PlayerObject* player) { std::vector<PeekItem> peekItems; PyScopedGIL gstate; PyObject* args = NULL; PyObject* peekList = NULL; PyObject* peekListIter = NULL; PyObject* song = NULL; args = PyTuple_New(1); if(!args) goto final; PyTuple_SetItem(args, 0, PyLong_FromLong(PEEKSTREAM_NUM)); { PyObject* peekQueue = player->peekQueue; Py_INCREF(peekQueue); PyScopedGIUnlock gunlock; PyScopedUnlock unlock(player->lock); PyScopedGIL glock; peekList = PyObject_CallObject(peekQueue, args); Py_DECREF(peekQueue); } if(!peekList) goto final; peekListIter = PyObject_GetIter(peekList); if(!peekListIter) goto final; { PyScopedGIUnlock gunlock; // let others use Python peekItems.reserve(PEEKSTREAM_NUM); } while((song = PyIter_Next(peekListIter)) != NULL) { PeekItem item; item.song = song; peekItems.push_back(item); } final: // pass through any Python errors if(PyErr_Occurred()) PyErr_Print(); Py_XDECREF(song); Py_XDECREF(peekListIter); Py_XDECREF(peekList); Py_XDECREF(args); return peekItems; } void PlayerObject::openPeekInStreams() { PlayerObject* player = this; if(player->peekQueue == NULL) return; while(pyQueueLock || openStreamLock) { PyScopedUnlock unlock(this->lock); usleep(100); } pyQueueLock = true; std::vector<PeekItem> peekItems = queryPeekItems(player); struct CleanupPeekItems { std::vector<PeekItem>& peekItems; CleanupPeekItems(std::vector<PeekItem>& v) : peekItems(v) {} ~CleanupPeekItems() { PyScopedGIL gstate; for(PeekItem& it : peekItems) { Py_XDECREF(it.song); } // pass through any Python errors if(PyErr_Occurred()) PyErr_Print(); } } cleanupPeekItems(peekItems); // Start after the first item. The first item is the currently played song. PlayerObject::InStreams::ItemPtr startAfter = player->inStreams.mainLink()->next; if(!startAfter->isData(true) // it means there is no stream at all yet || player->curSong == NULL // playing hasn't been started yet || player->curSong != startAfter->value.song ) { // TODO: not exactly sure what to do... pyQueueLock = false; return; } for(PeekItem& it : peekItems) { if(it.song == player->curSong) { printf("Warning: peek queue contained current song (%s)\n", objStr(player->curSong).c_str()); it.valid = false; } } { std::set<PyObject*> songs; for(PeekItem& it : peekItems) { if(!it.valid) continue; if(songs.find(it.song) == songs.end()) songs.insert(it.song); else { printf("Warning: peek queue contains same song twice (%s)\n", objStr(it.song).c_str()); it.valid = false; } } } bool modi = false; for(PeekItem& it : peekItems) { if(!it.valid) continue; bool found; modi |= pushPeekInStream(startAfter, it.song, found); if(!found) { PlayerObject::InStreams::ItemPtr s; { PyScopedUnlock unlock(player->lock); s = new PlayerObject::InStreams::Item(); if(!s->value.open(player, it.song)) s = NULL; } if(s) { startAfter->insertAfter(s); startAfter = s; modi = true; } } } // If there is a modified peek queue, old entries might still be in there. // Remove them now. while(inStreams.size() > PEEKSTREAM_NUM + 1) { if(!inStreams.pop_back()) assert(false); } if(mainLog.enabled && modi) { mainLog << "new peek streams:"; int c = 1; for(PlayerInStream& is : inStreams) { mainLog << "\n " << c << ": " << objStr(is.song); if(c > PEEKSTREAM_NUM + 10) { mainLog << "\n too many!"; break; } ++c; } if(c == 0) mainLog << " none"; mainLog << endl; } pyQueueLock = false; } bool PlayerObject::tryOvertakePeekInStream() { assert(curSong != NULL); PlayerObject::InStreams::ItemPtr startAfter = inStreams.mainLink(); bool found; pushPeekInStream(startAfter, curSong, found); if(found) { mainLog << "tryOvertakePeekInStream: overtake" << endl; // take the new Song object. it might be a different one. PyScopedGIL gstate; Py_XDECREF(curSong); curSong = startAfter->value.song; Py_INCREF(curSong); return true; } return false; } // returns wether there we did something static bool loopFrame(PlayerObject* player) { // We must not hold the PyGIL here! bool didSomething = false; auto popFront = [&](PlayerObject::InStreams::ItemPtr& is) { PlayerObject::InStreams::ItemPtr frontPtr = player->inStreams.pop_front(); assert(frontPtr == is); // InStream reset must always be in unlocked scope PyScopedUnlock unlock(player->lock); is.reset(); frontPtr.reset(); }; auto switchNextSong = [&](bool skipped = false) { if(!player->getNextSong(skipped, false)) { fprintf(stderr, "cannot get next song\n"); PyScopedGIL gstate; if(PyErr_Occurred()) PyErr_Print(); } didSomething = true; }; auto pushPyEv_onSongFinished = [&](PlayerInStream* inStream) { if(player->dict) { PyScopedGIL gstate; Py_INCREF(player->dict); PyObject* onSongFinished = PyDict_GetItemString(player->dict, "onSongFinished"); if(onSongFinished && onSongFinished != Py_None) { Py_INCREF(onSongFinished); PyObject* kwargs = PyDict_New(); assert(kwargs); if(inStream->song) PyDict_SetItemString(kwargs, "song", inStream->song); PyDict_SetItemString_retain(kwargs, "finalTimePos", PyFloat_FromDouble(inStream->playerTimePos)); PyObject* retObj = PyEval_CallObjectWithKeywords(onSongFinished, NULL, kwargs); Py_XDECREF(retObj); // errors are not fatal from the callback, so handle it now and go on if(PyErr_Occurred()) PyErr_Print(); Py_DECREF(kwargs); Py_DECREF(onSongFinished); } Py_DECREF(player->dict); } }; { PyScopedLock lock(player->lock); if(!player->curSong) { workerLog << "open first song" << endl; switchNextSong(); } if(!player->curSong) return true; } { PyScopedLock lock(player->lock); PlayerObject::InStreams::ItemPtr inStreamPtr = player->inStreams.front(); PlayerInStream* inStream = inStreamPtr ? &inStreamPtr->value : NULL; if(inStream && player->curSong != inStream->song) { workerLog << "current " << objStr(player->curSong) << " is not the same as the first stream " << objStr(inStream->song) << endl; bool ret = player->openInStream(); if(ret && player->nextSongOnEof) player->openPeekInStreams(); } else if(inStream && inStream->playerHitEnd) { workerLog << "song finished" << endl; pushPyEv_onSongFinished(inStream); popFront(inStreamPtr); inStream = NULL; } else if(inStream && !inStream->isOpened()) { workerLog << "pop front stream" << endl; popFront(inStreamPtr); inStream = NULL; } if(inStream && player->fader.sampleFactor() == 0) { // It means we are ready to proceed any action in faded-out state. // Currently, that's only seeking. if(inStream->seekPos >= 0) { workerLog << "faded-out: seek stream to " << inStream->seekPos << endl; PyScopedUnlock unlock(player->lock); PyScopedLock lock(inStream->lock); inStream->seekAbs(inStream->seekPos); inStream->seekPos = -1; } if(inStream->skipMe) { workerLog << "faded-out: skip song" << endl; switchNextSong(true); } // Note that we are not necessarily in playing state. if(player->playing) // Whatever we did, if we are in playing state, fade-in. player->fader.change(1, player->outSamplerate, false); } else if(!inStream && player->nextSongOnEof) { workerLog << "switch song" << endl; switchNextSong(); } } for(PlayerInStream& is : player->inStreams) { PyScopedLock lock(is.lock); if(!_buffersFullEnough(&is)) { _processInStream(player, &is); didSomething = true; } } { PyScopedLock lock(player->lock); if(player->isOutStreamOpen() && !player->playing && player->fader.finished()) { workerLog << "close output stream" << endl; player->closeOutStream(true); } } return didSomething; } // The following three functions are at the moment defined in the main application. // If we don't find them, don't care and just ignore. static void ThreadHangDetector_registerCurThread(const char* threadName, float timeoutSecs) { typedef void Handler(const char*, float); static Handler* handler = (Handler*) dlsym(RTLD_DEFAULT, "ThreadHangDetector_registerCurThread"); if(!handler) return; handler(threadName, timeoutSecs); } static void ThreadHangDetector_lifeSignalCurThread() { typedef void Handler(); static Handler* handler = (Handler*) dlsym(RTLD_DEFAULT, "ThreadHangDetector_lifeSignalCurThread"); if(!handler) return; handler(); } static void ThreadHangDetector_unregisterCurThread() { typedef void Handler(); static Handler* handler = (Handler*) dlsym(RTLD_DEFAULT, "ThreadHangDetector_unregisterCurThread"); if(!handler) return; handler(); } void PlayerObject::workerProc(std::atomic<bool>& stopSignal) { setCurThreadName("musicplayer.so worker"); ThreadHangDetector_registerCurThread("musicplayer.so worker", 5); while(true) { if(stopSignal) break; bool didSomething = loopFrame(this); ThreadHangDetector_lifeSignalCurThread(); if(!didSomething) usleep(1000); } ThreadHangDetector_unregisterCurThread(); } void PlayerObject::startWorkerThread() { workerThread.start(); } bool PlayerObject::readOutStream(OUTSAMPLE_t* samples, size_t sampleNum, size_t* sampleNumOut) { // We expect to have the PlayerObject lock here. PlayerObject* player = this; OUTSAMPLE_t* origSamples = samples; size_t origSampleNum = sampleNum; Fader::Scope faderScope(fader); if(player->playing) { if(faderScope.finished() && faderScope.sampleFactor() == 0) { // It means that we faded-out but we are in playing mode. // This means that we are awaiting for some worker-proc-command // to be executed. // Wait until buffers are full again. player->outOfSync = true; // Fill the buffer with silence. memset((uint8_t*)samples, 0, sampleNum*OUTSAMPLEBYTELEN); return false; } } if(player->playing || !faderScope.finished()) { if(sampleNumOut == NULL) { bool outOfSync = player->outOfSync.exchange(false); if(outOfSync) { // check if there is enough data size_t availableSize = 0; bool isEnough = false; for(PlayerInStream& is : player->inStreams) { availableSize += is.outBuffer.size(); if(availableSize > BUFFER_FILL_SIZE / 2) { // half the buffer size (e.g. ~5secs) isEnough = true; break; } if(!is.readerHitEnd) break; } if(!isEnough) { // silence memset((uint8_t*)samples, 0, sampleNum*OUTSAMPLEBYTELEN); player->outOfSync = true; return false; } } } for(PlayerInStream& is : player->inStreams) { is.playerStartedPlaying = true; size_t popCount = is.outBuffer.pop((uint8_t*)samples, sampleNum*OUTSAMPLEBYTELEN, false); popCount /= OUTSAMPLEBYTELEN; // because they are in bytes but we want number of samples { if(player->volumeAdjustNeeded(&is)) { for(size_t i = 0; i < popCount; ++i) { OUTSAMPLE_t* sampleAddr = samples + i; OUTSAMPLE_t sample = *sampleAddr; // TODO: endian swap? double sampleFloat = OutSampleAsFloat(sample); sampleFloat *= faderScope.sampleFactor(); sampleFloat *= player->volume; sampleFloat *= is.gainFactor; sampleFloat = player->volumeSmoothClip.get(sampleFloat); sample = (OUTSAMPLE_t) FloatToOutSample(sampleFloat); *sampleAddr = sample; // TODO: endian swap? if(i % player->outNumChannels == player->outNumChannels - 1) faderScope.frameTick(); } } } samples += popCount; sampleNum -= popCount; is.playerTimePos = is.playerTimePos + timeDelay(popCount); if(sampleNum == 0) break; // if the reader hit not the end but we haven't filled this buffer, // it means that our reading+decoding thread is behind. // we can't do anything here, so break. if(!is.readerHitEnd) break; // The worker thread will switch to the next song. is.playerHitEnd = true; } } if(sampleNum > 0 && sampleNumOut == NULL) { if(player->playing) printf("readOutStream: we have %zu too less samples available (requested %zu)\n", sampleNum, origSampleNum); // Fade out the current buffer. // Note that this is somewhat hacky, as the number of filled samples vary. // But it's still the best we can do here. const size_t filledSampleNum = origSampleNum - sampleNum; for(size_t i = 0; i < filledSampleNum; ++i) { OUTSAMPLE_t* sampleAddr = origSamples + i; OUTSAMPLE_t sample = *sampleAddr; // TODO: endian swap? double sampleFloat = OutSampleAsFloat(sample); // Very simple. Ignores outNumChannels. But doesn't matter that much. sampleFloat *= double(filledSampleNum - i - 1) / filledSampleNum; sample = (OUTSAMPLE_t) FloatToOutSample(sampleFloat); *sampleAddr = sample; // TODO: endian swap? } // Fill the remaining with silence. memset((uint8_t*)samples, 0, sampleNum*OUTSAMPLEBYTELEN); // When we play again, fade in again. faderScope.resetZero(); // We are now out-of-sync. // Only start playing again when we have enough data. player->outOfSync = true; } if(sampleNumOut) *sampleNumOut = origSampleNum - sampleNum; return sampleNum == 0; } PyObject * pySetFfmpegLogLevel(PyObject* self, PyObject* args) { int level = 0; if(!PyArg_ParseTuple(args, "i:setFfmpegLogLevel", &level)) return NULL; av_log_set_level(level); Py_INCREF(Py_None); return Py_None; } PyObject * pyEnableDebugLog(PyObject* self, PyObject* args) { PyObject* value = NULL; if(!PyArg_ParseTuple(args, "O:enableDebugLog", &value)) return NULL; Log::enabled = PyObject_IsTrue(value); Py_INCREF(Py_None); return Py_None; }
28.210526
773
0.668349
albertz
b3bb7024e5e4f424c0c5d0927f92c63be9d4c0b7
1,274
hpp
C++
22_Pvector/Pvector.hpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
22_Pvector/Pvector.hpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
22_Pvector/Pvector.hpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
#include <vector> #include <fstream> #include <iostream> using namespace std; #ifndef INC_41_TRAITS_PVECTOR_HPP #define INC_41_TRAITS_PVECTOR_HPP template<typename T> struct persistence_traits { static void write(ofstream &o, const T &elem) { o << elem << endl; } }; template<typename T, typename P=persistence_traits<T>> class Pvector { string filename; vector<T> v; void read_vector() { ifstream ifs(filename); for (;;) { T x; ifs >> x; if (!ifs.good()) { break; } v.push_back(x); } } void write_vector() { ofstream ofs(filename); for (const T &elem : v) { persister::write(ofs, elem); } } public: typedef P persister; explicit Pvector(string fname) : filename(fname) { read_vector(); } ~Pvector() { write_vector(); cout << "Destructor called!" << endl; } void push_back(const T &el) { v.push_back(el); } void pop_back() { v.pop_back(); } long getSize() { return v.size(); } void printElement(int index) { cout << v.at(index) << endl; } }; #endif //INC_41_TRAITS_PVECTOR_HPP
18.2
54
0.536892
jonixis
b3bc314b3e857569bdb88feaed3e98e849c6c9d7
1,442
cpp
C++
src/walls.cpp
JulianNeeleman/kattis
035c1113ffb397c2d8538af8ba16b7ee4160393d
[ "MIT" ]
null
null
null
src/walls.cpp
JulianNeeleman/kattis
035c1113ffb397c2d8538af8ba16b7ee4160393d
[ "MIT" ]
1
2017-05-16T15:57:29.000Z
2017-05-17T19:43:56.000Z
src/walls.cpp
JulianNeeleman/kattis
035c1113ffb397c2d8538af8ba16b7ee4160393d
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <vector> #include <cmath> using namespace std; const double epsilon = 0.0001; struct Point { double x, y; }; double dist(const Point& p, const Point& q) { return sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y)); } int check(const vector<Point>& ws, const vector<Point>& cs, double r) { for(const Point &p : ws) { bool success = false; for(const Point &q : cs) { if(dist(p, q) <= r + epsilon) success = true; } if(!success) return 5; } return cs.size(); } int main() { double l, w, n, r; cin >> l >> w >> n >> r; vector<Point> ws = { { -l / 2.0, 0.0 }, { l / 2.0, 0.0 }, { 0.0, -w / 2.0 }, { 0.0, w / 2.0 } }; vector<Point> cs(n); for(int i = 0; i < n; i++) { cin >> cs[i].x >> cs[i].y; } int ans = 5; vector<Point> cur; for(int a = 0; a < n; a++) { cur.push_back(cs[a]); ans = min(ans, check(ws, cur, r)); for(int b = a + 1; b < n; b++) { cur.push_back(cs[b]); ans = min(ans, check(ws, cur, r)); for(int c = b + 1; c < n; c++) { cur.push_back(cs[c]); ans = min(ans, check(ws, cur, r)); for(int d = c + 1; d < n; d++) { cur.push_back(cs[d]); ans = min(ans, check(ws, cur, r)); cur.pop_back(); } cur.pop_back(); } cur.pop_back(); } cur.pop_back(); } if(ans < 5) cout << ans << endl; else cout << "Impossible" << endl; return 0; }
20.309859
71
0.520111
JulianNeeleman
b3bcd8253059818f8721730ed9c272478c943a7e
23,067
cpp
C++
emf_core_bindings/src/emf_fs.cpp
GabeRealB/emf
a233edaed7ed99948b0a935e6378bac131fdf4c2
[ "Apache-2.0", "MIT" ]
null
null
null
emf_core_bindings/src/emf_fs.cpp
GabeRealB/emf
a233edaed7ed99948b0a935e6378bac131fdf4c2
[ "Apache-2.0", "MIT" ]
null
null
null
emf_core_bindings/src/emf_fs.cpp
GabeRealB/emf
a233edaed7ed99948b0a935e6378bac131fdf4c2
[ "Apache-2.0", "MIT" ]
1
2021-01-10T15:00:08.000Z
2021-01-10T15:00:08.000Z
#include <emf_core/emf_fs.h> #include <emf_core_bindings/emf_core_bindings.h> using namespace EMF::Core::C; namespace EMF::Core::Bindings::C { extern "C" { emf_file_handler_t EMF_CALL_C emf_fs_register_file_handler(const emf_file_handler_interface_t* EMF_NOT_NULL file_handler, const emf_file_type_span_t* EMF_NOT_NULL file_types) EMF_NOEXCEPT { EMF_ASSERT_ERROR(file_handler != nullptr, "emf_fs_register_file_handler()") EMF_ASSERT_ERROR(file_types != nullptr, "emf_fs_register_file_handler()") EMF_ASSERT_ERROR(file_types->data != nullptr, "emf_fs_register_file_handler()") EMF_ASSERT_ERROR(file_types->length > 0, "emf_fs_register_file_handler()") return emf_binding_interface->fs_register_file_handler_fn(file_handler, file_types); } void EMF_CALL_C emf_fs_remove_file_handler(emf_file_handler_t file_handler) EMF_NOEXCEPT { emf_binding_interface->fs_remove_file_handler_fn(file_handler); } void EMF_CALL_C emf_fs_create_file(const emf_path_t* EMF_NOT_NULL filename, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT { EMF_ASSERT_ERROR(filename != nullptr, "emf_fs_create_file()") EMF_ASSERT_ERROR(emf_fs_exists(filename) == emf_bool_false, "emf_fs_create_file()") #ifdef EMF_ENABLE_DEBUG_ASSERTIONS auto parent { emf_fs_get_parent(filename) }; EMF_ASSERT_ERROR(emf_fs_exists(&parent) == emf_bool_true, "emf_fs_create_file()") EMF_ASSERT_ERROR(emf_fs_is_virtual(&parent) == emf_bool_false, "emf_fs_create_file()") EMF_ASSERT_ERROR(emf_fs_get_access_mode(&parent) == emf_file_access_mode_write, "emf_fs_create_file()") #endif // EMF_ENABLE_DEBUG_ASSERTIONS emf_binding_interface->fs_create_file_fn(filename, options); } void EMF_CALL_C emf_fs_create_link( const emf_path_t* EMF_NOT_NULL source, const emf_path_t* EMF_NOT_NULL destination, emf_fs_link_t type) EMF_NOEXCEPT { EMF_ASSERT_ERROR(source != nullptr, "emf_fs_create_link()") EMF_ASSERT_ERROR(destination != nullptr, "emf_fs_create_link()") EMF_ASSERT_ERROR(emf_fs_exists(source) == emf_bool_true, "emf_fs_create_link()") EMF_ASSERT_ERROR(emf_fs_exists(destination) == emf_bool_false, "emf_fs_create_link()") EMF_ASSERT_ERROR(emf_fs_is_virtual(source) == emf_bool_false, "emf_fs_create_link()") #ifdef EMF_ENABLE_DEBUG_ASSERTIONS auto destination_parent { emf_fs_get_parent(destination) }; EMF_ASSERT_ERROR(emf_fs_exists(&destination_parent) == emf_bool_true, "emf_fs_create_link()") EMF_ASSERT_ERROR(emf_fs_is_virtual(&destination_parent) == emf_bool_true, "emf_fs_create_link()") EMF_ASSERT_ERROR(emf_fs_get_access_mode(&destination_parent) == emf_file_access_mode_write, "emf_fs_create_link()") #endif // EMF_ENABLE_DEBUG_ASSERTIONS emf_binding_interface->fs_create_link_fn(source, destination, type); } void EMF_CALL_C emf_fs_create_directory(const emf_path_t* EMF_NOT_NULL path, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_create_directory()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_false, "emf_fs_create_directory()") #ifdef EMF_ENABLE_DEBUG_ASSERTIONS auto parent { emf_fs_get_parent(path) }; EMF_ASSERT_ERROR(emf_fs_exists(&parent) == emf_bool_true, "emf_fs_create_directory()") EMF_ASSERT_ERROR(emf_fs_get_access_mode(&parent) == emf_file_access_mode_write, "emf_fs_create_directory()") #endif // EMF_ENABLE_DEBUG_ASSERTIONS emf_binding_interface->fs_create_directory_fn(path, options); } void EMF_CALL_C emf_fs_delete(const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_delete()") EMF_ASSERT_ERROR(emf_fs_can_delete(path, recursive) == emf_bool_true, "emf_fs_delete()") emf_binding_interface->fs_delete_fn(path, recursive); } emf_mount_id_t EMF_CALL_C emf_fs_mount_memory_file(emf_file_handler_t file_handler, const emf_memory_span_t* EMF_NOT_NULL file, emf_access_mode_t access_mode, const emf_path_t* EMF_NOT_NULL mount_point, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT { EMF_ASSERT_ERROR(file != nullptr, "emf_fs_mount_memory_file()") EMF_ASSERT_ERROR(mount_point != nullptr, "emf_fs_mount_memory_file()") EMF_ASSERT_ERROR(file->data != nullptr, "emf_fs_mount_memory_file()") EMF_ASSERT_ERROR(file->length > 0, "emf_fs_mount_memory_file()") EMF_ASSERT_ERROR(emf_fs_exists(mount_point) == emf_bool_false, "emf_fs_mount_memory_file()") #ifdef EMF_ENABLE_DEBUG_ASSERTIONS auto mount_point_parent { emf_fs_get_parent(mount_point) }; EMF_ASSERT_ERROR(emf_fs_exists(&mount_point_parent) == emf_bool_true, "emf_fs_mount_memory_file()") EMF_ASSERT_ERROR(emf_fs_is_virtual(&mount_point_parent) == emf_bool_true, "emf_fs_mount_memory_file()") EMF_ASSERT_ERROR(emf_fs_get_access_mode(&mount_point_parent) == emf_file_access_mode_write, "emf_fs_mount_memory_file()") #endif // EMF_ENABLE_DEBUG_ASSERTIONS return emf_binding_interface->fs_mount_memory_file_fn(file_handler, file, access_mode, mount_point, options); } emf_mount_id_t EMF_CALL_C emf_fs_mount_native_path(emf_file_handler_t file_handler, const emf_native_path_char_t* EMF_NOT_NULL path, emf_access_mode_t access_mode, const emf_path_t* EMF_NOT_NULL mount_point, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_mount_native_path()") EMF_ASSERT_ERROR(mount_point != nullptr, "emf_fs_mount_native_path()") EMF_ASSERT_ERROR(emf_fs_can_mount_native_path(file_handler, path) == emf_bool_true, "emf_fs_mount_native_path()") EMF_ASSERT_ERROR(emf_fs_exists(mount_point) == emf_bool_false, "emf_fs_mount_native_path()") #ifdef EMF_ENABLE_DEBUG_ASSERTIONS auto mount_point_parent { emf_fs_get_parent(mount_point) }; EMF_ASSERT_ERROR(emf_fs_exists(&mount_point_parent) == emf_bool_true, "emf_fs_mount_native_path()") EMF_ASSERT_ERROR(emf_fs_is_virtual(&mount_point_parent) == emf_bool_true, "emf_fs_mount_native_path()") EMF_ASSERT_ERROR(emf_fs_get_access_mode(&mount_point_parent) == emf_file_access_mode_write, "emf_fs_mount_native_path()") #endif // EMF_ENABLE_DEBUG_ASSERTIONS return emf_binding_interface->fs_mount_native_path_fn(file_handler, path, access_mode, mount_point, options); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_unmount(emf_mount_id_t mount_id) EMF_NOEXCEPT { return emf_binding_interface->fs_unmount_fn(mount_id); } void EMF_CALL_C emf_fs_set_access_mode( const emf_path_t* EMF_NOT_NULL path, emf_access_mode_t access_mode, emf_bool_t recursive) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_set_access_mode()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_set_access_mode()") EMF_ASSERT_ERROR(emf_fs_can_set_access_mode(path, access_mode, recursive) == emf_bool_true, "emf_fs_set_access_mode()") emf_binding_interface->fs_set_access_mode_fn(path, access_mode, recursive); } EMF_NODISCARD emf_access_mode_t EMF_CALL_C emf_fs_get_access_mode(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_access_mode()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_access_mode()") return emf_binding_interface->fs_get_access_mode_fn(path); } EMF_NODISCARD emf_mount_id_t EMF_CALL_C emf_fs_get_mount_id(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_mount_id()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_mount_id()") EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false || emf_fs_get_entry_type(path) == emf_fs_entry_type_mount_point, "emf_fs_get_mount_id()") return emf_binding_interface->fs_get_mount_id_fn(path); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_access( const emf_path_t* EMF_NOT_NULL path, emf_access_mode_t access_mode) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_access()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_can_access()") return emf_binding_interface->fs_can_access_fn(path, access_mode); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_set_access_mode( const emf_path_t* EMF_NOT_NULL path, emf_access_mode_t access_mode, emf_bool_t recursive) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_set_access_mode()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_can_set_access_mode()") return emf_binding_interface->fs_can_set_access_mode_fn(path, access_mode, recursive); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_is_virtual(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_is_virtual()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_is_virtual()") return emf_binding_interface->fs_is_virtual_fn(path); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_delete(const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_delete()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_can_delete()") return emf_binding_interface->fs_can_delete_fn(path, recursive); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_mount_type( emf_file_handler_t file_handler, const emf_file_type_t* EMF_NOT_NULL type) EMF_NOEXCEPT { EMF_ASSERT_ERROR(type != nullptr, "emf_fs_can_mount_type()") return emf_binding_interface->fs_can_mount_type_fn(file_handler, type); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_can_mount_native_path( emf_file_handler_t file_handler, const emf_native_path_char_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_can_mount_native_path()") return emf_binding_interface->fs_can_mount_native_path_fn(file_handler, path); } EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_entries(const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_num_entries()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_num_entries()") return emf_binding_interface->fs_get_num_entries_fn(path, recursive); } size_t EMF_CALL_C emf_fs_get_entries( const emf_path_t* EMF_NOT_NULL path, emf_bool_t recursive, emf_path_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_entries()") EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_entries()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_entries()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_entries()") EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_entries(path, recursive), "emf_fs_get_entries()") return emf_binding_interface->fs_get_entries_fn(path, recursive, buffer); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_exists(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_exists()") return emf_binding_interface->fs_exists_fn(path); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_type_exists(const emf_file_type_t* EMF_NOT_NULL type) EMF_NOEXCEPT { EMF_ASSERT_ERROR(type != nullptr, "emf_fs_exists()") return emf_binding_interface->fs_type_exists_fn(type); } EMF_NODISCARD emf_fs_entry_type_t EMF_CALL_C emf_fs_get_entry_type(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_entry_type()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_entry_type()") return emf_binding_interface->fs_get_entry_type_fn(path); } EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_resolve_link(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_resolve_link()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_resolve_link()") EMF_ASSERT_ERROR(emf_fs_get_entry_type(path) == emf_fs_entry_type_link, "emf_fs_resolve_link()") return emf_binding_interface->fs_resolve_link_fn(path); } EMF_NODISCARD emf_fs_link_t EMF_CALL_C emf_fs_get_link_type(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_link_type()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_link_type()") EMF_ASSERT_ERROR(emf_fs_get_entry_type(path) == emf_fs_entry_type_link, "emf_fs_get_link_type()") return emf_binding_interface->fs_get_link_type_fn(path); } EMF_NODISCARD emf_entry_size_t EMF_CALL_C emf_fs_get_size(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_size()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_size()") return emf_binding_interface->fs_get_size_fn(path); } EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_native_path_length(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_native_path_length()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_native_path_length()") EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false, "emf_fs_get_native_path_length()") return emf_binding_interface->fs_get_native_path_length_fn(path); } size_t EMF_CALL_C emf_fs_get_native_path( const emf_path_t* EMF_NOT_NULL path, emf_native_path_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_native_path()") EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_native_path()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_get_native_path()") EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false, "emf_fs_get_native_path()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_native_path()") EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_native_path_length(path), "emf_fs_get_native_path()") return emf_binding_interface->fs_get_native_path_fn(path, buffer); } EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_file_handlers() EMF_NOEXCEPT { return emf_binding_interface->fs_get_num_file_handlers_fn(); } size_t EMF_CALL_C emf_fs_get_file_handlers(emf_file_handler_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT { EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_file_handlers()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_file_handlers()") EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_file_handlers(), "emf_fs_get_file_handlers()") return emf_binding_interface->fs_get_file_handlers_fn(buffer); } EMF_NODISCARD emf_file_handler_t EMF_CALL_C emf_fs_get_file_handler_from_type( const emf_file_type_t* EMF_NOT_NULL type) EMF_NOEXCEPT { EMF_ASSERT_ERROR(type != nullptr, "emf_fs_get_file_handler_from_type()") EMF_ASSERT_ERROR(emf_fs_type_exists(type) == emf_bool_true, "emf_fs_get_file_handler_from_type()") return emf_binding_interface->fs_get_file_handler_from_type_fn(type); } EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_file_types() EMF_NOEXCEPT { return emf_binding_interface->fs_get_num_file_types_fn(); } size_t EMF_CALL_C emf_fs_get_file_types(emf_file_type_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT { EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_file_types()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_file_types()") EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_file_types(), "emf_fs_get_file_types()") return emf_binding_interface->fs_get_file_types_fn(buffer); } EMF_NODISCARD size_t EMF_CALL_C emf_fs_get_num_handler_file_types(emf_file_handler_t file_handler) EMF_NOEXCEPT { return emf_binding_interface->fs_get_num_handler_file_types_fn(file_handler); } size_t EMF_CALL_C emf_fs_get_handler_file_types( emf_file_handler_t file_handler, emf_file_type_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT { EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_get_file_types()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_get_file_types()") EMF_ASSERT_ERROR(buffer->length >= emf_fs_get_num_handler_file_types(file_handler), "emf_fs_get_file_types()") return emf_binding_interface->fs_get_handler_file_types_fn(file_handler, buffer); } EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_normalize(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_normalize()") return emf_binding_interface->fs_normalize_fn(path); } EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_get_parent(const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_get_parent()") return emf_binding_interface->fs_get_parent_fn(path); } EMF_NODISCARD emf_path_t EMF_CALL_C emf_fs_join( const emf_path_t* EMF_NOT_NULL lhs, const emf_path_t* EMF_NOT_NULL rhs) EMF_NOEXCEPT { EMF_ASSERT_ERROR(lhs != nullptr, "emf_fs_join()") EMF_ASSERT_ERROR(rhs != nullptr, "emf_fs_join()") return emf_binding_interface->fs_join_fn(lhs, rhs); } EMF_NODISCARD emf_mount_id_t EMF_CALL_C emf_fs_unsafe_create_mount_id(const emf_path_t* EMF_NOT_NULL mount_point) EMF_NOEXCEPT { EMF_ASSERT_ERROR(mount_point != nullptr, "emf_fs_unsafe_create_mount_id()") EMF_ASSERT_ERROR(emf_fs_exists(mount_point) == emf_bool_false, "emf_fs_unsafe_create_mount_id()") #ifdef EMF_ENABLE_DEBUG_ASSERTIONS auto mount_point_parent { emf_fs_get_parent(mount_point) }; EMF_ASSERT_ERROR(emf_fs_exists(&mount_point_parent) == emf_bool_true, "emf_fs_unsafe_create_mount_id()") EMF_ASSERT_ERROR(emf_fs_get_access_mode(&mount_point_parent) == emf_file_access_mode_write, "emf_fs_unsafe_create_mount_id()") #endif // EMF_ENABLE_DEBUG_ASSERTIONS return emf_binding_interface->fs_unsafe_create_mount_id_fn(mount_point); } void EMF_CALL_C emf_fs_unsafe_remove_mount_id(emf_mount_id_t mount_id) EMF_NOEXCEPT { emf_binding_interface->fs_unsafe_remove_mount_id_fn(mount_id); } void EMF_CALL_C emf_fs_unsafe_unmount_force(emf_mount_id_t mount_id) EMF_NOEXCEPT { emf_binding_interface->fs_unsafe_unmount_force_fn(mount_id); } void EMF_CALL_C emf_fs_unsafe_link_mount_point( emf_mount_id_t mount_id, emf_file_handler_t file_handler, emf_file_handler_mount_id_t file_handler_mount_id) EMF_NOEXCEPT { emf_binding_interface->fs_unsafe_link_mount_point_fn(mount_id, file_handler, file_handler_mount_id); } EMF_NODISCARD emf_file_stream_t EMF_CALL_C emf_fs_unsafe_create_file_stream() EMF_NOEXCEPT { return emf_binding_interface->fs_unsafe_create_file_stream_fn(); } void EMF_CALL_C emf_fs_unsafe_remove_file_stream(emf_file_stream_t file_stream) EMF_NOEXCEPT { emf_binding_interface->fs_unsafe_remove_file_stream_fn(file_stream); } void EMF_CALL_C emf_fs_unsafe_link_file_stream( emf_file_stream_t file_stream, emf_file_handler_t file_handler, emf_file_handler_stream_t file_handler_stream) EMF_NOEXCEPT { emf_binding_interface->fs_unsafe_link_file_stream_fn(file_stream, file_handler, file_handler_stream); } EMF_NODISCARD emf_file_handler_t EMF_CALL_C emf_fs_unsafe_get_file_handler_handle_from_stream( emf_file_stream_t stream) EMF_NOEXCEPT { return emf_binding_interface->fs_unsafe_get_file_handler_handle_from_stream_fn(stream); } EMF_NODISCARD emf_file_handler_t EMF_CALL_C emf_fs_unsafe_get_file_handler_handle_from_path( const emf_path_t* EMF_NOT_NULL path) EMF_NOEXCEPT { EMF_ASSERT_ERROR(path != nullptr, "emf_fs_unsafe_get_file_handler_handle_from_path()") EMF_ASSERT_ERROR(emf_fs_exists(path) == emf_bool_true, "emf_fs_unsafe_get_file_handler_handle_from_path()") EMF_ASSERT_ERROR(emf_fs_is_virtual(path) == emf_bool_false || emf_fs_get_entry_type(path) == emf_fs_entry_type_mount_point, "emf_fs_unsafe_get_file_handler_handle_from_path()") return emf_binding_interface->fs_unsafe_get_file_handler_handle_from_path_fn(path); } EMF_NODISCARD emf_file_handler_stream_t EMF_CALL_C emf_fs_unsafe_get_file_handler_stream( emf_file_stream_t file_stream) EMF_NOEXCEPT { return emf_binding_interface->fs_unsafe_get_file_handler_stream_fn(file_stream); } EMF_NODISCARD emf_file_handler_mount_id_t EMF_CALL_C emf_fs_unsafe_get_file_handler_mount_id(emf_mount_id_t mount_id) EMF_NOEXCEPT { return emf_binding_interface->fs_unsafe_get_file_handler_mount_id_fn(mount_id); } EMF_NODISCARD emf_file_handler_interface_t EMF_CALL_C emf_fs_unsafe_get_file_handler(emf_file_handler_t file_handler) EMF_NOEXCEPT { return emf_binding_interface->fs_unsafe_get_file_handler_fn(file_handler); } EMF_NODISCARD emf_file_stream_t EMF_CALL_C emf_fs_stream_open(const emf_path_t* EMF_NOT_NULL filename, emf_file_open_mode_t open_mode, emf_access_mode_t access_mode, const void* EMF_MAYBE_NULL options) EMF_NOEXCEPT { EMF_ASSERT_ERROR(filename != nullptr, "emf_fs_stream_open()") EMF_ASSERT_ERROR(emf_fs_get_entry_type(filename) == emf_fs_entry_type_file, "emf_fs_stream_open()") EMF_ASSERT_ERROR(emf_fs_can_access(filename, access_mode) == emf_bool_true, "emf_fs_stream_open()") return emf_binding_interface->fs_stream_open_fn(filename, open_mode, access_mode, options); } void EMF_CALL_C emf_fs_stream_close(emf_file_stream_t stream) EMF_NOEXCEPT { emf_binding_interface->fs_stream_close_fn(stream); } void EMF_CALL_C emf_fs_stream_flush(emf_file_stream_t stream) EMF_NOEXCEPT { emf_binding_interface->fs_stream_flush_fn(stream); } size_t EMF_CALL_C emf_fs_stream_read( emf_file_stream_t stream, emf_fs_buffer_t* EMF_NOT_NULL buffer, size_t read_count) EMF_NOEXCEPT { EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_stream_read()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_stream_read()") EMF_ASSERT_ERROR(buffer->length >= read_count, "emf_fs_stream_read()") return emf_binding_interface->fs_stream_read_fn(stream, buffer, read_count); } size_t EMF_CALL_C emf_fs_stream_write( emf_file_stream_t stream, const emf_fs_buffer_t* EMF_NOT_NULL buffer, size_t write_count) EMF_NOEXCEPT { EMF_ASSERT_ERROR(buffer != nullptr, "emf_fs_stream_write()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_fs_stream_write()") EMF_ASSERT_ERROR(buffer->length >= write_count, "emf_fs_stream_write()") EMF_ASSERT_ERROR(emf_fs_stream_can_write(stream) == emf_bool_true, "emf_fs_stream_write()") return emf_binding_interface->fs_stream_write_fn(stream, buffer, write_count); } EMF_NODISCARD emf_pos_t EMF_CALL_C emf_fs_stream_get_pos(emf_file_stream_t stream) EMF_NOEXCEPT { return emf_binding_interface->fs_stream_get_pos_fn(stream); } emf_off_t EMF_CALL_C emf_fs_stream_set_pos(emf_file_stream_t stream, emf_pos_t position) EMF_NOEXCEPT { return emf_binding_interface->fs_stream_set_pos_fn(stream, position); } emf_off_t EMF_CALL_C emf_fs_stream_move_pos(emf_file_stream_t stream, emf_off_t offset, emf_fs_direction_t direction) EMF_NOEXCEPT { return emf_binding_interface->fs_stream_move_pos_fn(stream, offset, direction); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_stream_can_write(emf_file_stream_t stream) EMF_NOEXCEPT { return emf_binding_interface->fs_stream_can_write_fn(stream); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_fs_stream_can_grow(emf_file_stream_t stream, size_t size) EMF_NOEXCEPT { return emf_binding_interface->fs_stream_can_grow_fn(stream, size); } } }
48.460084
130
0.816144
GabeRealB
b3be0ea154014d1eed00974a8b0250dfd275c0b2
413
cpp
C++
Appserver/src/servicios/ServicioInexistente.cpp
seguijoaquin/taller2
f41232516de15fe045805131b09299e5c2634e5e
[ "MIT" ]
2
2016-06-06T03:26:49.000Z
2017-08-06T18:12:33.000Z
Appserver/src/servicios/ServicioInexistente.cpp
seguijoaquin/taller2
f41232516de15fe045805131b09299e5c2634e5e
[ "MIT" ]
60
2016-03-19T16:01:27.000Z
2016-06-23T16:26:10.000Z
Appserver/src/servicios/ServicioInexistente.cpp
seguijoaquin/taller2
f41232516de15fe045805131b09299e5c2634e5e
[ "MIT" ]
null
null
null
#include "ServicioInexistente.h" ServicioInexistente::ServicioInexistente(){ Logger::Instance()->log(WARNING, "Se crea el Servicio Inexstente"); this->respuesta = new RespuestaServicioInexistente(); } ServicioInexistente::~ServicioInexistente() { //dtor } void ServicioInexistente::setRespuestaTokenInvalido(){ ((RespuestaServicioInexistente*) this->respuesta)->setRespuestaTokenInvalido(); }
24.294118
83
0.762712
seguijoaquin
b3c2be0d7c9f027f32390842006099361e76ec7d
135
cpp
C++
Cplusplus/week_four/extra/DailyTask_Mechanic/man.cpp
nexusstar/SoftUni
b97bdb08a227fd335df5b7869940c14717f760f2
[ "MIT" ]
1
2016-12-20T19:53:03.000Z
2016-12-20T19:53:03.000Z
Cplusplus/week_four/extra/DailyTask_Mechanic/man.cpp
nexusstar/SoftUni
b97bdb08a227fd335df5b7869940c14717f760f2
[ "MIT" ]
null
null
null
Cplusplus/week_four/extra/DailyTask_Mechanic/man.cpp
nexusstar/SoftUni
b97bdb08a227fd335df5b7869940c14717f760f2
[ "MIT" ]
null
null
null
#include "man.h" #include "car.h" void Man::crashCar(Car &aCar) { if(aCar.needsRepair == true) return; aCar.needsRepair = true; }
15
38
0.666667
nexusstar
b3c2ef63f883c3d06f27912aa32ed1534c46e34d
2,814
cpp
C++
source/Windows/Storage/File.cpp
awstanley/cpp-gamefilesystem
fc06cf5f2b4f873846677f45fa5480a69cdd91df
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2021-07-12T19:25:29.000Z
2021-07-12T19:25:29.000Z
source/Windows/Storage/File.cpp
awstanley/cpp-gamefilesystem
fc06cf5f2b4f873846677f45fa5480a69cdd91df
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
6
2017-10-16T19:30:25.000Z
2018-10-06T23:55:19.000Z
source/Windows/Storage/File.cpp
awstanley/cpp-gamefilesystem
fc06cf5f2b4f873846677f45fa5480a69cdd91df
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2017-10-14T10:21:44.000Z
2021-07-12T19:25:39.000Z
/* * Copyright 2017-2018 ReversingSpace. See the COPYRIGHT file at the * top-level directory of this distribution and in the repository: * https://github.com/ReversingSpace/cpp-gamefilesystem * * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your * option. This file may not be copied, modified, or distributed * except according to those terms. **/ // This is the WINDOWS file code. #if defined(_WIN32) || defined(_WIN64) #include <ReversingSpace/Storage/File.hpp> #include <Windows.h> #if defined(_DEBUG) #include <stdio.h> #endif namespace reversingspace { #if REVERSINGSPACE_STORAGE_GRANULARITY == 1 namespace platform { std::uint64_t get_granularity() { SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); std::uint64_t granularity = SystemInfo.dwAllocationGranularity; return granularity; } } #endif namespace storage { bool File::open() { // Shared mode is *always* READ|WRITE, as we don't care // and shouldn't care. For games, this is a non-issue, // and it allows modders to do things. Changing this // reflects a massive change that we probably don't want // to have to deal with. DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; DWORD dwDesiredAccess = GENERIC_READ; DWORD dwCreationDisposition = OPEN_ALWAYS; DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; switch (access) { case FileAccess::Read: { dwCreationDisposition = OPEN_EXISTING; dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY; } break; case FileAccess::Write: { dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; } break; case FileAccess::ReadWrite: { dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; } break; case FileAccess::ReadExecute: case FileAccess::Execute: { // This bodes terribly. dwDesiredAccess = GENERIC_READ | GENERIC_EXECUTE; } break; case FileAccess::ReadWriteExecute: { dwDesiredAccess = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE; } break; } // This creates (or opens) the file. Naming is somewhat obvious, // but the arguments are kind of weird to anyone used to `fopen`. file_handle = ::CreateFileW( path.wstring().c_str(), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL ); if (file_handle == INVALID_HANDLE_VALUE) { #if defined(_DEBUG) auto error = GetLastError(); fprintf(stderr, "Error in CreateFileW call: %d\n", error); #endif return false; } return true; } // Platform-specific terminate. void File::close() { ::CloseHandle(file_handle); } } } #endif//defined(_WIN32) || defined(_WIN64)
28.714286
70
0.704691
awstanley
b3c43ce490d6003bf0804ccb623ab9ac6be650c6
1,094
hpp
C++
L7/EMail/SMTP/GpSmtpClientCurl.hpp
ITBear/GpNetwork
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
[ "Apache-2.0" ]
null
null
null
L7/EMail/SMTP/GpSmtpClientCurl.hpp
ITBear/GpNetwork
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
[ "Apache-2.0" ]
null
null
null
L7/EMail/SMTP/GpSmtpClientCurl.hpp
ITBear/GpNetwork
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
[ "Apache-2.0" ]
null
null
null
#pragma once #include "GpSmtpClient.hpp" typedef void CURL; namespace GPlatform { class GPNETWORK_API GpSmtpClientCurl final: public GpSmtpClient { public: CLASS_REMOVE_CTRS_MOVE_COPY(GpSmtpClientCurl) CLASS_DECLARE_DEFAULTS(GpSmtpClientCurl) public: GpSmtpClientCurl (void) noexcept; virtual ~GpSmtpClientCurl (void) noexcept override final; virtual std::string/*msg_id*/ Send (const GpEmail& aEmail) override final; virtual bool IsValid (void) const noexcept override final; private: void CurlInit (void); void CurlClear (void) noexcept; void FillAddrs (void* aCurlList, const GpEmailAddr::C::Vec::SP& aAddrList) const; private: CURL* iCurl = nullptr; }; }//namespace GPlatform
31.257143
106
0.5
ITBear
b3c5c742b8bc852eae598eaf1b1a12f53da03a96
324
cpp
C++
src/megabreakthrough/megapawn.cpp
hallur/boardgame
374fd1366cbae785bc40ba24403d50e36b2a3637
[ "MIT" ]
null
null
null
src/megabreakthrough/megapawn.cpp
hallur/boardgame
374fd1366cbae785bc40ba24403d50e36b2a3637
[ "MIT" ]
1
2018-04-09T19:08:41.000Z
2018-04-09T19:08:41.000Z
src/megabreakthrough/megapawn.cpp
hallur/boardgame
374fd1366cbae785bc40ba24403d50e36b2a3637
[ "MIT" ]
null
null
null
#include "megabreakthrough/megapawn.h" boardgame::megabreakthrough::MegaPawn::MegaPawn(boardgame::Player* player, bool top) : boardgame::breakthrough::Pawn(player, top, 'm') { moveRules_.push_back(MoveRule( 0, (top ? 1 : -1), true, false, false, 2 )); // up up } boardgame::megabreakthrough::MegaPawn::~MegaPawn() {}
46.285714
136
0.70679
hallur
b3c892cac66c0538a3d64bf3077a696e9424e054
7,047
cpp
C++
src/unittest/indexed_vg.cpp
fabbondanza/vg
86edd831bd76b4c33e4cf51134f557c49736cf2b
[ "MIT" ]
2
2015-07-07T13:32:55.000Z
2016-05-03T00:09:20.000Z
src/unittest/indexed_vg.cpp
fabbondanza/vg
86edd831bd76b4c33e4cf51134f557c49736cf2b
[ "MIT" ]
2
2016-12-22T23:46:07.000Z
2021-07-28T17:49:50.000Z
src/unittest/indexed_vg.cpp
fabbondanza/vg
86edd831bd76b4c33e4cf51134f557c49736cf2b
[ "MIT" ]
1
2020-01-17T03:21:40.000Z
2020-01-17T03:21:40.000Z
/// \file indexed_vg.cpp /// /// unit tests for the vg-file-backed handle graph implementation #include <iostream> #include "json2pb.h" #include <vg/vg.pb.h> #include "../indexed_vg.hpp" #include "../vg.hpp" #include "../utility.hpp" #include "../algorithms/id_sort.hpp" #include "random_graph.hpp" #include "catch.hpp" namespace vg { namespace unittest { /// Save the given Graph into a temporary vg file and return the file name string save_vg_file(const Graph& graph) { string filename = temp_file::create(); VG vg; vg.extend(graph); // Serialize with a small chunk size so we can exercise the indexing vg.serialize_to_file(filename, 10); return filename; } using namespace std; TEST_CASE("An IndexedVG can be created for a single node", "[handle][indexed-vg]") { // This 1-node graph is sorted string graph_json = R"({ "node": [{"id": 1, "sequence": "GATTACA"}], "path": [ {"name": "ref", "mapping": [ {"position": {"node_id": 1}, "edit": [{"from_length": 7, "to_length": 7}]} ]} ] })"; // Load the JSON Graph proto_graph; json2pb(proto_graph, graph_json.c_str(), graph_json.size()); REQUIRE(proto_graph.node_size() == 1); // Save a vg file string vg_name = save_vg_file(proto_graph); { // Load the file up and build and save the index IndexedVG indexed(vg_name); for (auto& node : proto_graph.node()) { // For each node in the graph we saved // Get a handle handle_t handle = indexed.get_handle(node.id()); // Make sure it has the right ID REQUIRE(indexed.get_id(handle) == node.id()); // Make sure it has the right initial orientation REQUIRE(!indexed.get_is_reverse(handle)); // Make sure flipping works handle_t flipped = indexed.flip(handle); REQUIRE(indexed.get_id(flipped) == node.id()); REQUIRE(indexed.get_is_reverse(flipped)); REQUIRE(indexed.flip(flipped) == handle); // Make sure the length is correct REQUIRE(indexed.get_length(handle) == node.sequence().size()); // Make sure the sequence is correct REQUIRE(indexed.get_sequence(handle) == node.sequence()); // Since this graph is empty, make sure there are no edges REQUIRE(indexed.get_degree(handle, false) == 0); REQUIRE(indexed.get_degree(handle, true) == 0); } } // Clean up after the index temp_file::remove(vg_name); temp_file::remove(vg_name + ".vgi"); } TEST_CASE("IndexedVG works on random graphs", "[handle][indexed-vg]") { for (size_t trial = 0; trial < 5; trial++) { // Make a bunch of random graphs VG random; random_graph(300, 3, 30, &random); // Sort each by ID random.id_sort(); string filename = temp_file::create(); random.serialize_to_file(filename, 10); { // Load the file up and build and save the index IndexedVG indexed(filename); unordered_set<handle_t> indexed_handles; random.for_each_handle([&](const handle_t& node) { // For each node in the graph we saved // Get a handle in the index handle_t handle = indexed.get_handle(random.get_id(node)); // Remember it for later indexed_handles.insert(handle); // Make sure it has the right ID REQUIRE(indexed.get_id(handle) == random.get_id(node)); // Make sure it has the right initial orientation REQUIRE(!indexed.get_is_reverse(handle)); // Make sure flipping works handle_t flipped = indexed.flip(handle); REQUIRE(indexed.get_id(flipped) == random.get_id(node)); REQUIRE(indexed.get_is_reverse(flipped)); REQUIRE(indexed.flip(flipped) == handle); // Make sure the length is correct REQUIRE(indexed.get_length(handle) == random.get_length(node)); // Make sure the sequence is correct REQUIRE(indexed.get_sequence(handle) == random.get_sequence(node)); REQUIRE(indexed.get_sequence(indexed.flip(handle)) == random.get_sequence(random.flip(node))); // Make sure degrees agree REQUIRE(indexed.get_degree(handle, false) == random.get_degree(node, false)); REQUIRE(indexed.get_degree(handle, true) == random.get_degree(node, true)); // Make sure the edges match up under all conditions for (bool flip_it : {false, true}) { for (bool go_left : {false, true}) { unordered_set<handle_t> random_edge_partners; random.follow_edges(flip_it ? random.flip(node) : node, go_left, [&](const handle_t& other) { random_edge_partners.insert(other); }); indexed.follow_edges(flip_it ? indexed.flip(handle) : handle, go_left, [&](const handle_t& other) { // Get the corresponding random graph handle handle_t random_handle = random.get_handle(indexed.get_id(other), indexed.get_is_reverse(other)); REQUIRE(random_edge_partners.count(random_handle)); random_edge_partners.erase(random_handle); }); // Make sure we erased all the edges we added REQUIRE(random_edge_partners.empty()); } } }); // Make sure basic statistics agree REQUIRE(indexed.get_node_count() == random.get_node_count()); REQUIRE(indexed.min_node_id() == random.min_node_id()); REQUIRE(indexed.max_node_id() == random.max_node_id()); // Make sure we can loop over the handles OK indexed.for_each_handle([&](const handle_t& handle) { REQUIRE(indexed_handles.count(handle)); indexed_handles.erase(handle); }); REQUIRE(indexed_handles.size() == 0); } // Clean up after the index temp_file::remove(filename); temp_file::remove(filename + ".vgi"); } } } }
36.703125
125
0.52831
fabbondanza
b3c8c58b8227b04730f666745a2633845ac29820
4,323
hxx
C++
opencascade/XmlMDF.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
37
2020-01-20T21:50:21.000Z
2022-02-09T13:01:09.000Z
opencascade/XmlMDF.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/XmlMDF.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
22
2020-04-03T21:59:52.000Z
2022-03-06T18:43:35.000Z
// Created on: 2001-07-09 // Created by: Julia DOROVSKIKH // Copyright (c) 2001-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // 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, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _XmlMDF_HeaderFile #define _XmlMDF_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <XmlObjMgt_Element.hxx> #include <XmlObjMgt_SRelocationTable.hxx> #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> #include <XmlObjMgt_RRelocationTable.hxx> #include <XmlMDF_MapOfDriver.hxx> #include <Message_ProgressRange.hxx> class TDF_Data; class XmlMDF_ADriverTable; class TDF_Label; class Message_Messenger; class XmlMDF_ADriver; class XmlMDF_TagSourceDriver; class XmlMDF_ReferenceDriver; class XmlMDF_ADriverTable; //! This package provides classes and methods to //! translate a transient DF into a persistent one and //! vice versa. //! //! Driver //! //! A driver is a tool used to translate a transient //! attribute into a persistent one and vice versa. //! //! Driver Table //! //! A driver table is an object building links between //! object types and object drivers. In the //! translation process, a driver table is asked to //! give a translation driver for each current object //! to be translated. class XmlMDF { public: DEFINE_STANDARD_ALLOC //! Translates a transient <aSource> into a persistent //! <aTarget>. Standard_EXPORT static void FromTo (const Handle(TDF_Data)& aSource, XmlObjMgt_Element& aTarget, XmlObjMgt_SRelocationTable& aReloc, const Handle(XmlMDF_ADriverTable)& aDrivers, const Message_ProgressRange& theRange = Message_ProgressRange()); //! Translates a persistent <aSource> into a transient //! <aTarget>. //! Returns True if completed successfully (False on error) Standard_EXPORT static Standard_Boolean FromTo (const XmlObjMgt_Element& aSource, Handle(TDF_Data)& aTarget, XmlObjMgt_RRelocationTable& aReloc, const Handle(XmlMDF_ADriverTable)& aDrivers, const Message_ProgressRange& theRange = Message_ProgressRange()); //! Adds the attribute storage drivers to <aDriverSeq>. Standard_EXPORT static void AddDrivers (const Handle(XmlMDF_ADriverTable)& aDriverTable, const Handle(Message_Messenger)& theMessageDriver); private: Standard_EXPORT static Standard_Integer WriteSubTree (const TDF_Label& theLabel, XmlObjMgt_Element& theElement, XmlObjMgt_SRelocationTable& aReloc, const Handle(XmlMDF_ADriverTable)& aDrivers, const Message_ProgressRange& theRange = Message_ProgressRange()); Standard_EXPORT static Standard_Integer ReadSubTree (const XmlObjMgt_Element& theElement, const TDF_Label& theLabel, XmlObjMgt_RRelocationTable& aReloc, const XmlMDF_MapOfDriver& aDrivers, const Message_ProgressRange& theRange = Message_ProgressRange()); Standard_EXPORT static void CreateDrvMap (const Handle(XmlMDF_ADriverTable)& aDriverTable, XmlMDF_MapOfDriver& anAsciiDriverMap); friend class XmlMDF_ADriver; friend class XmlMDF_TagSourceDriver; friend class XmlMDF_ReferenceDriver; friend class XmlMDF_ADriverTable; }; #endif // _XmlMDF_HeaderFile
38.598214
103
0.664122
valgur
b3cee6ad0f5bc6392d02c9a9eef97a89b24f47c2
7,660
cpp
C++
Submissions/hw3/HW_swapPhase.cpp
ChibiKev/Image-Processing-Projects
7f37bd222bfe3738ee73bc47fb576718532019c0
[ "MIT" ]
null
null
null
Submissions/hw3/HW_swapPhase.cpp
ChibiKev/Image-Processing-Projects
7f37bd222bfe3738ee73bc47fb576718532019c0
[ "MIT" ]
null
null
null
Submissions/hw3/HW_swapPhase.cpp
ChibiKev/Image-Processing-Projects
7f37bd222bfe3738ee73bc47fb576718532019c0
[ "MIT" ]
null
null
null
#include "IP.h" using namespace IP; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW_swapPhase: // // Swap the phase channels of I1 and I2. // Output is in II1 and II2. // struct complexP { int len; // length of complex number list float * real; // pointer to real number list float * imag; // pointer to imaginary number list }; extern void HW_fft2MagPhase(ImagePtr Ifft, ImagePtr Imag, ImagePtr Iphase); extern void HW_MagPhase2fft(ImagePtr Imag, ImagePtr Iphase, ImagePtr Ifft); extern void fft1D(complexP *q1, int dir, complexP *q2); extern void fft1DRow(ImagePtr I1, ImagePtr Image1); extern void fft1DColumn(ImagePtr I1, ImagePtr Image1, ImagePtr Image2); extern void fft1DMagPhase(ImagePtr I1, ImagePtr Image2, float *Magnitude, float *Phase); extern float getMin(float arr[], int total); extern float getMax(float arr[], int total); void swapPhase(ImagePtr I, float * magnitude ,float * newPhase, int total); //Puts new phase on image I void Ifft1DRow(ImagePtr I, ImagePtr IFFT, ImagePtr IFFTout); void Ifft1DColumn(ImagePtr I, ImagePtr rowI, ImagePtr IFFTout, ImagePtr resultPtr); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HW_swapPhase: // // Swap phase of I1 with I2. // (I1_mag, I2_phase) -> II1 // (I1_phase, I2_mag) -> II2 // void HW_swapPhase(ImagePtr I1, ImagePtr I2, ImagePtr II1, ImagePtr II2) { //Dimensions of I1 int w1 = I1->width(); int h1 = I1->height(); int total1 = w1 * h1; //Dimensions of I2 int w2 = I2->width(); int h2 = I2->height(); int total2 = w2 * h2; //Checking that the images have same dimensions if(w1 != w2 || h1 != h2) { printf("Dimensions of I1: %d x %d \nDimensions of I2: %d x %d\nAre not equal\n",w1,h1,w2,h2); return; } // copy image header (width, height) of input image I1 to output image II1 & II2 IP_copyImageHeader(I1, II1); IP_copyImageHeader(I1, II2); // compute FFT of I1 and I2: ImagePtr I1FFTTemp; ImagePtr I1FFT; //Final FFT for Image I1 ImagePtr I2FFT; //Final FFT for Image I2 ImagePtr I2FFTTemp; //Allocating memory for FFT of images I1 and I2 I1FFT->allocImage(w1,h1,FFT_TYPE); I1FFTTemp->allocImage(w1, h1, FFT_TYPE); I2FFT->allocImage(w2,h2,FFT_TYPE); I2FFTTemp->allocImage(w2, h2, FFT_TYPE); //FFT of I1 fft1DRow(I1,I1FFTTemp); fft1DColumn(I1, I1FFTTemp, I1FFT); //FFT of I2 fft1DRow(I2, I2FFTTemp); fft1DColumn(I2, I2FFTTemp, I2FFT); // compute magnitude and phase from real and imaginary FFT channels float *magnitude1 = new float[total1]; // Declaring Magnitude for Img1 float *phase1 = new float[total1]; // Declairing Phase for Img1 fft1DMagPhase(I1, I1FFT, magnitude1 , phase1); float *magnitude2 = new float[total2]; // Declaring Magnitude for Img2 float *phase2 = new float[total2]; // Declairing Phase for Img2 fft1DMagPhase(I2, I2FFT, magnitude2 , phase2); //Impage Pointers to hold IFFT for FFT fo I1 ImagePtr I1IFFTTemp; ImagePtr I1Ifft; swapPhase(I1FFT,magnitude1,phase2,total1); //Take the phase of I2 and put it to I1 //Computing IFFT for FFT of I1 to get back image Ifft1DRow(I1,I1FFT, I1IFFTTemp); Ifft1DColumn(I1, I1IFFTTemp, I1Ifft, II1); //Impage Pointers to hold IFFT for FFT fo I2 ImagePtr I2IFFTTemp; ImagePtr I2Ifft; swapPhase(I2FFT,magnitude2,phase1,total2); //Take the phase of I1 and put it to I2 //Computing IFFT for FFT of I2 to get back image Ifft1DRow(I2,I2FFT, I2IFFTTemp); Ifft1DColumn(I2, I2IFFTTemp, I2Ifft, II2); } //Takes image I and puts the newPhase array as its phase void swapPhase(ImagePtr I, float * magnitude ,float * newPhase, int total) { ChannelPtr<float> real, img; real = I[0]; //Real ptr img = I[1]; //Imaginary ptr for (int i = 0; i < total; ++i){ //Update real and imaginary components with the new Phase *real++ = magnitude[i] * cos(newPhase[i]); *img++ = magnitude[i] * sin(newPhase[i]); } } void Ifft1DRow(ImagePtr I, ImagePtr IFFT ,ImagePtr IFFTout) { int w = I->width(); int h = I->height(); ChannelPtr<float> real, img, real2, img2; //Allocationg memory for output of FFT1D row IFFTout->allocImage(w, h, FFT_TYPE); real = IFFT[0]; //real ptr img = IFFT[1]; //img ptr real2 = IFFTout[0]; img2 = IFFTout[1]; complexP c1, c2, *q1, *q2; q1 = &c1; q2 = &c2; q1->len = w; // length of complex number list q1->real = new float[w]; // pointer to real number list q1->imag = new float[w]; // pointer to imaginary number list q2->len = w; // length of complex number list q2->real = new float[w]; // pointer to real number list q2->imag = new float[w]; // pointer to imaginary number list for (int row = 0; row < h; ++row) { for (int column = 0; column < w; ++column) { q1->real[column] = *real++; q1->imag[column] = *img++; } fft1D(q1, 1, q2); //Calling fft1D but with dir =1 for (int i = 0; i < q2->len; ++i) { *real2++ = q2->real[i]; // Sets Real Output to Image *img2++ = q2->imag[i]; // Sets Imaginary Output to Image1 } } } void Ifft1DColumn(ImagePtr I, ImagePtr IFFT ,ImagePtr IFFTout, ImagePtr II1) { int w = I->width(); int h = I->height(); ChannelPtr<float> real, img, real2, img2; ChannelPtr<uchar> pII1; //Pointer to our final output image int type; //Allocationg memory for output of FFT1D row IFFTout->allocImage(w, h, FFT_TYPE); real2 = IFFTout[0]; //real ptr img2 = IFFTout[1]; //img ptr for (int ch = 0; IP_getChannel(II1, ch, pII1, type); ++ch) { real = IFFT[0]; img = IFFT[1]; complexP c1, c2, *q1, *q2; q1 = &c1; q2 = &c2; q1->len = w; // length of complex number list q1->real = new float[w]; // pointer to real number list q1->imag = new float[w]; // pointer to imaginary number list q2->len = w; // length of complex number list q2->real = new float[w]; // pointer to real number list q2->imag = new float[w]; // pointer to imaginary number list for (int column = 0; column < w; ++column) { ChannelPtr<float> temp_real = real; //Ptr to real ChannelPtr<float> temp_img = img; //ptr to img for (int row = 0; row < h; ++row) { q1->real[row] = *temp_real; q1->imag[row] = *temp_img; if (row < h - 1) { temp_real += w; temp_img += w; } } fft1D(q1, 1, q2); //Calling fft1D but with dir =1 for (int i = 0; i < q2->len; ++i) { //Writing to final output image *pII1++ = CLIP(q2->real[i], 0, MaxGray); } real++; // Next Column For Real img++; // Next Column For Imaginary } } }
34.504505
103
0.550783
ChibiKev
b3cf3075b856c111d212ccfd8fe6e171f156002a
4,317
cpp
C++
ms-utils/math/approximation/QuadLinFit.cpp
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
18
2020-01-23T12:14:09.000Z
2022-02-27T22:11:35.000Z
ms-utils/math/approximation/QuadLinFit.cpp
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
39
2020-11-20T12:19:35.000Z
2022-02-22T18:45:55.000Z
ms-utils/math/approximation/QuadLinFit.cpp
nasa/gunns
248323939a476abe5178538cd7a3512b5f42675c
[ "NASA-1.3" ]
7
2020-02-10T19:25:43.000Z
2022-03-16T01:10:00.000Z
/************************** TRICK HEADER ********************************************************** LIBRARY DEPENDENCY: ((TsApproximation.o)) ***************************************************************************************************/ #include "QuadLinFit.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Default constructs this Bivariate Quadratic, Linear curve fit model. //////////////////////////////////////////////////////////////////////////////////////////////////// QuadLinFit::QuadLinFit() : TsApproximation(), mA(0.0), mB(0.0), mC(0.0), mD(0.0), mE(0.0), mF(0.0) { // nothing to do } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @param[in] a (--) First coefficient for curve fit model. /// @param[in] b (--) Second coefficient for curve fit model. /// @param[in] c (--) Third coefficient for curve fit model. /// @param[in] d (--) Fourth coefficient for curve fit model. /// @param[in] e (--) Fifth coefficient for curve fit model. /// @param[in] f (--) Sixth coefficient for curve fit model. /// @param[in] minX (--) Curve fit model valid range lower limit for first variable. /// @param[in] maxX (--) Curve fit model valid range upper limit for first variable. /// @param[in] minY (--) Curve fit model valid range lower limit for second variable. /// @param[in] maxY (--) Curve fit model valid range upper limit for second variable. /// @param[in] name (--) name for the instance. /// /// @details Constructs this Bivariate Quadratic, Linear curve fit model taking coefficient and /// range arguments. //////////////////////////////////////////////////////////////////////////////////////////////////// QuadLinFit::QuadLinFit(const double a, const double b, const double c, const double d, const double e, const double f, const double minX, const double maxX, const double minY, const double maxY, const std::string &name) : TsApproximation(), mA(a), mB(b), mC(c), mD(d), mE(e), mF(f) { init(a, b, c, d, e, f,minX, maxX, minY, maxY, name ); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Default destructs this Bivariate Quadratic, Linear curve fit model. //////////////////////////////////////////////////////////////////////////////////////////////////// QuadLinFit::~QuadLinFit() { // nothing to do } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @param[in] a (--) First coefficient for curve fit model. /// @param[in] b (--) Second coefficient for curve fit model. /// @param[in] c (--) Third coefficient for curve fit model. /// @param[in] d (--) Fourth coefficient for curve fit model. /// @param[in] e (--) Fifth coefficient for curve fit model. /// @param[in] f (--) Sixth coefficient for curve fit model. /// @param[in] minX (--) Curve fit model valid range lower limit for first variable. /// @param[in] maxX (--) Curve fit model valid range upper limit for first variable. /// @param[in] minY (--) Curve fit model valid range lower limit for second variable. /// @param[in] maxY (--) Curve fit model valid range upper limit for second variable. /// @param[in] name (--) name for the instance. /// /// @details Initializes this Bivarirate Quadratic, Linear curve fit model taking coefficient, range and /// name arguments //////////////////////////////////////////////////////////////////////////////////////////////////// void QuadLinFit::init(const double a, const double b, const double c, const double d, const double e, const double f, const double minX, const double maxX, const double minY, const double maxY, const std::string &name) { /// - Initialize the parent TsApproximation::init(minX, maxX, minY, maxY, name); /// - Initialize the coefficients. mA = a; mB = b; mC = c; mD = d; mE = e; mF = f; }
44.05102
105
0.465833
nasa
b3d1a40f57df1f5dc51f1a546cf169bcddbfa8b4
2,424
cpp
C++
charNameMap.cpp
kim3-sudo/MarvelCharacters-cslab
828746b6a4fcd09c5467010d282b7dac7c1a3244
[ "Unlicense" ]
null
null
null
charNameMap.cpp
kim3-sudo/MarvelCharacters-cslab
828746b6a4fcd09c5467010d282b7dac7c1a3244
[ "Unlicense" ]
null
null
null
charNameMap.cpp
kim3-sudo/MarvelCharacters-cslab
828746b6a4fcd09c5467010d282b7dac7c1a3244
[ "Unlicense" ]
null
null
null
#include "charNameMap.h" charNameMap::charNameMap(string fileName) { string name; // important name string line; string page_id; string fullName; fstream infile(fileName); // opens fileName for input int position = 1; //getline(infile, line); // ignore 0 header, no char data if(infile.good()) { while(true) { char delim = ','; // wait until we run out of commas getline(infile, page_id, delim); getline(infile, fullName, delim); char characterData[fullName.size() +1]; strcpy(characterData, fullName.c_str()); char delims[] = " ()\""; char * name; name = strtok(characterData, delims); // string token while(name != NULL) { cout << name << endl; nameMap[name].push_back(position); name = strtok(NULL, delims); } getline(infile, line); if(infile.fail()) { break; } position = infile.tellg(); //Get the position of the next line (Get the line number) } infile.close(); // Close the file success = true; // Report that map creation was a success } else { success = false; } } bool charNameMap::nameMapSuccess() { return success; } vector<string> charNameMap::getNameMatches(string name) { vector<string> matchList; string match; // holds matching character strings map<string, vector<int>>::iterator nameiterator; // make iterator nameiterator = nameMap.lower_bound(name); // set iterator to closest match // back up to 2 places or to the beginning of the map. for (int i = 0; i < 2 && (nameiterator != nameMap.begin()); i++) { --nameiterator; } // Get up to 10 closest results for (int i = 0; i < 10 && (nameiterator != nameMap.end()); i++) { match = (*nameiterator).first; // Set match to the name value in the map pointed to by our iterator matchList.push_back(match); // Add match to our matchlist nameiterator++; // Move to the next result } return matchList; //Returns 6 closest names } vector<int> charNameMap::getCharacterIndexes(string confirmedName) { vector<int> profileLocations; // Create int vector to hold profile locations profileLocations = nameMap.at(confirmedName); //Set our new vector to the value of the vector in our map, mapped from the name "confirmedName". return profileLocations; // Return all locations of characters with the name "confirmedName" }
34.628571
145
0.652228
kim3-sudo
b3d1e1203c2696aa0fdfed91592ed93edb51fb92
2,719
cpp
C++
ObjOrientedProgramming/Movie/Movie/Movie.cpp
jhbrian/Learning-Progress
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
[ "MIT" ]
null
null
null
ObjOrientedProgramming/Movie/Movie/Movie.cpp
jhbrian/Learning-Progress
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
[ "MIT" ]
null
null
null
ObjOrientedProgramming/Movie/Movie/Movie.cpp
jhbrian/Learning-Progress
de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb
[ "MIT" ]
null
null
null
//************************************************************************************* //Program Name: Movie //Author: Jin Han Ho //IDE Used: Visual Studio 2019 //Program description: read inputs from input file and output them as 4 sets of object //************************************************************************************* #include <iostream> #include <string> #include <fstream> #include <iomanip> #include <sstream> using namespace std; /*---------------------------- Movie ---------------------------- - screenWriter: string - yearReleased : int - title : string ---------------------------- + getScreenWriter() : string + getYearReleased() : int + getTitle() : string + setScreenWriter(a : string) : void + setYearReleased(y : int) : void + setTitle(t : string) : void ----------------------------*/ class Movie { private: string screenWriter; int yearReleased =0; string title; public: string getScreenWriter(); int getYearReleased(); string getTitle(); void setScreenWriter(string a); void setYearReleased(int y); void setTitle(string t); }; string Movie::getScreenWriter() { return screenWriter; } int Movie::getYearReleased() { return yearReleased; } string Movie::getTitle() { return title; } void Movie::setScreenWriter(string a) { screenWriter = a; } void Movie::setYearReleased(int y) { yearReleased = y; } void Movie::setTitle(string t) { title = t; } int main(){ ifstream fin; string name, writer; int i=0,year = 0; const int SIZE = 4; Movie Arr[SIZE]; fin.open("input.txt"); while (getline(fin, writer)) { fin >> year; fin.ignore(); getline(fin, name); Arr[i].setScreenWriter(writer); Arr[i].setYearReleased(year); Arr[i].setTitle(name); i++; } cout << "This program will create several objects depicting movies." << endl << "Reading input file..." << endl << "...done." << endl; for (int i = 0; i < SIZE; i++) { cout << "Movie: " << Arr[i].getTitle() << endl; cout << setw(10) << " > " << "Year released: " << Arr[i].getYearReleased() << endl; cout << setw(10) << " > " << "Screenwriter: " << Arr[i].getScreenWriter() << endl; } fin.close(); cout << endl; cout << "I attest that this code is my original programming work, and that I received" << endl << "no help creating it. I attest that I did not copy this code or any portion of this" << endl << "code from any source." << endl; return 0; }
26.398058
104
0.513056
jhbrian
b3d512204bea6a02f0da8217f061a8d137bf6f55
43,843
cpp
C++
source/blender/collada/AnimationExporter.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
2
2018-06-18T01:50:25.000Z
2018-06-18T01:50:32.000Z
source/blender/collada/AnimationExporter.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
source/blender/collada/AnimationExporter.cpp
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Contributor(s): Chingiz Dyussenov, Arystanbek Dyussenov, Jan Diederich, Tod Liverseed. * * ***** END GPL LICENSE BLOCK ***** */ #include "GeometryExporter.h" #include "AnimationExporter.h" #include "MaterialExporter.h" template<class Functor> void forEachObjectInExportSet(Scene *sce, Functor &f, LinkNode *export_set) { LinkNode *node; for (node = export_set; node; node = node->next) { Object *ob = (Object *)node->link; f(ob); } } bool AnimationExporter::exportAnimations(Scene *sce) { bool has_animations = hasAnimations(sce); if (has_animations) { this->scene = sce; openLibrary(); forEachObjectInExportSet(sce, *this, this->export_settings->export_set); closeLibrary(); } return has_animations; } // called for each exported object void AnimationExporter::operator()(Object *ob) { FCurve *fcu; char *transformName; /* bool isMatAnim = false; */ /* UNUSED */ //Export transform animations if (ob->adt && ob->adt->action) { fcu = (FCurve *)ob->adt->action->curves.first; //transform matrix export for bones are temporarily disabled here. if (ob->type == OB_ARMATURE) { bArmature *arm = (bArmature *)ob->data; for (Bone *bone = (Bone *)arm->bonebase.first; bone; bone = bone->next) write_bone_animation_matrix(ob, bone); } while (fcu) { //for armature animations as objects if (ob->type == OB_ARMATURE) transformName = fcu->rna_path; else transformName = extract_transform_name(fcu->rna_path); if ((STREQ(transformName, "location") || STREQ(transformName, "scale")) || (STREQ(transformName, "rotation_euler") && ob->rotmode == ROT_MODE_EUL) || (STREQ(transformName, "rotation_quaternion"))) { dae_animation(ob, fcu, transformName, false); } fcu = fcu->next; } } export_object_constraint_animation(ob); //This needs to be handled by extra profiles, so postponed for now //export_morph_animation(ob); //Export Lamp parameter animations if ( (ob->type == OB_LAMP) && ((Lamp *)ob->data)->adt && ((Lamp *)ob->data)->adt->action) { fcu = (FCurve *)(((Lamp *)ob->data)->adt->action->curves.first); while (fcu) { transformName = extract_transform_name(fcu->rna_path); if ((STREQ(transformName, "color")) || (STREQ(transformName, "spot_size")) || (STREQ(transformName, "spot_blend")) || (STREQ(transformName, "distance"))) { dae_animation(ob, fcu, transformName, true); } fcu = fcu->next; } } //Export Camera parameter animations if ( (ob->type == OB_CAMERA) && ((Camera *)ob->data)->adt && ((Camera *)ob->data)->adt->action) { fcu = (FCurve *)(((Camera *)ob->data)->adt->action->curves.first); while (fcu) { transformName = extract_transform_name(fcu->rna_path); if ((STREQ(transformName, "lens")) || (STREQ(transformName, "ortho_scale")) || (STREQ(transformName, "clip_end")) || (STREQ(transformName, "clip_start"))) { dae_animation(ob, fcu, transformName, true); } fcu = fcu->next; } } //Export Material parameter animations. for (int a = 0; a < ob->totcol; a++) { Material *ma = give_current_material(ob, a + 1); if (!ma) continue; if (ma->adt && ma->adt->action) { /* isMatAnim = true; */ fcu = (FCurve *)ma->adt->action->curves.first; while (fcu) { transformName = extract_transform_name(fcu->rna_path); if ((STREQ(transformName, "specular_hardness")) || (STREQ(transformName, "specular_color")) || (STREQ(transformName, "diffuse_color")) || (STREQ(transformName, "alpha")) || (STREQ(transformName, "ior"))) { dae_animation(ob, fcu, transformName, true, ma); } fcu = fcu->next; } } } } void AnimationExporter::export_object_constraint_animation(Object *ob) { std::vector<float> fra; //Takes frames of target animations make_anim_frames_from_targets(ob, fra); if (fra.size()) dae_baked_object_animation(fra, ob); } void AnimationExporter::export_morph_animation(Object *ob) { FCurve *fcu; char *transformName; Key *key = BKE_key_from_object(ob); if (!key) return; if (key->adt && key->adt->action) { fcu = (FCurve *)key->adt->action->curves.first; while (fcu) { transformName = extract_transform_name(fcu->rna_path); dae_animation(ob, fcu, transformName, true); fcu = fcu->next; } } } void AnimationExporter::make_anim_frames_from_targets(Object *ob, std::vector<float> &frames ) { ListBase *conlist = get_active_constraints(ob); if (conlist == NULL) return; bConstraint *con; for (con = (bConstraint *)conlist->first; con; con = con->next) { ListBase targets = {NULL, NULL}; const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); if (!validateConstraints(con)) continue; if (cti && cti->get_constraint_targets) { bConstraintTarget *ct; Object *obtar; /* get targets * - constraints should use ct->matrix, not directly accessing values * - ct->matrix members have not yet been calculated here! */ cti->get_constraint_targets(con, &targets); for (ct = (bConstraintTarget *)targets.first; ct; ct = ct->next) { obtar = ct->tar; if (obtar) find_frames(obtar, frames); } if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); } } } //euler sources from quternion sources float *AnimationExporter::get_eul_source_for_quat(Object *ob) { FCurve *fcu = (FCurve *)ob->adt->action->curves.first; const int keys = fcu->totvert; float *quat = (float *)MEM_callocN(sizeof(float) * fcu->totvert * 4, "quat output source values"); float *eul = (float *)MEM_callocN(sizeof(float) * fcu->totvert * 3, "quat output source values"); float temp_quat[4]; float temp_eul[3]; while (fcu) { char *transformName = extract_transform_name(fcu->rna_path); if (STREQ(transformName, "rotation_quaternion") ) { for (int i = 0; i < fcu->totvert; i++) { *(quat + (i * 4) + fcu->array_index) = fcu->bezt[i].vec[1][1]; } } fcu = fcu->next; } for (int i = 0; i < keys; i++) { for (int j = 0; j < 4; j++) temp_quat[j] = quat[(i * 4) + j]; quat_to_eul(temp_eul, temp_quat); for (int k = 0; k < 3; k++) eul[i * 3 + k] = temp_eul[k]; } MEM_freeN(quat); return eul; } //Get proper name for bones std::string AnimationExporter::getObjectBoneName(Object *ob, const FCurve *fcu) { //hard-way to derive the bone name from rna_path. Must find more compact method std::string rna_path = std::string(fcu->rna_path); char *boneName = strtok((char *)rna_path.c_str(), "\""); boneName = strtok(NULL, "\""); if (boneName != NULL) return /*id_name(ob) + "_" +*/ std::string(boneName); else return id_name(ob); } std::string AnimationExporter::getAnimationPathId(const FCurve *fcu) { std::string rna_path = std::string(fcu->rna_path); return translate_id(rna_path); } //convert f-curves to animation curves and write void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformName, bool is_param, Material *ma) { const char *axis_name = NULL; char anim_id[200]; bool has_tangents = false; bool quatRotation = false; if (STREQ(transformName, "rotation_quaternion") ) { fprintf(stderr, "quaternion rotation curves are not supported. rotation curve will not be exported\n"); quatRotation = true; return; } //axis names for colors else if (STREQ(transformName, "color") || STREQ(transformName, "specular_color") || STREQ(transformName, "diffuse_color") || STREQ(transformName, "alpha")) { const char *axis_names[] = {"R", "G", "B"}; if (fcu->array_index < 3) axis_name = axis_names[fcu->array_index]; } //axis names for transforms else if (STREQ(transformName, "location") || STREQ(transformName, "scale") || STREQ(transformName, "rotation_euler") || STREQ(transformName, "rotation_quaternion")) { const char *axis_names[] = {"X", "Y", "Z"}; if (fcu->array_index < 3) axis_name = axis_names[fcu->array_index]; } else { /* no axis name. single parameter */ axis_name = ""; } std::string ob_name = std::string("null"); //Create anim Id if (ob->type == OB_ARMATURE) { ob_name = getObjectBoneName(ob, fcu); BLI_snprintf( anim_id, sizeof(anim_id), "%s_%s.%s", (char *)translate_id(ob_name).c_str(), (char *)translate_id(transformName).c_str(), axis_name); } else { if (ma) ob_name = id_name(ob) + "_material"; else ob_name = id_name(ob); BLI_snprintf( anim_id, sizeof(anim_id), "%s_%s_%s", (char *)translate_id(ob_name).c_str(), (char *)getAnimationPathId(fcu).c_str(), axis_name); } openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING); // create input source std::string input_id = create_source_from_fcurve(COLLADASW::InputSemantic::INPUT, fcu, anim_id, axis_name); // create output source std::string output_id; //quat rotations are skipped for now, because of complications with determining axis. if (quatRotation) { float *eul = get_eul_source_for_quat(ob); float *eul_axis = (float *)MEM_callocN(sizeof(float) * fcu->totvert, "quat output source values"); for (int i = 0; i < fcu->totvert; i++) { eul_axis[i] = eul[i * 3 + fcu->array_index]; } output_id = create_source_from_array(COLLADASW::InputSemantic::OUTPUT, eul_axis, fcu->totvert, quatRotation, anim_id, axis_name); MEM_freeN(eul); MEM_freeN(eul_axis); } else if (STREQ(transformName, "lens") && (ob->type == OB_CAMERA)) { output_id = create_lens_source_from_fcurve((Camera *) ob->data, COLLADASW::InputSemantic::OUTPUT, fcu, anim_id); } else { output_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUTPUT, fcu, anim_id, axis_name); } // create interpolations source std::string interpolation_id = create_interpolation_source(fcu, anim_id, axis_name, &has_tangents); // handle tangents (if required) std::string intangent_id; std::string outtangent_id; if (has_tangents) { // create in_tangent source intangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::IN_TANGENT, fcu, anim_id, axis_name); // create out_tangent source outtangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUT_TANGENT, fcu, anim_id, axis_name); } std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX; COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id); std::string empty; sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id)); sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id)); // this input is required sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id)); if (has_tangents) { sampler.addInput(COLLADASW::InputSemantic::IN_TANGENT, COLLADABU::URI(empty, intangent_id)); sampler.addInput(COLLADASW::InputSemantic::OUT_TANGENT, COLLADABU::URI(empty, outtangent_id)); } addSampler(sampler); std::string target; if (!is_param) target = translate_id(ob_name) + "/" + get_transform_sid(fcu->rna_path, -1, axis_name, true); else { if (ob->type == OB_LAMP) target = get_light_id(ob) + "/" + get_light_param_sid(fcu->rna_path, -1, axis_name, true); if (ob->type == OB_CAMERA) target = get_camera_id(ob) + "/" + get_camera_param_sid(fcu->rna_path, -1, axis_name, true); if (ma) target = translate_id(id_name(ma)) + "-effect" + "/common/" /*profile common is only supported */ + get_transform_sid(fcu->rna_path, -1, axis_name, true); //if shape key animation, this is the main problem, how to define the channel targets. /*target = get_morph_id(ob) + "/value" +*/ } addChannel(COLLADABU::URI(empty, sampler_id), target); closeAnimation(); } //write bone animations in transform matrix sources void AnimationExporter::write_bone_animation_matrix(Object *ob_arm, Bone *bone) { if (!ob_arm->adt) return; //This will only export animations of bones in deform group. /* if (!is_bone_deform_group(bone)) return; */ sample_and_write_bone_animation_matrix(ob_arm, bone); for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) write_bone_animation_matrix(ob_arm, child); } bool AnimationExporter::is_bone_deform_group(Bone *bone) { bool is_def; //Check if current bone is deform if ((bone->flag & BONE_NO_DEFORM) == 0) return true; //Check child bones else { for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) { //loop through all the children until deform bone is found, and then return is_def = is_bone_deform_group(child); if (is_def) return true; } } //no deform bone found in children also return false; } void AnimationExporter::sample_and_write_bone_animation_matrix(Object *ob_arm, Bone *bone) { bArmature *arm = (bArmature *)ob_arm->data; int flag = arm->flag; std::vector<float> fra; //char prefix[256]; //Check if there is a fcurve in the armature for the bone in param //when baking this check is not needed, solve every bone for every frame. /*FCurve *fcu = (FCurve *)ob_arm->adt->action->curves.first; while (fcu) { std::string bone_name = getObjectBoneName(ob_arm, fcu); int val = BLI_strcasecmp((char *)bone_name.c_str(), bone->name); if (val == 0) break; fcu = fcu->next; } if (!(fcu)) return;*/ bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, bone->name); if (!pchan) return; //every inserted keyframe of bones. find_frames(ob_arm, fra); if (flag & ARM_RESTPOS) { arm->flag &= ~ARM_RESTPOS; BKE_pose_where_is(scene, ob_arm); } if (fra.size()) { dae_baked_animation(fra, ob_arm, bone); } if (flag & ARM_RESTPOS) arm->flag = flag; BKE_pose_where_is(scene, ob_arm); } void AnimationExporter::dae_baked_animation(std::vector<float> &fra, Object *ob_arm, Bone *bone) { std::string ob_name = id_name(ob_arm); std::string bone_name = bone->name; char anim_id[200]; if (!fra.size()) return; BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char *)translate_id(ob_name).c_str(), (char *)translate_id(bone_name).c_str(), "pose_matrix"); openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING); // create input source std::string input_id = create_source_from_vector(COLLADASW::InputSemantic::INPUT, fra, false, anim_id, ""); // create output source std::string output_id; output_id = create_4x4_source(fra, ob_arm, bone, anim_id); // create interpolations source std::string interpolation_id = fake_interpolation_source(fra.size(), anim_id, ""); std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX; COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id); std::string empty; sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id)); sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id)); // TODO create in/out tangents source // this input is required sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id)); addSampler(sampler); std::string target = get_joint_id(bone, ob_arm) + "/transform"; addChannel(COLLADABU::URI(empty, sampler_id), target); closeAnimation(); } void AnimationExporter::dae_baked_object_animation(std::vector<float> &fra, Object *ob) { std::string ob_name = id_name(ob); char anim_id[200]; if (!fra.size()) return; BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s", (char *)translate_id(ob_name).c_str(), "object_matrix"); openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING); // create input source std::string input_id = create_source_from_vector(COLLADASW::InputSemantic::INPUT, fra, false, anim_id, ""); // create output source std::string output_id; output_id = create_4x4_source( fra, ob, NULL, anim_id); // create interpolations source std::string interpolation_id = fake_interpolation_source(fra.size(), anim_id, ""); std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX; COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id); std::string empty; sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id)); sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id)); // TODO create in/out tangents source // this input is required sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id)); addSampler(sampler); std::string target = translate_id(ob_name) + "/transform"; addChannel(COLLADABU::URI(empty, sampler_id), target); closeAnimation(); } // dae_bone_animation -> add_bone_animation // (blend this into dae_bone_animation) void AnimationExporter::dae_bone_animation(std::vector<float> &fra, float *values, int tm_type, int axis, std::string ob_name, std::string bone_name) { const char *axis_names[] = {"X", "Y", "Z"}; const char *axis_name = NULL; char anim_id[200]; bool is_rot = tm_type == 0; if (!fra.size()) return; char rna_path[200]; BLI_snprintf(rna_path, sizeof(rna_path), "pose.bones[\"%s\"].%s", bone_name.c_str(), tm_type == 0 ? "rotation_quaternion" : (tm_type == 1 ? "scale" : "location")); if (axis > -1) axis_name = axis_names[axis]; std::string transform_sid = get_transform_sid(NULL, tm_type, axis_name, false); BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char *)translate_id(ob_name).c_str(), (char *)translate_id(bone_name).c_str(), (char *)transform_sid.c_str()); openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING); // create input source std::string input_id = create_source_from_vector(COLLADASW::InputSemantic::INPUT, fra, is_rot, anim_id, axis_name); // create output source std::string output_id; if (axis == -1) output_id = create_xyz_source(values, fra.size(), anim_id); else output_id = create_source_from_array(COLLADASW::InputSemantic::OUTPUT, values, fra.size(), is_rot, anim_id, axis_name); // create interpolations source std::string interpolation_id = fake_interpolation_source(fra.size(), anim_id, axis_name); std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX; COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id); std::string empty; sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id)); sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id)); // TODO create in/out tangents source // this input is required sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id)); addSampler(sampler); std::string target = translate_id(ob_name + "_" + bone_name) + "/" + transform_sid; addChannel(COLLADABU::URI(empty, sampler_id), target); closeAnimation(); } float AnimationExporter::convert_time(float frame) { return FRA2TIME(frame); } float AnimationExporter::convert_angle(float angle) { return COLLADABU::Math::Utils::radToDegF(angle); } std::string AnimationExporter::get_semantic_suffix(COLLADASW::InputSemantic::Semantics semantic) { switch (semantic) { case COLLADASW::InputSemantic::INPUT: return INPUT_SOURCE_ID_SUFFIX; case COLLADASW::InputSemantic::OUTPUT: return OUTPUT_SOURCE_ID_SUFFIX; case COLLADASW::InputSemantic::INTERPOLATION: return INTERPOLATION_SOURCE_ID_SUFFIX; case COLLADASW::InputSemantic::IN_TANGENT: return INTANGENT_SOURCE_ID_SUFFIX; case COLLADASW::InputSemantic::OUT_TANGENT: return OUTTANGENT_SOURCE_ID_SUFFIX; default: break; } return ""; } void AnimationExporter::add_source_parameters(COLLADASW::SourceBase::ParameterNameList& param, COLLADASW::InputSemantic::Semantics semantic, bool is_rot, const char *axis, bool transform) { switch (semantic) { case COLLADASW::InputSemantic::INPUT: param.push_back("TIME"); break; case COLLADASW::InputSemantic::OUTPUT: if (is_rot) { param.push_back("ANGLE"); } else { if (axis) { param.push_back(axis); } else if (transform) { param.push_back("TRANSFORM"); } else { //assumes if axis isn't specified all axises are added param.push_back("X"); param.push_back("Y"); param.push_back("Z"); } } break; case COLLADASW::InputSemantic::IN_TANGENT: case COLLADASW::InputSemantic::OUT_TANGENT: param.push_back("X"); param.push_back("Y"); break; default: break; } } void AnimationExporter::get_source_values(BezTriple *bezt, COLLADASW::InputSemantic::Semantics semantic, bool is_angle, float *values, int *length) { switch (semantic) { case COLLADASW::InputSemantic::INPUT: *length = 1; values[0] = convert_time(bezt->vec[1][0]); break; case COLLADASW::InputSemantic::OUTPUT: *length = 1; if (is_angle) { values[0] = RAD2DEGF(bezt->vec[1][1]); } else { values[0] = bezt->vec[1][1]; } break; case COLLADASW::InputSemantic::IN_TANGENT: *length = 2; values[0] = convert_time(bezt->vec[0][0]); if (bezt->ipo != BEZT_IPO_BEZ) { // We're in a mixed interpolation scenario, set zero as it's irrelevant but value might contain unused data values[0] = 0; values[1] = 0; } else if (is_angle) { values[1] = RAD2DEGF(bezt->vec[0][1]); } else { values[1] = bezt->vec[0][1]; } break; case COLLADASW::InputSemantic::OUT_TANGENT: *length = 2; values[0] = convert_time(bezt->vec[2][0]); if (bezt->ipo != BEZT_IPO_BEZ) { // We're in a mixed interpolation scenario, set zero as it's irrelevant but value might contain unused data values[0] = 0; values[1] = 0; } else if (is_angle) { values[1] = RAD2DEGF(bezt->vec[2][1]); } else { values[1] = bezt->vec[2][1]; } break; default: *length = 0; break; } } std::string AnimationExporter::create_source_from_fcurve(COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name) { std::string source_id = anim_id + get_semantic_suffix(semantic); //bool is_angle = STREQ(fcu->rna_path, "rotation"); bool is_angle = false; if (strstr(fcu->rna_path, "rotation") || strstr(fcu->rna_path,"spot_size")) is_angle = true; COLLADASW::FloatSourceF source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(fcu->totvert); switch (semantic) { case COLLADASW::InputSemantic::INPUT: case COLLADASW::InputSemantic::OUTPUT: source.setAccessorStride(1); break; case COLLADASW::InputSemantic::IN_TANGENT: case COLLADASW::InputSemantic::OUT_TANGENT: source.setAccessorStride(2); break; default: break; } COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); add_source_parameters(param, semantic, is_angle, axis_name, false); source.prepareToAppendValues(); for (unsigned int i = 0; i < fcu->totvert; i++) { float values[3]; // be careful! int length = 0; get_source_values(&fcu->bezt[i], semantic, is_angle, values, &length); for (int j = 0; j < length; j++) source.appendValues(values[j]); } source.finish(); return source_id; } /* * Similar to create_source_from_fcurve, but adds conversion of lens * animation data from focal length to FOV. */ std::string AnimationExporter::create_lens_source_from_fcurve(Camera *cam, COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id) { std::string source_id = anim_id + get_semantic_suffix(semantic); COLLADASW::FloatSourceF source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(fcu->totvert); source.setAccessorStride(1); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); add_source_parameters(param, semantic, false, "", false); source.prepareToAppendValues(); for (unsigned int i = 0; i < fcu->totvert; i++) { float values[3]; // be careful! int length = 0; get_source_values(&fcu->bezt[i], semantic, false, values, &length); for (int j = 0; j < length; j++) { float val = RAD2DEGF(focallength_to_fov(values[j], cam->sensor_x)); source.appendValues(val); } } source.finish(); return source_id; } //Currently called only to get OUTPUT source values ( if rotation and hence the axis is also specified ) std::string AnimationExporter::create_source_from_array(COLLADASW::InputSemantic::Semantics semantic, float *v, int tot, bool is_rot, const std::string& anim_id, const char *axis_name) { std::string source_id = anim_id + get_semantic_suffix(semantic); COLLADASW::FloatSourceF source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(tot); source.setAccessorStride(1); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); add_source_parameters(param, semantic, is_rot, axis_name, false); source.prepareToAppendValues(); for (int i = 0; i < tot; i++) { float val = v[i]; ////if (semantic == COLLADASW::InputSemantic::INPUT) // val = convert_time(val); //else if (is_rot) val = RAD2DEGF(val); source.appendValues(val); } source.finish(); return source_id; } // only used for sources with INPUT semantic std::string AnimationExporter::create_source_from_vector(COLLADASW::InputSemantic::Semantics semantic, std::vector<float> &fra, bool is_rot, const std::string& anim_id, const char *axis_name) { std::string source_id = anim_id + get_semantic_suffix(semantic); COLLADASW::FloatSourceF source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(fra.size()); source.setAccessorStride(1); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); add_source_parameters(param, semantic, is_rot, axis_name, false); source.prepareToAppendValues(); std::vector<float>::iterator it; for (it = fra.begin(); it != fra.end(); it++) { float val = *it; //if (semantic == COLLADASW::InputSemantic::INPUT) val = convert_time(val); /*else if (is_rot) val = convert_angle(val);*/ source.appendValues(val); } source.finish(); return source_id; } std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Object *ob, Bone *bone, const std::string &anim_id) { COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT; std::string source_id = anim_id + get_semantic_suffix(semantic); COLLADASW::Float4x4Source source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(frames.size()); source.setAccessorStride(16); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); add_source_parameters(param, semantic, false, NULL, true); source.prepareToAppendValues(); bPoseChannel *parchan = NULL; bPoseChannel *pchan = NULL; if (ob->type == OB_ARMATURE && bone) { bPose *pose = ob->pose; pchan = BKE_pose_channel_find_name(pose, bone->name); if (!pchan) return ""; parchan = pchan->parent; enable_fcurves(ob->adt->action, bone->name); } std::vector<float>::iterator it; int j = 0; for (it = frames.begin(); it != frames.end(); it++) { float mat[4][4], ipar[4][4]; float ctime = BKE_scene_frame_get_from_ctime(scene, *it); CFRA = BKE_scene_frame_get_from_ctime(scene, *it); //BKE_scene_update_for_newframe(G.main->eval_ctx, G.main,scene,scene->lay); BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_ALL); if (bone) { if (pchan->flag & POSE_CHAIN) { enable_fcurves(ob->adt->action, NULL); BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_ALL); BKE_pose_where_is(scene, ob); } else { BKE_pose_where_is_bone(scene, ob, pchan, ctime, 1); } // compute bone local mat if (bone->parent) { invert_m4_m4(ipar, parchan->pose_mat); mul_m4_m4m4(mat, ipar, pchan->pose_mat); } else copy_m4_m4(mat, pchan->pose_mat); // OPEN_SIM_COMPATIBILITY // AFAIK animation to second life is via BVH, but no // reason to not have the collada-animation be correct if (export_settings->open_sim) { float temp[4][4]; copy_m4_m4(temp, bone->arm_mat); temp[3][0] = temp[3][1] = temp[3][2] = 0.0f; invert_m4(temp); mul_m4_m4m4(mat, mat, temp); if (bone->parent) { copy_m4_m4(temp, bone->parent->arm_mat); temp[3][0] = temp[3][1] = temp[3][2] = 0.0f; mul_m4_m4m4(mat, temp, mat); } } } else { calc_ob_mat_at_time(ob, ctime, mat); } UnitConverter converter; double outmat[4][4]; converter.mat4_to_dae_double(outmat, mat); source.appendValues(outmat); j++; BIK_release_tree(scene, ob, ctime); } if (ob->adt) { enable_fcurves(ob->adt->action, NULL); } source.finish(); return source_id; } // only used for sources with OUTPUT semantic ( locations and scale) std::string AnimationExporter::create_xyz_source(float *v, int tot, const std::string& anim_id) { COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT; std::string source_id = anim_id + get_semantic_suffix(semantic); COLLADASW::FloatSourceF source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(tot); source.setAccessorStride(3); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); add_source_parameters(param, semantic, false, NULL, false); source.prepareToAppendValues(); for (int i = 0; i < tot; i++) { source.appendValues(*v, *(v + 1), *(v + 2)); v += 3; } source.finish(); return source_id; } std::string AnimationExporter::create_interpolation_source(FCurve *fcu, const std::string& anim_id, const char *axis_name, bool *has_tangents) { std::string source_id = anim_id + get_semantic_suffix(COLLADASW::InputSemantic::INTERPOLATION); COLLADASW::NameSource source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(fcu->totvert); source.setAccessorStride(1); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); param.push_back("INTERPOLATION"); source.prepareToAppendValues(); *has_tangents = false; for (unsigned int i = 0; i < fcu->totvert; i++) { if (fcu->bezt[i].ipo == BEZT_IPO_BEZ) { source.appendValues(BEZIER_NAME); *has_tangents = true; } else if (fcu->bezt[i].ipo == BEZT_IPO_CONST) { source.appendValues(STEP_NAME); } else { // BEZT_IPO_LIN source.appendValues(LINEAR_NAME); } } // unsupported? -- HERMITE, CARDINAL, BSPLINE, NURBS source.finish(); return source_id; } std::string AnimationExporter::fake_interpolation_source(int tot, const std::string& anim_id, const char *axis_name) { std::string source_id = anim_id + get_semantic_suffix(COLLADASW::InputSemantic::INTERPOLATION); COLLADASW::NameSource source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(tot); source.setAccessorStride(1); COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList(); param.push_back("INTERPOLATION"); source.prepareToAppendValues(); for (int i = 0; i < tot; i++) { source.appendValues(LINEAR_NAME); } source.finish(); return source_id; } std::string AnimationExporter::get_light_param_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis) { std::string tm_name; // when given rna_path, determine tm_type from it if (rna_path) { char *name = extract_transform_name(rna_path); if (STREQ(name, "color")) tm_type = 1; else if (STREQ(name, "spot_size")) tm_type = 2; else if (STREQ(name, "spot_blend")) tm_type = 3; else if (STREQ(name, "distance")) tm_type = 4; else tm_type = -1; } switch (tm_type) { case 1: tm_name = "color"; break; case 2: tm_name = "fall_off_angle"; break; case 3: tm_name = "fall_off_exponent"; break; case 4: tm_name = "blender/blender_dist"; break; default: tm_name = ""; break; } if (tm_name.size()) { if (axis_name[0]) return tm_name + "." + std::string(axis_name); else return tm_name; } return std::string(""); } std::string AnimationExporter::get_camera_param_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis) { std::string tm_name; // when given rna_path, determine tm_type from it if (rna_path) { char *name = extract_transform_name(rna_path); if (STREQ(name, "lens")) tm_type = 0; else if (STREQ(name, "ortho_scale")) tm_type = 1; else if (STREQ(name, "clip_end")) tm_type = 2; else if (STREQ(name, "clip_start")) tm_type = 3; else tm_type = -1; } switch (tm_type) { case 0: tm_name = "xfov"; break; case 1: tm_name = "xmag"; break; case 2: tm_name = "zfar"; break; case 3: tm_name = "znear"; break; default: tm_name = ""; break; } if (tm_name.size()) { if (axis_name[0]) return tm_name + "." + std::string(axis_name); else return tm_name; } return std::string(""); } // Assign sid of the animated parameter or transform // for rotation, axis name is always appended and the value of append_axis is ignored std::string AnimationExporter::get_transform_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis) { std::string tm_name; bool is_angle = false; // when given rna_path, determine tm_type from it if (rna_path) { char *name = extract_transform_name(rna_path); if (STREQ(name, "rotation_euler")) tm_type = 0; else if (STREQ(name, "rotation_quaternion")) tm_type = 1; else if (STREQ(name, "scale")) tm_type = 2; else if (STREQ(name, "location")) tm_type = 3; else if (STREQ(name, "specular_hardness")) tm_type = 4; else if (STREQ(name, "specular_color")) tm_type = 5; else if (STREQ(name, "diffuse_color")) tm_type = 6; else if (STREQ(name, "alpha")) tm_type = 7; else if (STREQ(name, "ior")) tm_type = 8; else tm_type = -1; } switch (tm_type) { case 0: case 1: tm_name = "rotation"; is_angle = true; break; case 2: tm_name = "scale"; break; case 3: tm_name = "location"; break; case 4: tm_name = "shininess"; break; case 5: tm_name = "specular"; break; case 6: tm_name = "diffuse"; break; case 7: tm_name = "transparency"; break; case 8: tm_name = "index_of_refraction"; break; default: tm_name = ""; break; } if (tm_name.size()) { if (is_angle) return tm_name + std::string(axis_name) + ".ANGLE"; else if (axis_name[0]) return tm_name + "." + std::string(axis_name); else return tm_name; } return std::string(""); } char *AnimationExporter::extract_transform_name(char *rna_path) { char *dot = strrchr(rna_path, '.'); return dot ? (dot + 1) : rna_path; } //find keyframes of all the objects animations void AnimationExporter::find_frames(Object *ob, std::vector<float> &fra) { if (ob->adt && ob->adt->action) { FCurve *fcu = (FCurve *)ob->adt->action->curves.first; for (; fcu; fcu = fcu->next) { for (unsigned int i = 0; i < fcu->totvert; i++) { float f = fcu->bezt[i].vec[1][0]; if (std::find(fra.begin(), fra.end(), f) == fra.end()) fra.push_back(f); } } // keep the keys in ascending order std::sort(fra.begin(), fra.end()); } } // enable fcurves driving a specific bone, disable all the rest // if bone_name = NULL enable all fcurves void AnimationExporter::enable_fcurves(bAction *act, char *bone_name) { FCurve *fcu; char prefix[200]; if (bone_name) BLI_snprintf(prefix, sizeof(prefix), "pose.bones[\"%s\"]", bone_name); for (fcu = (FCurve *)act->curves.first; fcu; fcu = fcu->next) { if (bone_name) { if (STREQLEN(fcu->rna_path, prefix, strlen(prefix))) fcu->flag &= ~FCURVE_DISABLED; else fcu->flag |= FCURVE_DISABLED; } else { fcu->flag &= ~FCURVE_DISABLED; } } } bool AnimationExporter::hasAnimations(Scene *sce) { LinkNode *node; for (node=this->export_settings->export_set; node; node=node->next) { Object *ob = (Object *)node->link; FCurve *fcu = 0; //Check for object transform animations if (ob->adt && ob->adt->action) fcu = (FCurve *)ob->adt->action->curves.first; //Check for Lamp parameter animations else if ( (ob->type == OB_LAMP) && ((Lamp *)ob->data)->adt && ((Lamp *)ob->data)->adt->action) fcu = (FCurve *)(((Lamp *)ob->data)->adt->action->curves.first); //Check for Camera parameter animations else if ( (ob->type == OB_CAMERA) && ((Camera *)ob->data)->adt && ((Camera *)ob->data)->adt->action) fcu = (FCurve *)(((Camera *)ob->data)->adt->action->curves.first); //Check Material Effect parameter animations. for (int a = 0; a < ob->totcol; a++) { Material *ma = give_current_material(ob, a + 1); if (!ma) continue; if (ma->adt && ma->adt->action) { fcu = (FCurve *)ma->adt->action->curves.first; } } //check shape key animation if (!fcu) { Key *key = BKE_key_from_object(ob); if (key && key->adt && key->adt->action) fcu = (FCurve *)key->adt->action->curves.first; } if (fcu) return true; } return false; } //------------------------------- Not used in the new system.-------------------------------------------------------- void AnimationExporter::find_rotation_frames(Object *ob, std::vector<float> &fra, const char *prefix, int rotmode) { if (rotmode > 0) find_frames(ob, fra, prefix, "rotation_euler"); else if (rotmode == ROT_MODE_QUAT) find_frames(ob, fra, prefix, "rotation_quaternion"); /*else if (rotmode == ROT_MODE_AXISANGLE) ;*/ } void AnimationExporter::find_frames(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name) { if (ob->adt && ob->adt->action) { FCurve *fcu = (FCurve *)ob->adt->action->curves.first; for (; fcu; fcu = fcu->next) { if (prefix && !STREQLEN(prefix, fcu->rna_path, strlen(prefix))) continue; char *name = extract_transform_name(fcu->rna_path); if (STREQ(name, tm_name)) { for (unsigned int i = 0; i < fcu->totvert; i++) { float f = fcu->bezt[i].vec[1][0]; if (std::find(fra.begin(), fra.end(), f) == fra.end()) fra.push_back(f); } } } // keep the keys in ascending order std::sort(fra.begin(), fra.end()); } } void AnimationExporter::write_bone_animation(Object *ob_arm, Bone *bone) { if (!ob_arm->adt) return; //write bone animations for 3 transform types //i=0 --> rotations //i=1 --> scale //i=2 --> location for (int i = 0; i < 3; i++) sample_and_write_bone_animation(ob_arm, bone, i); for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) write_bone_animation(ob_arm, child); } void AnimationExporter::sample_and_write_bone_animation(Object *ob_arm, Bone *bone, int transform_type) { bArmature *arm = (bArmature *)ob_arm->data; int flag = arm->flag; std::vector<float> fra; char prefix[256]; BLI_snprintf(prefix, sizeof(prefix), "pose.bones[\"%s\"]", bone->name); bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, bone->name); if (!pchan) return; //Fill frame array with key frame values framed at \param:transform_type switch (transform_type) { case 0: find_rotation_frames(ob_arm, fra, prefix, pchan->rotmode); break; case 1: find_frames(ob_arm, fra, prefix, "scale"); break; case 2: find_frames(ob_arm, fra, prefix, "location"); break; default: return; } // exit rest position if (flag & ARM_RESTPOS) { arm->flag &= ~ARM_RESTPOS; BKE_pose_where_is(scene, ob_arm); } //v array will hold all values which will be exported. if (fra.size()) { float *values = (float *)MEM_callocN(sizeof(float) * 3 * fra.size(), "temp. anim frames"); sample_animation(values, fra, transform_type, bone, ob_arm, pchan); if (transform_type == 0) { // write x, y, z curves separately if it is rotation float *axisValues = (float *)MEM_callocN(sizeof(float) * fra.size(), "temp. anim frames"); for (int i = 0; i < 3; i++) { for (unsigned int j = 0; j < fra.size(); j++) axisValues[j] = values[j * 3 + i]; dae_bone_animation(fra, axisValues, transform_type, i, id_name(ob_arm), bone->name); } MEM_freeN(axisValues); } else { // write xyz at once if it is location or scale dae_bone_animation(fra, values, transform_type, -1, id_name(ob_arm), bone->name); } MEM_freeN(values); } // restore restpos if (flag & ARM_RESTPOS) arm->flag = flag; BKE_pose_where_is(scene, ob_arm); } void AnimationExporter::sample_animation(float *v, std::vector<float> &frames, int type, Bone *bone, Object *ob_arm, bPoseChannel *pchan) { bPoseChannel *parchan = NULL; bPose *pose = ob_arm->pose; pchan = BKE_pose_channel_find_name(pose, bone->name); if (!pchan) return; parchan = pchan->parent; enable_fcurves(ob_arm->adt->action, bone->name); std::vector<float>::iterator it; for (it = frames.begin(); it != frames.end(); it++) { float mat[4][4], ipar[4][4]; float ctime = BKE_scene_frame_get_from_ctime(scene, *it); BKE_animsys_evaluate_animdata(scene, &ob_arm->id, ob_arm->adt, ctime, ADT_RECALC_ANIM); BKE_pose_where_is_bone(scene, ob_arm, pchan, ctime, 1); // compute bone local mat if (bone->parent) { invert_m4_m4(ipar, parchan->pose_mat); mul_m4_m4m4(mat, ipar, pchan->pose_mat); } else copy_m4_m4(mat, pchan->pose_mat); switch (type) { case 0: mat4_to_eul(v, mat); break; case 1: mat4_to_size(v, mat); break; case 2: copy_v3_v3(v, mat[3]); break; } v += 3; } enable_fcurves(ob_arm->adt->action, NULL); } bool AnimationExporter::validateConstraints(bConstraint *con) { bool valid = true; const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); /* these we can skip completely (invalid constraints...) */ if (cti == NULL) valid = false; if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) valid = false; /* these constraints can't be evaluated anyway */ if (cti->evaluate_constraint == NULL) valid = false; /* influence == 0 should be ignored */ if (con->enforce == 0.0f) valid = false; return valid; } void AnimationExporter::calc_ob_mat_at_time(Object *ob, float ctime , float mat[][4]) { ListBase *conlist = get_active_constraints(ob); bConstraint *con; for (con = (bConstraint *)conlist->first; con; con = con->next) { ListBase targets = {NULL, NULL}; const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); if (cti && cti->get_constraint_targets) { bConstraintTarget *ct; Object *obtar; cti->get_constraint_targets(con, &targets); for (ct = (bConstraintTarget *)targets.first; ct; ct = ct->next) { obtar = ct->tar; if (obtar) { BKE_animsys_evaluate_animdata(scene, &obtar->id, obtar->adt, ctime, ADT_RECALC_ANIM); BKE_object_where_is_calc_time(scene, obtar, ctime); } } if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); } } BKE_object_where_is_calc_time(scene, ob, ctime); copy_m4_m4(mat, ob->obmat); }
27.943276
191
0.685149
1-MillionParanoidTterabytes
b3d743aa9520ca333b45e102bcb2087b68b4c0fe
4,334
cpp
C++
oneEngine/oneGame/source/renderer/object/shapes/RrShapePlane.cpp
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/renderer/object/shapes/RrShapePlane.cpp
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/renderer/object/shapes/RrShapePlane.cpp
skarik/1Engine
84e846544b4a89af8fd7e9236131363096538ef4
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
#include "RrShapePlane.h" #include "gpuw/Device.h" #include "gpuw/GraphicsContext.h" #include "renderer/material/Material.h" rrMeshBuffer RrShapePlane::m_MeshBuffer; void RrShapePlane::BuildMeshBuffer ( void ) { if (m_MeshBuffer.m_mesh_uploaded == false) { const Real hxsize = 0.5F; const Real hysize = 0.5F; arModelData model; model.position = new Vector3f [4]; model.normal = new Vector3f [4]; model.tangent = new Vector3f [4]; model.color = new Vector4f [4]; model.texcoord0 = new Vector3f [4]; model.vertexNum = 4; model.indices = new uint16_t [6]; model.indexNum = 6; // set commons for ( uint i = 0; i < 4; i += 1 ) { model.normal[i] = Vector3f(0, 0, 1.0F); model.color[i] = Vector4f(1.0F, 1.0F, 1.0F, 1.0F); model.tangent[i] = Vector3f(1.0F, 0, 0); } // Set UVs: model.texcoord0[0] = Vector2f(0, 0); model.texcoord0[1] = Vector2f(1, 0); model.texcoord0[2] = Vector2f(0, 1); model.texcoord0[3] = Vector2f(1, 1); // Set triangles: model.indices[0] = 0; model.indices[1] = 2; model.indices[2] = 1; model.indices[3] = 2; model.indices[4] = 3; model.indices[5] = 1; // Set new positions model.position[0] = Vector2f(-hxsize, -hysize); model.position[1] = Vector2f( hxsize, -hysize); model.position[2] = Vector2f(-hxsize, hysize); model.position[3] = Vector2f( hxsize, hysize); // Model is created, we upload: m_MeshBuffer.InitMeshBuffers(&model); m_MeshBuffer.m_modeldata = NULL; // Free the CPU model data: delete_safe_array(model.position); delete_safe_array(model.normal); delete_safe_array(model.tangent); delete_safe_array(model.color); delete_safe_array(model.texcoord0); delete_safe_array(model.indices); } } RrShapePlane::RrShapePlane ( void ) : RrRenderObject() { BuildMeshBuffer(); } bool RrShapePlane::CreateConstants ( rrCameraPass* cameraPass ) { // Set up transformation for the mesh PushCbufferPerObject(this->transform.world, cameraPass); return true; } // Render the mesh bool RrShapePlane::Render ( const rrRenderParams* params ) { gpu::GraphicsContext* gfx = params->context->context_graphics; gpu::Pipeline* pipeline = GetPipeline( params->pass ); gfx->setPipeline(pipeline); // Set up the material helper... renderer::Material(this, params->context, params, pipeline) // set the depth & blend state registers .setDepthStencilState() .setRasterizerState() // bind the samplers & textures .setBlendState() .setTextures() // execute callback .executePassCallback(); // bind the vertex buffers auto passAccess = PassAccess(params->pass); for (int i = 0; i < passAccess.getVertexSpecificationCount(); ++i) { int buffer_index = (int)passAccess.getVertexSpecification()[i].location; int buffer_binding = (int)passAccess.getVertexSpecification()[i].binding; if (m_MeshBuffer.m_bufferEnabled[buffer_index]) gfx->setVertexBuffer(buffer_binding, &m_MeshBuffer.m_buffer[buffer_index], 0); } // bind the index buffer gfx->setIndexBuffer(&m_MeshBuffer.m_indexBuffer, gpu::kIndexFormatUnsigned16); // bind the cbuffers: TODO gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_MATRICES, &m_cbufPerObjectMatrices); gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_OBJECT_MATRICES, &m_cbufPerObjectMatrices); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_EXTENDED, &m_cbufPerObjectSurfaces[params->pass]); gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_OBJECT_EXTENDED, &m_cbufPerObjectSurfaces[params->pass]); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_CAMERA_INFORMATION, params->cbuf_perCamera); gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_CAMERA_INFORMATION, params->cbuf_perCamera); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_PASS_INFORMATION, params->cbuf_perPass); gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_PASS_INFORMATION, params->cbuf_perPass); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_FRAME_INFORMATION, params->cbuf_perFrame); gfx->setShaderCBuffer(gpu::kShaderStagePs, renderer::CBUFFER_PER_FRAME_INFORMATION, params->cbuf_perFrame); // draw now //gfx->drawIndexed(m_MeshBuffer.m_modeldata->indexNum, 0, 0); gfx->drawIndexed(6, 0, 0); return true; }
33.596899
123
0.739502
skarik
b3d91ac2b161cf618f17cb46fac3839324372ada
4,595
cpp
C++
tests/unit/test_exact_ops.cpp
ylatkin/tfcp
9db30f7fd23dfc9f56cbe9657c39dfd6ab4559cd
[ "Apache-2.0" ]
2
2020-04-28T16:37:03.000Z
2021-01-07T15:52:15.000Z
tests/unit/test_exact_ops.cpp
ylatkin/tfcp
9db30f7fd23dfc9f56cbe9657c39dfd6ab4559cd
[ "Apache-2.0" ]
1
2020-01-07T04:40:51.000Z
2020-01-07T06:48:49.000Z
tests/unit/test_exact_ops.cpp
ylatkin/tfcp
9db30f7fd23dfc9f56cbe9657c39dfd6ab4559cd
[ "Apache-2.0" ]
null
null
null
//====================================================================== // 2019-2020 (c) Evgeny Latkin // License: Apache 2.0 (http://www.apache.org/licenses/) //====================================================================== #include <tfcp/test_utils.h> #include <tfcp/exact.h> #include <tfcp/simd.h> #include <gtest/gtest.h> #include <random> #include <string> #include <tuple> #include <cmath> #include <cstdio> namespace { using namespace tfcp; using namespace testing; //---------------------------------------------------------------------- // // Reference functions (scalar types): ref_padd0, ref_psub0, ref_pmul0 // //---------------------------------------------------------------------- template<typename T> T ref_padd0(T x, T y, T& r1) { if (std::fabs(x) >= std::fabs(y)) { return fast_padd0(x, y, r1); } else { return fast_padd0(y, x, r1); } } template<typename T> T ref_psub0(T x, T y, T& r1) { if (std::fabs(x) >= std::fabs(y)) { return fast_psub0(x, y, r1); } else { T t0, t1; t0 = fast_psub0(y, x, t1); r1 = -t1; return -t0; } } template<typename T> T ref_pmul0(T x, T y, T& r1) { return nofma_pmul0(x, y, r1); } //---------------------------------------------------------------------- using TypeName = std::string; using OpName = std::string; using Params = typename std::tuple<TypeName, OpName>; class TestUnitExactOps : public TestWithParam<Params> { private: template<typename T, typename TX, typename F, typename FX> static void test_case(const char type[], const char op[], F f, FX fx) { std::mt19937 gen; std::uniform_real_distribution<T> dis(-10, 10); int errors = 0; // repeat this test 1000 times for (int n = 0; n < 1000; n++) { TX x, y, r0, r1; int len = sizeof(TX) / sizeof(T); for (int i = 0; i < len; i++) { getx(x, i) = dis(gen); getx(y, i) = dis(gen); } r0 = fx(x, y, r1); // maybe short-vector operation for (int i = 0; i < len; i++) { T xi = getx(x, i); T yi = getx(y, i); T r0i, r1i; // actual result T e0i, e1i; // expected r0i = getx(r0, i); r1i = getx(r1, i); e0i = f(xi, yi, e1i); if (r0i != e0i || r1i != e1i) { printf("ERROR: type=%s op=%s iter=%d i=%d " "result=%g + %g expected=%g + %g\n", type, op, n+1, i, r0i, r1i, e0i, e1i); errors++; if (errors > 25) { FAIL() << "too many failures"; } } } } ASSERT_EQ(errors, 0); } protected: #define TEST_CASE(OP) \ template<typename T, typename TX> \ static void test_##OP(const char type[]) \ { \ test_case<T, TX>(type, #OP, ref_p##OP##0<T>, p##OP##0<TX>); \ } TEST_CASE(add); TEST_CASE(sub); TEST_CASE(mul); #undef TEST_CASE }; TEST_P(TestUnitExactOps, smoke) { auto param = GetParam(); auto type = std::get<0>(param); auto op = std::get<1>(param); #define OP_CASE(T, TX, OP) \ if (op == #OP) { \ test_##OP<T,TX>(#TX); \ return; \ } #define TYPE_CASE(T, TX) \ if (type == #TX) { \ OP_CASE(T, TX, add); \ OP_CASE(T, TX, sub); \ OP_CASE(T, TX, mul); \ FAIL() << "unknown op: " << op; \ } TYPE_CASE(float, float); TYPE_CASE(float, floatx); TYPE_CASE(double, double); TYPE_CASE(double, doublex); #undef TYPE_CASE #undef OP_CASE FAIL() << "unknown type: " << type; } //---------------------------------------------------------------------- } // namespace INSTANTIATE_TEST_SUITE_P(types, TestUnitExactOps, Combine(Values("float", "double", "floatx", "doublex"), Values("add", "sub", "mul")));
25.960452
73
0.395212
ylatkin
b3da909cea3b1c3a0731cc6138e902ac2390dffd
12,477
hpp
C++
mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator/include/mcppalloc/mcppalloc_bitmap_allocator/bitmap_state_impl.hpp
garyfurnish/mcppalloc
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
[ "MIT" ]
null
null
null
mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator/include/mcppalloc/mcppalloc_bitmap_allocator/bitmap_state_impl.hpp
garyfurnish/mcppalloc
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
[ "MIT" ]
null
null
null
mcppalloc_bitmap_allocator/mcppalloc_bitmap_allocator/include/mcppalloc/mcppalloc_bitmap_allocator/bitmap_state_impl.hpp
garyfurnish/mcppalloc
5a6dfc99bab23e7f6aba8d20919d71a6e31c38bf
[ "MIT" ]
null
null
null
#pragma once #include <atomic> #include <iostream> #include <mcppalloc/mcppalloc_slab_allocator/slab_allocator.hpp> #include <mcpputil/mcpputil/intrinsics.hpp> #include <mcpputil/mcpputil/security.hpp> namespace mcppalloc::bitmap_allocator::details { inline bitmap_state_t *get_state(void *v) { uintptr_t vi = reinterpret_cast<uintptr_t>(v); size_t mask = ::std::numeric_limits<size_t>::max() << (mcpputil::ffs(c_bitmap_block_size) - 1); vi &= mask; vi += ::mcppalloc::slab_allocator::details::slab_allocator_t::cs_header_sz; bitmap_state_t *state = reinterpret_cast<bitmap_state_t *>(vi); return state; } MCPPALLOC_OPT_ALWAYS_INLINE auto bitmap_state_t::declared_entry_size() const noexcept -> size_t { return m_internal.m_info.m_data_entry_sz; } MCPPALLOC_OPT_ALWAYS_INLINE auto bitmap_state_t::real_entry_size() const noexcept -> size_t { return cs_object_alignment > declared_entry_size() ? cs_object_alignment : declared_entry_size(); } MCPPALLOC_OPT_ALWAYS_INLINE auto bitmap_state_t::header_size() const noexcept -> size_t { return m_internal.m_info.m_header_size; } template <typename Allocator_Policy> void bitmap_state_t::set_bitmap_package(bitmap_package_t<Allocator_Policy> *package) noexcept { m_internal.m_info.m_package = package; } inline auto bitmap_state_t::bitmap_package() const noexcept -> void * { return m_internal.m_info.m_package; } inline void bitmap_state_t::initialize_consts() noexcept { m_internal.m_pre_magic_number = cs_magic_number_pre; m_internal.m_post_magic_number = cs_magic_number_0; } template <typename Allocator_Policy> inline void bitmap_state_t::initialize(type_id_t type_id, uint8_t user_bit_fields, bitmap_package_t<Allocator_Policy> *package) noexcept { initialize_consts(); m_internal.m_info.m_type_id = type_id; m_internal.m_info.m_num_user_bit_fields = user_bit_fields; _compute_size(); free_bits_ref().fill(::std::numeric_limits<uint64_t>::max()); m_internal.m_info.m_cached_first_free = 0; m_internal.m_info.m_package = package; for (size_t i = 0; i < num_user_bit_fields(); ++i) { clear_user_bits(i); } } inline void bitmap_state_t::clear_mark_bits() noexcept { mark_bits_ref().clear(); } inline void bitmap_state_t::clear_user_bits(size_t index) noexcept { user_bits_ref(index).clear(); } inline auto bitmap_state_t::all_free() const noexcept -> bool { return free_bits_ref().all_set(); } inline auto bitmap_state_t::num_bit_arrays() const noexcept -> size_t { return cs_bits_array_multiple + m_internal.m_info.m_num_user_bit_fields; } inline auto bitmap_state_t::any_free() const noexcept -> bool { return free_bits_ref().any_set(); } inline auto bitmap_state_t::none_free() const noexcept -> bool { return free_bits_ref().none_set(); } inline auto bitmap_state_t::first_free() const noexcept -> size_t { return m_internal.m_info.m_cached_first_free; } inline auto bitmap_state_t::_compute_first_free() noexcept -> size_t { auto ret = free_bits_ref().first_set(); m_internal.m_info.m_cached_first_free = ret; return ret; } inline auto bitmap_state_t::any_marked() const noexcept -> bool { return mark_bits_ref().any_set(); } inline auto bitmap_state_t::none_marked() const noexcept -> bool { return mark_bits_ref().none_set(); } inline auto bitmap_state_t::free_popcount() const noexcept -> size_t { return free_bits_ref().popcount(); } inline void bitmap_state_t::set_free(size_t i, bool val) noexcept { free_bits_ref().set_bit(i, val); if (val) { m_internal.m_info.m_cached_first_free = ::std::min(i, m_internal.m_info.m_cached_first_free); } else if (i == m_internal.m_info.m_cached_first_free) { // not free if (i + 1 >= size()) { m_internal.m_info.m_cached_first_free = ::std::numeric_limits<size_t>::max(); } else if (is_free(i + 1)) { m_internal.m_info.m_cached_first_free++; } else { // could be anywhere _compute_first_free(); } } } inline void bitmap_state_t::set_marked(size_t i) noexcept { mark_bits_ref().set_bit_atomic(i, true, ::std::memory_order_relaxed); } inline auto bitmap_state_t::is_free(size_t i) const noexcept -> bool { return free_bits_ref().get_bit(i); } inline auto bitmap_state_t::is_marked(size_t i) const noexcept -> bool { return mark_bits_ref().get_bit(i); } inline auto bitmap_state_t::type_id() const noexcept -> type_id_t { return m_internal.m_info.m_type_id; } inline auto bitmap_state_t::size() const noexcept -> size_t { return m_internal.m_info.m_size; } inline void bitmap_state_t::_compute_size() noexcept { auto blocks = m_internal.m_info.m_num_blocks; auto unaligned = sizeof(*this) + sizeof(bits_array_type) * blocks * num_bit_arrays(); m_internal.m_info.m_header_size = mcpputil::align(unaligned, cs_header_alignment); auto hdr_sz = header_size(); auto data_sz = c_bitmap_block_size - slab_allocator::details::slab_allocator_t::cs_header_sz - hdr_sz; // this needs to be min of stuff auto num_data = data_sz / (real_entry_size()); num_data = ::std::min(num_data, m_internal.m_info.m_num_blocks * bits_array_type::size_in_bits()); m_internal.m_info.m_size = num_data; } inline auto bitmap_state_t::size_bytes() const noexcept -> size_t { return size() * real_entry_size(); } inline auto bitmap_state_t::total_size_bytes() const noexcept -> size_t { return size_bytes() + header_size(); } inline auto bitmap_state_t::begin() noexcept -> uint8_t * { return reinterpret_cast<uint8_t *>(this) + header_size(); } inline auto bitmap_state_t::end() noexcept -> uint8_t * { return begin() + size_bytes(); } inline auto bitmap_state_t::begin() const noexcept -> const uint8_t * { return reinterpret_cast<const uint8_t *>(this) + header_size(); } inline auto bitmap_state_t::end() const noexcept -> const uint8_t * { return begin() + size_bytes(); } inline void *bitmap_state_t::allocate() noexcept { size_t retries = 0; RESTART: auto i = first_free(); if (i >= size()) { return nullptr; } // guarentee the memory address exists somewhere that is visible to gc volatile auto memory_address = begin() + real_entry_size() * i; set_free(i, false); // this awful code is because for a conservative gc // we could set free before memory_address is live. // this can go wrong because we could mark while it is still free. if (mcpputil_unlikely(is_free(i))) { if (mcpputil_likely(retries < 15)) { goto RESTART; } else { ::std::cerr << "mcppalloc: bitmap_state terminating due to allocation failure 0b3fb7a6-7270-45e3-a1cf-da341de0ccfb\n"; ::std::abort(); } } assert(memory_address); verify_magic(); return memory_address; } inline bool bitmap_state_t::deallocate(void *vv) noexcept { auto v = reinterpret_cast<uint8_t *>(vv); if (v < begin() || v > end()) { return false; } size_t byte_diff = static_cast<size_t>(v - begin()); if (mcpputil_unlikely(byte_diff % real_entry_size())) { return false; } mcpputil::secure_zero_stream(v, real_entry_size()); auto i = byte_diff / real_entry_size(); set_free(i, true); for (size_t j = 0; j < num_user_bit_fields(); ++j) { user_bits_ref(j).set_bit(i, false); } return true; } inline void bitmap_state_t::or_with_to_be_freed(bitmap::dynamic_bitmap_ref_t<false> to_be_freed) { const size_t alloca_size = block_size_in_bytes() + bitmap::dynamic_bitmap_ref_t<false>::bits_type::cs_alignment; const auto mark_memory = alloca(alloca_size); auto mark = bitmap::make_dynamic_bitmap_ref_from_alloca(mark_memory, num_blocks(), alloca_size); mark.deep_copy(mark_bits_ref()); to_be_freed |= mark.negate(); } inline void bitmap_state_t::free_unmarked() { or_with_to_be_freed(free_bits_ref()); _compute_first_free(); } inline auto bitmap_state_t::num_blocks() const noexcept -> size_t { return m_internal.m_info.m_num_blocks; } inline auto bitmap_state_t::num_user_bit_fields() const noexcept -> size_t { return m_internal.m_info.m_num_user_bit_fields; } inline auto bitmap_state_t::block_size_in_bytes() const noexcept -> size_t { return num_blocks() * sizeof(bits_array_type); } inline auto bitmap_state_t::free_bits() noexcept -> bits_array_type * { return mcpputil::unsafe_cast<bits_array_type>(this + 1); } inline auto bitmap_state_t::free_bits() const noexcept -> const bits_array_type * { return mcpputil::unsafe_cast<bits_array_type>(this + 1); } inline auto bitmap_state_t::mark_bits() noexcept -> bits_array_type * { return free_bits() + num_blocks(); } inline auto bitmap_state_t::mark_bits() const noexcept -> const bits_array_type * { return free_bits() + num_blocks(); } inline auto bitmap_state_t::user_bits(size_t i) noexcept -> bits_array_type * { return mark_bits() + num_blocks() * (i + 1); } inline auto bitmap_state_t::user_bits(size_t i) const noexcept -> const bits_array_type * { return mark_bits() + num_blocks() * (i + 1); } inline auto bitmap_state_t::free_bits_ref() noexcept -> bitmap::dynamic_bitmap_ref_t<false> { return bitmap::make_dynamic_bitmap_ref(free_bits(), num_blocks()); } inline auto bitmap_state_t::free_bits_ref() const noexcept -> bitmap::dynamic_bitmap_ref_t<true> { return bitmap::make_dynamic_bitmap_ref(free_bits(), num_blocks()); } inline auto bitmap_state_t::mark_bits_ref() noexcept -> bitmap::dynamic_bitmap_ref_t<false> { return bitmap::make_dynamic_bitmap_ref(mark_bits(), num_blocks()); } inline auto bitmap_state_t::mark_bits_ref() const noexcept -> bitmap::dynamic_bitmap_ref_t<true> { return bitmap::make_dynamic_bitmap_ref(mark_bits(), num_blocks()); } inline auto bitmap_state_t::user_bits_ref(size_t index) noexcept -> bitmap::dynamic_bitmap_ref_t<false> { return bitmap::make_dynamic_bitmap_ref(user_bits(index), num_blocks()); } inline auto bitmap_state_t::user_bits_ref(size_t index) const noexcept -> bitmap::dynamic_bitmap_ref_t<true> { return bitmap::make_dynamic_bitmap_ref(user_bits(index), num_blocks()); } inline auto bitmap_state_t::user_bits_checked(size_t i) noexcept -> bits_array_type * { if (mcpputil_unlikely(i >= m_internal.m_info.m_num_user_bit_fields)) { ::std::cerr << "mcppalloc: User bits out of range: 224f26b3-d2e6-47f3-b6de-6a4194750242"; ::std::terminate(); } return user_bits(i); } inline auto bitmap_state_t::user_bits_checked(size_t i) const noexcept -> const bits_array_type * { if (mcpputil_unlikely(i >= m_internal.m_info.m_num_user_bit_fields)) { ::std::cerr << "mcppalloc: User bits out of range: 24a934d1-160f-4bfc-b765-e0e21ee69605"; ::std::terminate(); } return user_bits(i); } inline auto bitmap_state_t::get_index(void *v) const noexcept -> size_t { auto diff = reinterpret_cast<const uint8_t *>(v) - begin(); if (mcpputil_unlikely(diff < 0)) { assert(false); return ::std::numeric_limits<size_t>::max(); } const auto index = static_cast<size_t>(diff) / real_entry_size(); if (mcpputil_unlikely(index >= size())) { return ::std::numeric_limits<size_t>::max(); } return index; } inline auto bitmap_state_t::get_object(size_t i) noexcept -> void * { if (mcpputil_unlikely(i >= size())) { ::std::cerr << "mcppalloc: bitmap_state get object failed"; ::std::terminate(); } return reinterpret_cast<void *>(begin() + i * real_entry_size()); } inline auto bitmap_state_t::has_valid_magic_numbers() const noexcept -> bool { return m_internal.m_pre_magic_number == cs_magic_number_pre && m_internal.m_post_magic_number == cs_magic_number_0; } inline void bitmap_state_t::verify_magic() const { #ifdef _DEBUG if (mcpputil_unlikely(!has_valid_magic_numbers())) { ::std::cerr << "mcppalloc: bitmap_state: invalid magic numbers 027e8d50-8555-4e7f-93a7-4d048b506436\n"; ::std::abort(); } #endif } inline auto bitmap_state_t::addr_in_header(void *v) const noexcept -> bool { return begin() > v; } }
34.658333
126
0.703054
garyfurnish
b3dcce1a208ebefcab89e7970a04993c5780a1f9
466
cpp
C++
examples/appearance/figure/figure_2.cpp
gitplcc/matplotplusplus
c088749434154c230ee7547c6871d65e58876dc6
[ "MIT" ]
2,709
2020-08-29T01:25:40.000Z
2022-03-31T18:35:25.000Z
examples/appearance/figure/figure_2.cpp
p-ranav/matplotplusplus
b45015e2be88e3340b400f82637b603d733d45ce
[ "MIT" ]
124
2020-08-29T04:48:17.000Z
2022-03-25T15:45:59.000Z
examples/appearance/figure/figure_2.cpp
p-ranav/matplotplusplus
b45015e2be88e3340b400f82637b603d733d45ce
[ "MIT" ]
203
2020-08-29T04:16:22.000Z
2022-03-30T02:08:36.000Z
#include <matplot/matplot.h> int main() { using namespace matplot; auto h = figure(true); h->name("Measured Data"); h->number_title(false); h->color("green"); h->position({0, 0, 600, 600}); h->size(500, 500); h->draw(); h->font("Arial"); h->font_size(40); h->title("My experiment"); constexpr float pi_f = 3.14f; axis({-pi_f, pi_f, -1.5f, +1.5f}); fplot("cos(x)"); h->draw(); show(); return 0; }
20.26087
38
0.534335
gitplcc
b3dd57ad425ec876ef7d19ec92a978a2c029c1d1
17,494
cpp
C++
HTWK_ChangeSpeed/ChangeSpeed.cpp
HTWKSmartDriving/aadc-2017
aff82d8b7d936cdfade6e8ad3edd548c71be8311
[ "BSD-3-Clause" ]
10
2017-11-17T16:39:03.000Z
2020-10-10T08:33:43.000Z
HTWK_ChangeSpeed/ChangeSpeed.cpp
HTWKSmartDriving/aadc-2017
aff82d8b7d936cdfade6e8ad3edd548c71be8311
[ "BSD-3-Clause" ]
null
null
null
HTWK_ChangeSpeed/ChangeSpeed.cpp
HTWKSmartDriving/aadc-2017
aff82d8b7d936cdfade6e8ad3edd548c71be8311
[ "BSD-3-Clause" ]
5
2017-11-18T09:35:24.000Z
2021-01-20T07:03:46.000Z
#include "ChangeSpeed.h" ADTF_FILTER_PLUGIN(FILTER_NAME, OID, ChangeSpeed); ChangeSpeed::ChangeSpeed(const tChar *__info) : Leaf(__info) { // speed properties SetPropertyFloat(ROAD_SPEED_PROPERTY, SPEED_ROAD); SetPropertyStr(ROAD_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive on road"); SetPropertyFloat(INTERSECTION_SPEED_PROPERTY, SPEED_INTERSECTION); SetPropertyStr(INTERSECTION_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive on intersections"); SetPropertyFloat(NEARING_GIVE_WAY_SPEED_PROPERTY, SPEED_NEARING_GIVE_WAY); SetPropertyStr(NEARING_GIVE_WAY_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive when nearing give way intersection"); SetPropertyFloat(NEARING_HAVE_WAY_SPEED_PROPERTY, SPEED_NEARING_HAVE_WAY); SetPropertyStr(NEARING_HAVE_WAY_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive when nearing have way intersection"); SetPropertyFloat(NEARING_FULL_STOP_SPEED_PROPERTY, SPEED_NEARING_FULL_STOP); SetPropertyStr(NEARING_FULL_STOP_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive when nearing full stop intersection"); SetPropertyFloat(NEARING_GENERIC_SPEED_PROPERTY, SPEED_NEARING_GENERIC); SetPropertyStr(NEARING_GENERIC_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, "Speed to drive when nearing generic intersection"); //other properties SetPropertyFloat(DETECT_DIST_PROPERTY, DETECT_DIST_DEFAULT); SetPropertyStr(DETECT_DIST_PROPERTY NSSUBPROP_DESCRIPTION, DETECT_DIST_DESCRIPTION); SetPropertyFloat(SLOW_SPEED_PROPERTY, SLOW_SPEED_DEFAULT); SetPropertyStr(SLOW_SPEED_PROPERTY NSSUBPROP_DESCRIPTION, SLOW_SPEED_DESCRIPTION); SetPropertyFloat(STOP_AT_PERSON_PROPERTY, STOP_AT_PERSON_DEFAULT); SetPropertyStr(STOP_AT_PERSON_PROPERTY NSSUBPROP_DESCRIPTION, STOP_AT_PERSON_DESCRIPTION); SetPropertyFloat(LANE_WIDTH_PROPERTY, LANE_WIDTH_DEFAULT); SetPropertyFloat(ROAD_OBTACLE_DIST_PROPERTY, ROAD_OBTACLE_DIST_DEFAULT); SetPropertyFloat(INTERSECTION_OBTACLE_DIST_PROPERTY, INTERSECTION_OBTACLE_DIST_DEFAULT); SetPropertyFloat(PEDESTRIAN_OBTACLE_DIST_PROPERTY, PEDESTRIAN_OBTACLE_DIST_DEFAULT); } ChangeSpeed::~ChangeSpeed() = default; tResult ChangeSpeed::Init(tInitStage eStage, __exception) { RETURN_IF_FAILED(Leaf::Init(eStage, __exception_ptr)); if (eStage == StageNormal) { detectDist = static_cast<tFloat32>(GetPropertyFloat(DETECT_DIST_PROPERTY, DETECT_DIST_DEFAULT)); slowSpeed = static_cast<tFloat32>(GetPropertyFloat(SLOW_SPEED_PROPERTY, SLOW_SPEED_DEFAULT)); speedOnRoad = static_cast<tFloat32>(GetPropertyFloat(ROAD_SPEED_PROPERTY)); speedNearingHaveWay = static_cast<tFloat32>(GetPropertyFloat(NEARING_HAVE_WAY_SPEED_PROPERTY)); speedNearingGiveWay = static_cast<tFloat32>(GetPropertyFloat(NEARING_GIVE_WAY_SPEED_PROPERTY)); speedNearingFullStop = static_cast<tFloat32>(GetPropertyFloat(NEARING_FULL_STOP_SPEED_PROPERTY)); speedNearingGeneric = static_cast<tFloat32>(GetPropertyFloat(NEARING_GENERIC_SPEED_PROPERTY)); speedIntersection = static_cast<tFloat32>(GetPropertyFloat(INTERSECTION_SPEED_PROPERTY)); stopPersonTime = static_cast<int>(GetPropertyFloat(STOP_AT_PERSON_PROPERTY, STOP_AT_PERSON_DEFAULT) * 1000000); laneWidth = GetPropertyFloat(LANE_WIDTH_PROPERTY, LANE_WIDTH_DEFAULT); distRoad = GetPropertyFloat(ROAD_OBTACLE_DIST_PROPERTY, ROAD_OBTACLE_DIST_DEFAULT); distPedestrian = GetPropertyFloat(PEDESTRIAN_OBTACLE_DIST_PROPERTY, PEDESTRIAN_OBTACLE_DIST_DEFAULT); distIntersection = GetPropertyFloat(INTERSECTION_OBTACLE_DIST_PROPERTY, INTERSECTION_OBTACLE_DIST_DEFAULT); pedestrianTime = 5000000; } RETURN_NOERROR; } tResult ChangeSpeed::OnTrigger() { std::vector<tTrackingData> allObstacles; IntersectionState intersectionState; if (!IS_OK(worldService->Pull(WORLD_CURRENT_POSITION, currentPos))) { // LOG_ERROR("Current Position could not be pulled!"); TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } if (!IS_OK(worldService->Pull(WORLD_OBSTACLES, allObstacles))) { noObstacles = true; } else { noObstacles = false; } if (!IS_OK(worldService->Pull(WORLD_CURRENT_HEADING, heading))) { // LOG_ERROR("Heading could not be pulled!"); TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } // if (!IS_OK(worldService->Pull(WORLD_ZEBRA_STATE, zebraState))) { // LOG_ERROR("Zebra State could not be pulled!"); // RETURN_ERROR(ERR_FAILED); // } if (!IS_OK(worldService->Pull(WORLD_INTERSECTION_STATE, intersectionState))) { // LOG_ERROR("intersection state could not be pulled!"); TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } if (!IS_OK(worldService->Pull(WORLD_CURRENT_SPEED, currentSpeed))) { #ifdef DEBUG_MAP_VIEW_LOG LOG_ERROR("Current speed could not be pulled from WorldService"); #endif TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } if (!IS_OK(worldService->Pull(CAR_STATE, state))) { #ifdef DEBUG_MAP_VIEW_LOG LOG_ERROR("State could not be pulled from WorldService"); #endif TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } if (!IS_OK(worldService->Pull(WORLD_NEXT_TURN, nextTurn))) { // LOG_ERROR("nextTurn could not be pulled!"); TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } if (!IS_OK(worldService->Pull(WORLD_ROAD_SIGN_EXT, nextSign))) { // LOG_ERROR("road sign could not be pulled!"); TransmitStatus(BT::FAIL); RETURN_ERROR(ERR_FAILED); } // heading = HTWKMathUtils::rad2deg(heading); // if (!IS_OK(worldService->Pull(WORLD_LANE_LEFT, leftLaneDist))) { leftLaneDist = laneWidth * 1.5; // } // if (!IS_OK(worldService->Pull(WORLD_LANE_RIGHT, rightLaneDist))) { rightLaneDist = laneWidth / 2; // } return findSpeedNew(allObstacles, intersectionState); } // 90 // | //180 -- -- 0 // | // -90 //HTWKLane //ChangeSpeed::ExtractLanesFromPositionAndHeading(HTWKPoint carPos, tFloat carHeading) { // HTWKLane lane; // // berechne Punkt der auf der Fahrspur liegt // // linke Spur: berechne Vektor der 90 Grad nach links von aktueller Position aus zeigt, mit Länge der Distanz zur Spur // // rechte Spur: Vektor zeigt 90 Grad nach rechts // tFloat rotatedHeading = carHeading + 90; // //rechne von Polarkoordinaten in kartesische um // HTWKPoint vector2Lane = PolarToCartesian(rightLaneDist, rotatedHeading); // // addiere berechneten Vektor auf die eigene Position = Spurpunkt 1 // lane.rightStart = carPos.add(vector2Lane); // // berechne 2. Spurpunkt, durch Addition eines Vektors mit beliebiger Länge und Winkel in Richtung des Heading des Autos // // rechne in kartesische Koordinaten um // HTWKPoint lanePoint2 = lane.rightStart.add(PolarToCartesian(1.0, carHeading)); // // lege Gerade durch beide Punkte -> ~Spur // lane.right = HTWKPoint(lanePoint2.x() - lane.rightStart.x(), lanePoint2.y() - lane.rightStart.y()); // // // das gleiche für die mittlere Spur // // Vektor auf die Spur zeigt 90 Grad nach links // rotatedHeading = carHeading - 90; // //dist zur Mitte = dist nach rechts // vector2Lane = PolarToCartesian(rightLaneDist, rotatedHeading); // lane.middleStart = carPos.add(vector2Lane); // lanePoint2 = lane.middleStart.add(PolarToCartesian(1.0, carHeading)); // lane.middle = HTWKPoint(lanePoint2.x() - lane.middleStart.x(), lanePoint2.y() - lane.middleStart.y()); // // vector2Lane = PolarToCartesian(leftLaneDist, rotatedHeading); // lane.leftStart = carPos.add(vector2Lane); // lanePoint2 = lane.leftStart.add(PolarToCartesian(1.0, carHeading)); // lane.left = HTWKPoint(lanePoint2.x() - lane.leftStart.x(), lanePoint2.y() - lane.leftStart.y()); // return lane; //} // x = r * cos (alpha) // y = r * sin (alpha) //HTWKPoint ChangeSpeed::PolarToCartesian(tFloat length, tFloat angle) { // double x = length * std::cos(angle); // double y = length * std::sin(angle); // return HTWKPoint(x, y); //} ObstaclePos ChangeSpeed::IsPositionOnRoad(cv::Point2f obstaclePosition) { cv::Point2f carPosition; carPosition.x = static_cast<float>(-currentPos.x()); carPosition.y = static_cast<float>(-currentPos.y()); cv::Point2f newObstPos = htwk::translateAndRotate2DPoint(obstaclePosition, static_cast<float>(-(heading)), carPosition); // std::string log = "x: " + to_string(newObstPos.x) + " y: " + to_string(newObstPos.y); // LOG_INFO(log.c_str()); if (newObstPos.x >= 0) { //rechte Seite if (newObstPos.x <= rightLaneDist) { return ObstaclePos::LANE; } else { return ObstaclePos::OFFROAD_R; } } else { if (-newObstPos.x <= rightLaneDist) { return ObstaclePos::LANE; } else if (-newObstPos.x <= leftLaneDist) { return ObstaclePos::OTHER_LANE; } else { return ObstaclePos::OFFROAD_L; } } } tResult ChangeSpeed::FullBrake() { // LOG_INFO("do full brake"); //stopPersonTimer = _clock->GetStreamTime() + stopPersonTime; SetSpeedOutput(0); return TransmitStatus(BT::SUCCESS); } tResult ChangeSpeed::findUsualSpeed(const IntersectionState &interState) { tFloat32 speed = 0; if (state == stateCar::stateCar_RUNNING) { switch (interState) { case IntersectionState::ON_ROAD: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: ON_ROAD"); #endif speed = speedOnRoad; fullStopDone = false; stopTimer = 0; break; case IntersectionState::NEARING_HAVE_WAY: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: NEARING_HAVE_WAY"); #endif speed = speedNearingHaveWay; fullStopDone = false; stopTimer = 0; break; case IntersectionState::NEARING_GIVE_WAY: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: NEARING_GIVE_WAY"); #endif speed = speedNearingGiveWay; fullStopDone = false; stopTimer = 0; break; case IntersectionState::NEARING_FULL_STOP: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: NEARING_FULL_STOP"); #endif speed = speedNearingFullStop; fullStopDone = false; stopTimer = 0; break; case IntersectionState::ON_INTERSECTION: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: ON_INTERSECTION"); #endif speed = speedIntersection; break; case IntersectionState::STOP_NOW: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: STOP_NOW"); #endif if (!fullStopDone) { if (currentSpeed > 0.1) { speed = 0; } else { if (stopTimer == 0) { stopTimer = _clock->GetStreamTime() + STOP_AT_STOP_SIGN; } else if (_clock->GetStreamTime() > stopTimer) { fullStopDone = tTrue; } } } else { speed = speedIntersection; } break; case IntersectionState::NEARING_GENERIC: #ifdef DEBUG_MAP_VIEW_LOG LOG_INFO("IntersectionState: NEARING_GENERIC"); #endif speed = speedNearingGeneric; fullStopDone = false; stopTimer = 0; break; } } else { speed = 0; } SetSpeedOutput(speed); RETURN_NOERROR; } tResult ChangeSpeed::findSpeedNew(const vector<tTrackingData> &obstacles, const IntersectionState &interState) { //pedestrian if (pedestrianTimer != 0) { SetSpeedOutput(0); if (pedestrianTimer + pedestrianTime > _clock->GetStreamTime()) { pedestrianTimer = 0; } return TransmitStatus(BT::SUCCESS); } HTWKPoint pedestrianPos1 = HTWKPoint(3.5, 0.5); HTWKPoint pedestrianPos2 = HTWKPoint(3.5, 10.5); if (HTWKUtils::Equals(pedestrianPos1, currentPos, distPedestrian) || HTWKUtils::Equals(pedestrianPos2, currentPos, distPedestrian)) { SetSpeedOutput(0); pedestrianTimer = _clock->GetStreamTime(); return TransmitStatus(BT::SUCCESS); } if (interState == IntersectionState::STOP_NOW) { if (!IS_OK(findObstacleSpeedOnIntersection(obstacles))) { findUsualSpeed(interState); return TransmitStatus(BT::SUCCESS); } else { RETURN_NOERROR; } } if (!IS_OK(findObstacleSpeedOnRoad(obstacles))) { findUsualSpeed(interState); return TransmitStatus(BT::SUCCESS); } else { RETURN_NOERROR; } } tResult ChangeSpeed::findObstacleSpeedOnRoad(const vector<tTrackingData> &obstacles) { if (stopPersonTimer != 0) { SetSpeedOutput(slowSpeed); if (stopPersonTimer + stopPersonTime < _clock->GetStreamTime()) { stopPersonTimer = 0; } RETURN_ERROR(ERR_FAILED); } if (noObstacles) { RETURN_ERROR(ERR_FAILED); } for (const tTrackingData &obstacle : obstacles) { HTWKPoint distPoint; distPoint.setXval(obstacle.position.x); distPoint.setYval(obstacle.position.y); if (obstacle.type == ObstacleType::CHILD && distPoint.dist(currentPos) <= distRoad) { stopPersonTimer = _clock->GetStreamTime(); SetSpeedOutput(slowSpeed); return TransmitStatus(BT::SUCCESS); } } RETURN_ERROR(ERR_FAILED); } tResult ChangeSpeed::findObstacleSpeedOnIntersection(const vector<tTrackingData> &obstacles) { if (noObstacles) { RETURN_ERROR(ERR_FAILED); } for (tTrackingData obstacle : obstacles) { ObstaclePos obstRoad = IsPositionOnRoad(obstacle.position); HTWKPoint distPoint; distPoint.setXval(obstacle.position.x); distPoint.setYval(obstacle.position.y); if (obstacle.type == ObstacleType::CAR && distPoint.dist(currentPos) < distIntersection) { switch (nextTurn) { case Orientation::TurnDirection::STRAIGHT: if (obstRoad == ObstaclePos::OFFROAD_R) { return FullBrake(); } else if (obstRoad == ObstaclePos::OFFROAD_L) { return FullBrake(); } else { RETURN_ERROR(ERR_FAILED); } case Orientation::TurnDirection::LEFT: { return FullBrake(); } case Orientation::TurnDirection::RIGHT: if (obstRoad == ObstaclePos::OFFROAD_L) { return FullBrake(); } else { RETURN_ERROR(ERR_FAILED); } } } } RETURN_ERROR(ERR_FAILED); } //tResult ChangeSpeed::findObstacleSpeedOnPedestrian(const vector<tTrackingData> &obstacles) { // if (noObstacles) { // RETURN_ERROR(ERR_FAILED); // } // // ObstaclePos obstRoad; // HTWKPoint distPoint; // bool slowDown = false; // // for (tTrackingData obstacle : obstacles) { // obstRoad = IsPositionOnRoad(obstacle.position); // distPoint.setXval(obstacle.position.x); // distPoint.setYval(obstacle.position.y); // if(distPoint.dist(currentPos) > distPedestrian){ // RETURN_ERROR(ERR_FAILED); // } // // if (obstacle.type == ObstacleType::ADULT || obstacle.type == ObstacleType::CHILD) { // // if (firstObstacleSight) { // firstObstacleSight = false; // firstObstaclePos = obstRoad; // if (currentPos.dist(distPoint) <= pedestrianDetectDist) { // slowDown = true; // } else { // RETURN_ERROR(ERR_FAILED); // } // } else { // if (obstRoad == ObstaclePos::LANE || obstRoad == ObstaclePos::OTHER_LANE) { // return FullBrake(); // } else if (obstRoad == firstObstaclePos) { // return FullBrake(); // } else { // firstObstacleSight = true; // RETURN_ERROR(ERR_FAILED); // } // } // } // } // if (slowDown) { // SetSpeedOutput(slowSpeed); // return TransmitStatus(BT::SUCCESS); // } else { // RETURN_ERROR(ERR_FAILED); // } //} //tFloat ChangeSpeed::VectorAngle(HTWKPoint vec1, HTWKPoint vec2) { // tFloat prod = vec1.x() * vec2.x() + vec1.y() * vec2.y(); // tFloat length1 = std::sqrt(vec1.x() * vec1.x() + vec1.y() * vec1.y()); // tFloat length2 = std::sqrt(vec2.x() * vec2.x() + vec2.y() * vec2.y()); // return prod / (length1 * length2); //}
37.460385
137
0.634732
HTWKSmartDriving
b3df21842b1f9462c97161cf890ce8cf1a5004a1
2,402
cpp
C++
simulation/algorithms/Type2/C++/Qt/Type2/MainWindow.cpp
motchy869/Distributed-ThompthonSampling
17bb11f789ccc410e12c99347decc09c836dd708
[ "MIT" ]
null
null
null
simulation/algorithms/Type2/C++/Qt/Type2/MainWindow.cpp
motchy869/Distributed-ThompthonSampling
17bb11f789ccc410e12c99347decc09c836dd708
[ "MIT" ]
null
null
null
simulation/algorithms/Type2/C++/Qt/Type2/MainWindow.cpp
motchy869/Distributed-ThompthonSampling
17bb11f789ccc410e12c99347decc09c836dd708
[ "MIT" ]
null
null
null
#include "common.h" #include "Simulator.h" #include "MainWindow.h" #include <QApplication> #include <QDebug> #include <QLabel> #include <QMetaObject> #include <QProgressBar> #include <QThread> #include <QVBoxLayout> //QThreadによるマルチスレッド処理に関しては次が参考になる: https://qiita.com/hermit4/items/b1eaf6132fb06a30091f MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { //UI setWindowTitle(tr("Type1 simulation")); QVBoxLayout *vBoxLayout = new QVBoxLayout(); vBoxLayout->addWidget(m_label_basic_info = new QLabel(tr("basic info"))); m_label_basic_info->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); m_label_basic_info->setWordWrap(true); vBoxLayout->addStretch(); vBoxLayout->addWidget(new QLabel(tr("current play progress"))); vBoxLayout->addWidget(m_pb_current_play = new QProgressBar()); vBoxLayout->addWidget(new QLabel(tr("whole progress"))); vBoxLayout->addWidget(m_pb_sim = new QProgressBar()); QWidget *centralWidget = new QWidget(); centralWidget->setLayout(vBoxLayout); setCentralWidget(centralWidget); setMinimumWidth(640); //スレッド準備 m_simThread = new QThread(this); m_simulator = new Simulator(nullptr); //moveToThread するために親を null にする必要がある! m_simulator->moveToThread(m_simThread); //所属するイベントループを変更 connect(m_simThread, SIGNAL(started()), m_simulator, SLOT(run())); connect(m_simThread, SIGNAL(finished()), m_simulator, SLOT(deleteLater())); //親がいないQObjectの派生クラスは自動的にdeleteされないため、お膳立てしてやる。 connect(m_simulator, SIGNAL(update_basic_info_label(QString)), this, SLOT(update_basic_info_label(QString))); connect(m_simulator, SIGNAL(report_progress(int,int)), this, SLOT(update_progress_bar(int,int))); //終了の流れ connect(m_simulator, SIGNAL(sim_done()), m_simThread, SLOT(quit())); connect(m_simThread, SIGNAL(finished()), qApp, SLOT(quit())); m_simThread->start(); } void MainWindow::update_basic_info_label(QString s) { m_label_basic_info->setText(s); } void MainWindow::update_progress_bar(int prog_current, int prog_whole) { Q_ASSERT(prog_current>=0 && prog_current<=100 && prog_whole>=0 && prog_whole<=100); m_pb_current_play->setValue(prog_current); m_pb_sim->setValue(prog_whole); } void MainWindow::closeEvent(QCloseEvent*) { //ウィンドウを閉じた時にシミュレーションスレッドを終わらせる m_simThread->quit(); m_simThread->deleteLater(); } MainWindow::~MainWindow() { m_simThread->exit(); m_simThread->wait(); qDebug() << "~MainWindow()"; }
34.314286
124
0.764779
motchy869