text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "VoreealEditorPrivatePCH.h"
#include "BasicVolumeEditorViewportClient.h"
#include "SceneViewport.h"
#include "PreviewScene.h"
#include "ScopedTransaction.h"
#include "Runtime/Engine/Public/ComponentReregisterContext.h"
#include "AssetToolsModule.h"
#include "ContentBrowserModule.h"
#include "AssetRegistryModule.h"
#include "CanvasTypes.h"
#include "CanvasItem.h"
#include "SEditorViewport.h"
#include "SNotificationList.h"
#include "NotificationManager.h"
#include "BasicVolumeEditorSettings.h"
#define LOCTEXT_NAMESPACE "VoreealEditor"
FBasicVolumeEditorViewportClient::FBasicVolumeEditorViewportClient(TWeakPtr<FBasicVolumeEditor> InEditor, TWeakPtr<class SEditorViewport> InEditorViewportPtr)
: CurrentMode(EBasicVolumeEditorMode::ViewMode)
, EditorPtr(InEditor)
, EditorViewportPtr(InEditorViewportPtr)
{
check(EditorPtr.IsValid() && EditorViewportPtr.IsValid());
Widget->SetUsesEditorModeTools(ModeTools);
PreviewScene = &OwnedPreviewScene;
((FAssetEditorModeManager*)ModeTools)->SetPreviewScene(PreviewScene);
SetRealtime(true);
bManipulating = false;
bManipulationDirtiedSomething = false;
ScopedTransaction = nullptr;
bShowOctree = false;
bShowSockets = true;
bShowPivot = true;
DrawHelper.bDrawGrid = GetDefault<UBasicVolumeEditorSettings>()->bShowGridByDefault;
EngineShowFlags.DisableAdvancedFeatures();
EngineShowFlags.SetCompositeEditorPrimitives(true);
// Create a render component for the volume being edited
{
RenderVolumeComponent = NewObject<UBasicVolumeComponent>();
UBasicVolume* Volume = GetVolumeBeingEdited();
RenderVolumeComponent->SetBasicVolume(Volume);
PreviewScene->AddComponent(RenderVolumeComponent, FTransform::Identity);
}
}
void FBasicVolumeEditorViewportClient::ActivateEditMode()
{
ModeTools->SetWidgetMode(FWidget::WM_Translate);
}
#pragma region // Begin Show Flags
void FBasicVolumeEditorViewportClient::SetShowOctree(bool bShow)
{
bShowOctree = !bShowOctree;
Invalidate();
}
void FBasicVolumeEditorViewportClient::ToggleShowOctree()
{
bShowOctree = !bShowOctree;
Invalidate();
}
bool FBasicVolumeEditorViewportClient::IsSetShowOctreeChecked() const
{
return bShowOctree;
}
void FBasicVolumeEditorViewportClient::ToggleShowSockets()
{
bShowSockets = !bShowSockets;
Invalidate();
}
bool FBasicVolumeEditorViewportClient::IsShowSocketsChecked() const
{
return bShowSockets;
}
void FBasicVolumeEditorViewportClient::ToggleShowPivot()
{
bShowPivot = !bShowPivot;
Invalidate();
}
bool FBasicVolumeEditorViewportClient::IsShowPivotChecked() const
{
return bShowPivot;
}
#pragma endregion
void FBasicVolumeEditorViewportClient::EnterViewMode()
{
InternalActivateNewMode(EBasicVolumeEditorMode::ViewMode);
}
void FBasicVolumeEditorViewportClient::EnterEditMode()
{
InternalActivateNewMode(EBasicVolumeEditorMode::EditMode);
}
bool FBasicVolumeEditorViewportClient::IsInViewMode() const
{
return CurrentMode == EBasicVolumeEditorMode::ViewMode;
}
bool FBasicVolumeEditorViewportClient::IsInEditMode() const
{
return CurrentMode == EBasicVolumeEditorMode::EditMode;
}
void FBasicVolumeEditorViewportClient::DrawCanvas(FViewport& pViewport, FSceneView& View, FCanvas& Canvas)
{
const bool bIsHitTesting = Canvas.IsHitTesting();
if (!bIsHitTesting)
{
Canvas.SetHitProxy(nullptr);
}
if (!EditorPtr.IsValid())
{
return;
}
UBasicVolume* Volume = GetVolumeBeingEdited();
switch (CurrentMode)
{
default:
case EBasicVolumeEditorMode::ViewMode:
break;
case EBasicVolumeEditorMode::EditMode:
break;
}
//if (bShowSockets && !IsInSourceRegionEditMode())
//{
// FSpriteGeometryEditMode* GeometryEditMode = ModeTools->GetActiveModeTyped<FSpriteGeometryEditMode>(FSpriteGeometryEditMode::EM_SpriteGeometry);
// FSocketEditingHelper::DrawSocketNames(GeometryEditMode, RenderVolumeComponent, Viewport, View, Canvas);
//}
FEditorViewportClient::DrawCanvas(pViewport, View, Canvas);
}
void FBasicVolumeEditorViewportClient::Draw(const FSceneView* View, FPrimitiveDrawInterface* PDI)
{
FEditorViewportClient::Draw(View, PDI);
//// We don't draw the pivot when showing the source region
//// The pivot may be outside the actual texture bounds there
//if (bShowPivot && !bShowSourceTexture && !IsInSourceRegionEditMode())
//{
// const bool bCanSelectPivot = false;
// const bool bHitTestingForPivot = PDI->IsHitTesting() && bCanSelectPivot;
// FUnrealEdUtils::DrawWidget(View, PDI, RenderSpriteComponent->ComponentToWorld.ToMatrixWithScale(), 0, 0, EAxisList::XZ, EWidgetMovementMode::WMM_Translate, bHitTestingForPivot);
//}
//if (bShowSockets && !IsInSourceRegionEditMode())
//{
// FSpriteGeometryEditMode* GeometryEditMode = ModeTools->GetActiveModeTyped<FSpriteGeometryEditMode>(FSpriteGeometryEditMode::EM_SpriteGeometry);
// FSocketEditingHelper::DrawSockets(GeometryEditMode, RenderSpriteComponent, View, PDI);
//}
}
FBox FBasicVolumeEditorViewportClient::GetDesiredFocusBounds() const
{
UBasicVolumeComponent* ComponentToFocusOn = RenderVolumeComponent;
return ComponentToFocusOn->Bounds.GetBox();
}
void FBasicVolumeEditorViewportClient::Tick(float DeltaSeconds)
{
if (UBasicVolume* Volume = GetVolumeBeingEdited())
{
}
FVoreealEditorViewportClient::Tick(DeltaSeconds);
// Draw the octree
if (bShowOctree && RenderVolumeComponent)
{
RenderVolumeComponent->DrawDebugOctree(FLinearColor::Red, 0, 1.0f);
}
if (!GIntraFrameDebuggingGameThread)
{
OwnedPreviewScene.GetWorld()->Tick(LEVELTICK_All, DeltaSeconds);
}
}
void FBasicVolumeEditorViewportClient::ProcessClick(FSceneView& View, HHitProxy* HitProxy, FKey Key, EInputEvent Event, uint32 HitX, uint32 HitY)
{
const FViewportClick Click(&View, this, Key, Event, HitX, HitY);
const bool bIsCtrlKeyDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl);
const bool bIsShiftKeyDown = Viewport->KeyState(EKeys::LeftShift) || Viewport->KeyState(EKeys::RightShift);
const bool bIsAltKeyDown = Viewport->KeyState(EKeys::LeftAlt) || Viewport->KeyState(EKeys::RightAlt);
bool bHandled = false;
//HSpriteSelectableObjectHitProxy* SelectedItemProxy = HitProxyCast<HSpriteSelectableObjectHitProxy>(HitProxy);
//
//if (IsInSourceRegionEditMode())
//{
// if ((Event == EInputEvent::IE_DoubleClick) && (Key == EKeys::LeftMouseButton))
// {
// FVector4 WorldPoint = View.PixelToWorld(HitX, HitY, 0);
// UPaperSprite* Sprite = GetSpriteBeingEdited();
// FVector2D TexturePoint = SourceTextureViewComponent->GetSprite()->ConvertWorldSpaceToTextureSpace(WorldPoint);
// if (bIsCtrlKeyDown)
// {
// const FVector2D StartingUV = Sprite->GetSourceUV();
// const FVector2D StartingSize = Sprite->GetSourceSize();
//
// if (UPaperSprite* NewSprite = CreateNewSprite(FIntPoint((int32)StartingUV.X, (int32)StartingUV.Y), FIntPoint((int32)StartingSize.X, (int32)StartingSize.Y)))
// {
// NewSprite->ExtractSourceRegionFromTexturePoint(TexturePoint);
// bHandled = true;
// }
// }
// else
// {
// Sprite->ExtractSourceRegionFromTexturePoint(TexturePoint);
// bHandled = true;
// }
// }
// else if ((Event == EInputEvent::IE_Released) && (Key == EKeys::LeftMouseButton))
// {
// FVector4 WorldPoint = View.PixelToWorld(HitX, HitY, 0);
// FVector2D TexturePoint = SourceTextureViewComponent->GetSprite()->ConvertWorldSpaceToTextureSpace(WorldPoint);
// for (int32 RelatedSpriteIndex = 0; RelatedSpriteIndex < RelatedSprites.Num(); ++RelatedSpriteIndex)
// {
// FRelatedSprite& RelatedSprite = RelatedSprites[RelatedSpriteIndex];
// if ((TexturePoint.X >= RelatedSprite.SourceUV.X) && (TexturePoint.Y >= RelatedSprite.SourceUV.Y) &&
// (TexturePoint.X < (RelatedSprite.SourceUV.X + RelatedSprite.SourceDimension.X)) &&
// (TexturePoint.Y < (RelatedSprite.SourceUV.Y + RelatedSprite.SourceDimension.Y)))
// {
// bHandled = true;
//
// // Select this sprite
// if (UPaperSprite* LoadedSprite = Cast<UPaperSprite>(RelatedSprite.AssetData.GetAsset()))
// {
// if (SpriteEditorPtr.IsValid())
// {
// SpriteEditorPtr.Pin()->SetSpriteBeingEdited(LoadedSprite);
// break;
// }
// }
// }
// }
// }
//}
if (!bHandled)
{
FVoreealEditorViewportClient::ProcessClick(View, HitProxy, Key, Event, HitX, HitY);
}
}
bool FBasicVolumeEditorViewportClient::InputKey(FViewport* pViewport, int32 ControllerId, FKey Key, EInputEvent Event, float AmountDepressed, bool bGamepad)
{
bool bHandled = false;
FInputEventState InputState(pViewport, Key, Event);
// Pass keys to standard controls, if we didn't consume input
return (bHandled) ? true : FEditorViewportClient::InputKey(pViewport, ControllerId, Key, Event, AmountDepressed, bGamepad);
}
void FBasicVolumeEditorViewportClient::TrackingStarted(const struct FInputEventState& InInputState, bool bIsDragging, bool bNudge)
{
// Begin transacting. Give the current editor mode an opportunity to do the transacting.
const bool bTrackingHandledExternally = ModeTools->StartTracking(this, Viewport);
if (!bManipulating && bIsDragging && !bTrackingHandledExternally)
{
bManipulating = true;
bManipulationDirtiedSomething = false;
}
}
void FBasicVolumeEditorViewportClient::TrackingStopped()
{
// Stop transacting. Give the current editor mode an opportunity to do the transacting.
const bool bTransactingHandledByEditorMode = ModeTools->EndTracking(this, Viewport);
if (bManipulating && !bTransactingHandledByEditorMode)
{
bManipulating = false;
}
}
FLinearColor FBasicVolumeEditorViewportClient::GetBackgroundColor() const
{
return FLinearColor::Black;
}
void FBasicVolumeEditorViewportClient::NotifyVolumeBeingEditedHasChanged()
{
// Refresh the viewport in case we were not in realtime mode
Invalidate();
// Update components to know about the new volume being edited
UBasicVolume* Volume = GetVolumeBeingEdited();
RenderVolumeComponent->SetBasicVolume(Volume);
InternalActivateNewMode(CurrentMode);
if (Volume != nullptr)
{
// Create and display a notification about the new volume being edited
const FText NotificationErrorText = FText::Format(LOCTEXT("SwitchingToVolume", "Editing {0}"), FText::AsCultureInvariant(Volume->GetName()));
FNotificationInfo Info(NotificationErrorText);
Info.ExpireDuration = 2.0f;
FSlateNotificationManager::Get().AddNotification(Info);
}
}
void FBasicVolumeEditorViewportClient::InternalActivateNewMode(EBasicVolumeEditorMode NewMode)
{
CurrentMode = NewMode;
Viewport->InvalidateHitProxy();
UBasicVolume* Volume = GetVolumeBeingEdited();
switch (CurrentMode)
{
case EBasicVolumeEditorMode::ViewMode:
break;
case EBasicVolumeEditorMode::EditMode:
break;
}
}
#undef LOCTEXT_NAMESPACE
<commit_msg>clean up<commit_after>#include "VoreealEditorPrivatePCH.h"
#include "BasicVolumeEditorViewportClient.h"
#include "SceneViewport.h"
#include "PreviewScene.h"
#include "ScopedTransaction.h"
#include "Runtime/Engine/Public/ComponentReregisterContext.h"
#include "AssetToolsModule.h"
#include "ContentBrowserModule.h"
#include "AssetRegistryModule.h"
#include "CanvasTypes.h"
#include "CanvasItem.h"
#include "SEditorViewport.h"
#include "SNotificationList.h"
#include "NotificationManager.h"
#include "BasicVolumeEditorSettings.h"
#define LOCTEXT_NAMESPACE "VoreealEditor"
FBasicVolumeEditorViewportClient::FBasicVolumeEditorViewportClient(TWeakPtr<FBasicVolumeEditor> InEditor, TWeakPtr<class SEditorViewport> InEditorViewportPtr)
: CurrentMode(EBasicVolumeEditorMode::ViewMode)
, EditorPtr(InEditor)
, EditorViewportPtr(InEditorViewportPtr)
{
check(EditorPtr.IsValid() && EditorViewportPtr.IsValid());
Widget->SetUsesEditorModeTools(ModeTools);
PreviewScene = &OwnedPreviewScene;
((FAssetEditorModeManager*)ModeTools)->SetPreviewScene(PreviewScene);
SetRealtime(true);
bManipulating = false;
bManipulationDirtiedSomething = false;
ScopedTransaction = nullptr;
bShowOctree = true;
bShowSockets = true;
bShowPivot = true;
DrawHelper.bDrawGrid = GetDefault<UBasicVolumeEditorSettings>()->bShowGridByDefault;
EngineShowFlags.DisableAdvancedFeatures();
EngineShowFlags.SetCompositeEditorPrimitives(true);
// Create a render component for the volume being edited
{
RenderVolumeComponent = NewObject<UBasicVolumeComponent>();
UBasicVolume* Volume = GetVolumeBeingEdited();
RenderVolumeComponent->SetBasicVolume(Volume);
PreviewScene->AddComponent(RenderVolumeComponent, FTransform::Identity);
}
}
void FBasicVolumeEditorViewportClient::ActivateEditMode()
{
ModeTools->SetWidgetMode(FWidget::WM_Translate);
}
#pragma region // Begin Show Flags
void FBasicVolumeEditorViewportClient::SetShowOctree(bool bShow)
{
bShowOctree = !bShowOctree;
Invalidate();
}
void FBasicVolumeEditorViewportClient::ToggleShowOctree()
{
bShowOctree = !bShowOctree;
Invalidate();
}
bool FBasicVolumeEditorViewportClient::IsSetShowOctreeChecked() const
{
return bShowOctree;
}
void FBasicVolumeEditorViewportClient::ToggleShowSockets()
{
bShowSockets = !bShowSockets;
Invalidate();
}
bool FBasicVolumeEditorViewportClient::IsShowSocketsChecked() const
{
return bShowSockets;
}
void FBasicVolumeEditorViewportClient::ToggleShowPivot()
{
bShowPivot = !bShowPivot;
Invalidate();
}
bool FBasicVolumeEditorViewportClient::IsShowPivotChecked() const
{
return bShowPivot;
}
#pragma endregion
void FBasicVolumeEditorViewportClient::EnterViewMode()
{
InternalActivateNewMode(EBasicVolumeEditorMode::ViewMode);
}
void FBasicVolumeEditorViewportClient::EnterEditMode()
{
InternalActivateNewMode(EBasicVolumeEditorMode::EditMode);
}
bool FBasicVolumeEditorViewportClient::IsInViewMode() const
{
return CurrentMode == EBasicVolumeEditorMode::ViewMode;
}
bool FBasicVolumeEditorViewportClient::IsInEditMode() const
{
return CurrentMode == EBasicVolumeEditorMode::EditMode;
}
void FBasicVolumeEditorViewportClient::DrawCanvas(FViewport& pViewport, FSceneView& View, FCanvas& Canvas)
{
const bool bIsHitTesting = Canvas.IsHitTesting();
if (!bIsHitTesting)
{
Canvas.SetHitProxy(nullptr);
}
if (!EditorPtr.IsValid())
{
return;
}
UBasicVolume* Volume = GetVolumeBeingEdited();
switch (CurrentMode)
{
default:
case EBasicVolumeEditorMode::ViewMode:
break;
case EBasicVolumeEditorMode::EditMode:
break;
}
if (bShowSockets && !IsInEditMode())
{
//FSpriteGeometryEditMode* GeometryEditMode = ModeTools->GetActiveModeTyped<FSpriteGeometryEditMode>(FSpriteGeometryEditMode::EM_SpriteGeometry);
//FSocketEditingHelper::DrawSocketNames(GeometryEditMode, RenderVolumeComponent, Viewport, View, Canvas);
}
FEditorViewportClient::DrawCanvas(pViewport, View, Canvas);
}
void FBasicVolumeEditorViewportClient::Draw(const FSceneView* View, FPrimitiveDrawInterface* PDI)
{
FEditorViewportClient::Draw(View, PDI);
if (IsInEditMode())
{
if (bShowPivot)
{
const bool bCanSelectPivot = false;
const bool bHitTestingForPivot = PDI->IsHitTesting() && bCanSelectPivot;
FUnrealEdUtils::DrawWidget(View, PDI, RenderVolumeComponent->ComponentToWorld.ToMatrixWithScale(), 0, 0, EAxisList::XZ, EWidgetMovementMode::WMM_Translate, bHitTestingForPivot);
}
if (bShowSockets)
{
//FSpriteGeometryEditMode* GeometryEditMode = ModeTools->GetActiveModeTyped<FSpriteGeometryEditMode>(FSpriteGeometryEditMode::EM_SpriteGeometry);
//FSocketEditingHelper::DrawSockets(GeometryEditMode, RenderSpriteComponent, View, PDI);
}
}
}
FBox FBasicVolumeEditorViewportClient::GetDesiredFocusBounds() const
{
UBasicVolumeComponent* ComponentToFocusOn = RenderVolumeComponent;
return ComponentToFocusOn->Bounds.GetBox();
}
void FBasicVolumeEditorViewportClient::Tick(float DeltaSeconds)
{
if (UBasicVolume* Volume = GetVolumeBeingEdited())
{
}
FVoreealEditorViewportClient::Tick(DeltaSeconds);
// Draw the octree
if (bShowOctree && RenderVolumeComponent)
{
RenderVolumeComponent->DrawDebugOctree(FLinearColor::Red, 0, 1.0f);
}
if (!GIntraFrameDebuggingGameThread)
{
OwnedPreviewScene.GetWorld()->Tick(LEVELTICK_All, DeltaSeconds);
}
}
void FBasicVolumeEditorViewportClient::ProcessClick(FSceneView& View, HHitProxy* HitProxy, FKey Key, EInputEvent Event, uint32 HitX, uint32 HitY)
{
const FViewportClick Click(&View, this, Key, Event, HitX, HitY);
const bool bIsCtrlKeyDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl);
const bool bIsShiftKeyDown = Viewport->KeyState(EKeys::LeftShift) || Viewport->KeyState(EKeys::RightShift);
const bool bIsAltKeyDown = Viewport->KeyState(EKeys::LeftAlt) || Viewport->KeyState(EKeys::RightAlt);
bool bHandled = false;
if (!bHandled)
{
FVoreealEditorViewportClient::ProcessClick(View, HitProxy, Key, Event, HitX, HitY);
}
}
bool FBasicVolumeEditorViewportClient::InputKey(FViewport* pViewport, int32 ControllerId, FKey Key, EInputEvent Event, float AmountDepressed, bool bGamepad)
{
bool bHandled = false;
FInputEventState InputState(pViewport, Key, Event);
// Pass keys to standard controls, if we didn't consume input
return (bHandled) ? true : FEditorViewportClient::InputKey(pViewport, ControllerId, Key, Event, AmountDepressed, bGamepad);
}
void FBasicVolumeEditorViewportClient::TrackingStarted(const struct FInputEventState& InInputState, bool bIsDragging, bool bNudge)
{
// Begin transacting. Give the current editor mode an opportunity to do the transacting.
const bool bTrackingHandledExternally = ModeTools->StartTracking(this, Viewport);
if (!bManipulating && bIsDragging && !bTrackingHandledExternally)
{
bManipulating = true;
bManipulationDirtiedSomething = false;
}
}
void FBasicVolumeEditorViewportClient::TrackingStopped()
{
// Stop transacting. Give the current editor mode an opportunity to do the transacting.
const bool bTransactingHandledByEditorMode = ModeTools->EndTracking(this, Viewport);
if (bManipulating && !bTransactingHandledByEditorMode)
{
bManipulating = false;
}
}
FLinearColor FBasicVolumeEditorViewportClient::GetBackgroundColor() const
{
return FLinearColor::Black;
}
void FBasicVolumeEditorViewportClient::NotifyVolumeBeingEditedHasChanged()
{
// Refresh the viewport in case we were not in realtime mode
Invalidate();
// Update components to know about the new volume being edited
UBasicVolume* Volume = GetVolumeBeingEdited();
RenderVolumeComponent->SetBasicVolume(Volume);
InternalActivateNewMode(CurrentMode);
if (Volume != nullptr)
{
// Create and display a notification about the new volume being edited
const FText NotificationErrorText = FText::Format(LOCTEXT("SwitchingToVolume", "Editing {0}"), FText::AsCultureInvariant(Volume->GetName()));
FNotificationInfo Info(NotificationErrorText);
Info.ExpireDuration = 2.0f;
FSlateNotificationManager::Get().AddNotification(Info);
}
}
void FBasicVolumeEditorViewportClient::InternalActivateNewMode(EBasicVolumeEditorMode NewMode)
{
CurrentMode = NewMode;
Viewport->InvalidateHitProxy();
UBasicVolume* Volume = GetVolumeBeingEdited();
switch (CurrentMode)
{
case EBasicVolumeEditorMode::ViewMode:
break;
case EBasicVolumeEditorMode::EditMode:
break;
}
}
#undef LOCTEXT_NAMESPACE
<|endoftext|>
|
<commit_before>#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/mesh_segmentation.h>
#include <CGAL/property_map.h>
#include <iostream>
#include <fstream>
#include <string>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Polyhedron_3<K, CGAL::Polyhedron_items_with_id_3> Polyhedron;
// Property map associating a facet with an integer as id to an
// element in a vector stored internally
template<class ValueType>
struct Facet_with_id_pmap
: public boost::put_get_helper<ValueType&,
Facet_with_id_pmap<ValueType> >
{
typedef Polyhedron::Facet_const_handle key_type;
typedef ValueType value_type;
typedef value_type& reference;
typedef boost::lvalue_property_map_tag category;
Facet_with_id_pmap(
std::vector<ValueType>& internal_vector
) : internal_vector(internal_vector) { }
reference operator[](key_type key) const
{ return internal_vector[key->id()]; }
private:
std::vector<ValueType>& internal_vector;
};
int main(int argc,char* argv[])
{
typedef Polyhedron::Facet_iterator Facet_iterator;
typedef Polyhedron::Halfedge_around_facet_circulator Halfedge_facet_circulator;
std::string location;
std::string filePath;
// create and read Polyhedron
if (argc==1){
// TODO: Petteri, maybe change the paths when providing no arguments to something else
location= "/home/highschoolintern/Desktop/TestReconstruction2/testReconstruction_4slicesPhysical_reconstruction_isolatedRemoved_decimated.off";
filePath= "/home/highschoolintern/Desktop/SDFPropertyMap/build";
}else {
location= argv[1];
filePath= argv[2];
}
std::cout << location.c_str() << "\n";
Polyhedron mesh;
std::ifstream input(location.c_str());
if ( !input || !(input >> mesh) || mesh.empty() ) {
std::cerr << "Not a valid off file." << std::endl;
return EXIT_FAILURE;
}
// assign id field for each facet
std::size_t facet_id = 0;
for(Polyhedron::Facet_iterator facet_it = mesh.facets_begin();
facet_it != mesh.facets_end(); ++facet_it, ++facet_id) {
facet_it->id() = facet_id;
}
for ( Facet_iterator i = mesh.facets_begin(); i != mesh.facets_end(); ++i) {
Halfedge_facet_circulator j = i->facet_begin();
// Facets in polyhedral surfaces are at least triangles.
CGAL_assertion( CGAL::circulator_size(j) >= 3);
//std::cout << CGAL::circulator_size(j) << ' ';
do {
// std::cout << ' ' << std::distance(mesh.vertices_begin(), j->vertex());
} while ( ++j != i->facet_begin());
//std::cout << std::endl;
}
// create a property-map for SDF values
std::vector<double> sdf_values(mesh.size_of_facets());
Facet_with_id_pmap<double> sdf_property_map(sdf_values);
CGAL::sdf_values(mesh, sdf_property_map);
// access SDF values (with constant-complexity)
std::ofstream SDF(filePath.c_str());
SDF.open("SDFVals.txt");
for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
facet_it != mesh.facets_end(); ++facet_it) {
std::cout << sdf_property_map[facet_it] << " \n";
SDF << sdf_property_map[facet_it] << std::endl;
}
SDF.close();
std::cout << std::endl;
std::ofstream SDFfile;
// create a property-map for segment-ids
std::vector<std::size_t> segment_ids(mesh.size_of_facets());
Facet_with_id_pmap<std::size_t> segment_property_map(segment_ids);
CGAL::segmentation_from_sdf_values(mesh, sdf_property_map, segment_property_map);
// access segment-ids (with constant-complexity)
for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
facet_it != mesh.facets_end(); ++facet_it) {
std::cout << segment_property_map[facet_it] << " ";
}
std::cout << std::endl;
SDFfile.close();
}
<commit_msg>some comments added<commit_after>#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <CGAL/Polyhedron_items_with_id_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/mesh_segmentation.h>
#include <CGAL/property_map.h>
#include <iostream>
#include <fstream>
#include <string>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Polyhedron_3<K, CGAL::Polyhedron_items_with_id_3> Polyhedron;
// Property map associating a facet with an integer as id to an
// element in a vector stored internally
template<class ValueType>
struct Facet_with_id_pmap
: public boost::put_get_helper<ValueType&,
Facet_with_id_pmap<ValueType> >
{
typedef Polyhedron::Facet_const_handle key_type;
typedef ValueType value_type;
typedef value_type& reference;
typedef boost::lvalue_property_map_tag category;
Facet_with_id_pmap(
std::vector<ValueType>& internal_vector
) : internal_vector(internal_vector) { }
reference operator[](key_type key) const
{ return internal_vector[key->id()]; }
private:
std::vector<ValueType>& internal_vector;
};
int main(int argc,char* argv[])
{
typedef Polyhedron::Facet_iterator Facet_iterator;
typedef Polyhedron::Halfedge_around_facet_circulator Halfedge_facet_circulator;
std::string location;
std::string filePath;
// create and read Polyhedron
if (argc==1){
// TODO: Petteri, maybe change the paths when providing no arguments to something else
location= "/home/highschoolintern/Desktop/TestReconstruction2/testReconstruction_4slicesPhysical_reconstruction_isolatedRemoved_decimated.off";
filePath= "/home/highschoolintern/Desktop/SDFPropertyMap/build";
}else {
location= argv[1];
filePath= argv[2];
}
std::cout << location.c_str() << "\n";
Polyhedron mesh;
std::ifstream input(location.c_str());
if ( !input || !(input >> mesh) || mesh.empty() ) {
std::cerr << "Not a valid off file." << std::endl;
return EXIT_FAILURE;
}
// assign id field for each facet
std::size_t facet_id = 0;
for(Polyhedron::Facet_iterator facet_it = mesh.facets_begin();
facet_it != mesh.facets_end(); ++facet_it, ++facet_id) {
facet_it->id() = facet_id;
}
for ( Facet_iterator i = mesh.facets_begin(); i != mesh.facets_end(); ++i) {
Halfedge_facet_circulator j = i->facet_begin();
// Facets in polyhedral surfaces are at least triangles.
CGAL_assertion( CGAL::circulator_size(j) >= 3);
//std::cout << CGAL::circulator_size(j) << ' ';
do {
// std::cout << ' ' << std::distance(mesh.vertices_begin(), j->vertex());
} while ( ++j != i->facet_begin());
//std::cout << std::endl;
}
// create a property-map for SDF values
std::vector<double> sdf_values(mesh.size_of_facets());
Facet_with_id_pmap<double> sdf_property_map(sdf_values);
CGAL::sdf_values(mesh, sdf_property_map);
// access SDF values (with constant-complexity)
std::ofstream SDF(filePath.c_str());
SDF.open("SDFVals.txt");
for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
facet_it != mesh.facets_end(); ++facet_it) {
std::cout << sdf_property_map[facet_it] << " \n";
SDF << sdf_property_map[facet_it] << std::endl;
}
SDF.close();
std::cout << std::endl; // Printing the SDF values
std::ofstream SDFfile;
// create a property-map for segment-ids
std::vector<std::size_t> segment_ids(mesh.size_of_facets());
Facet_with_id_pmap<std::size_t> segment_property_map(segment_ids);
CGAL::segmentation_from_sdf_values(mesh, sdf_property_map, segment_property_map);
// access segment-ids (with constant-complexity)
for(Polyhedron::Facet_const_iterator facet_it = mesh.facets_begin();
facet_it != mesh.facets_end(); ++facet_it) {
std::cout << segment_property_map[facet_it] << " ";
}
std::cout << std::endl; // Printing the SDF Segment IDs
// These IDs could be saved to disk maybe as well, and used in piecewise denoising or something?
SDFfile.close();
}
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HTTP_METHODS_HPP
#define HTTP_METHODS_HPP
#include <array>
#include <string>
#include <ostream>
namespace http {
enum Method {
GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, CONNECT, PATCH,
INVALID = 0xffff
};
namespace method {
/** Get method string from method code **/
inline const std::string& str(const Method m) {
static std::array<std::string, 10> strings
{
{
"GET", "POST", "PUT", "DELETE", "OPTIONS",
"HEAD", "TRACE", "CONNECT", "PATCH", "INVALID"
}
};
if ((m >= 0) and (m < (strings.size() - 1))) {
return strings[m];
}
return strings[strings.size() - 1];
}
/**
* Get a code mapping from an HTTP
* method
*
* @param method - The HTTP method
*
* @return - The code mapped to the method
**/
inline Method code(const std::string& method) noexcept {
if (method == str(GET)) return GET;
if (method == str(POST)) return POST;
if (method == str(PUT)) return PUT;
if (method == str(DELETE)) return DELETE;
if (method == str(OPTIONS)) return OPTIONS;
if (method == str(HEAD)) return HEAD;
if (method == str(TRACE)) return TRACE;
if (method == str(CONNECT)) return CONNECT;
if (method == str(PATCH)) return PATCH;
return INVALID;
}
} // namespace method
std::ostream& operator << (std::ostream& output_device, const Method m) {
return output_device << http::method::str(m);
}
} // namespace http
#endif // HTTP_METHODS_HPP
<commit_msg>Inlined function since it resides in a header...<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HTTP_METHODS_HPP
#define HTTP_METHODS_HPP
#include <array>
#include <string>
#include <ostream>
namespace http {
enum Method {
GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, CONNECT, PATCH,
INVALID = 0xffff
};
namespace method {
/** Get method string from method code **/
inline const std::string& str(const Method m) {
static std::array<std::string, 10> strings
{
{
"GET", "POST", "PUT", "DELETE", "OPTIONS",
"HEAD", "TRACE", "CONNECT", "PATCH", "INVALID"
}
};
if ((m >= 0) and (m < (strings.size() - 1))) {
return strings[m];
}
return strings[strings.size() - 1];
}
/**
* Get a code mapping from an HTTP
* method
*
* @param method - The HTTP method
*
* @return - The code mapped to the method
**/
inline Method code(const std::string& method) noexcept {
if (method == str(GET)) return GET;
if (method == str(POST)) return POST;
if (method == str(PUT)) return PUT;
if (method == str(DELETE)) return DELETE;
if (method == str(OPTIONS)) return OPTIONS;
if (method == str(HEAD)) return HEAD;
if (method == str(TRACE)) return TRACE;
if (method == str(CONNECT)) return CONNECT;
if (method == str(PATCH)) return PATCH;
return INVALID;
}
} // namespace method
inline std::ostream& operator << (std::ostream& output_device, const Method m) {
return output_device << http::method::str(m);
}
} // namespace http
#endif // HTTP_METHODS_HPP
<|endoftext|>
|
<commit_before>#include "text.h"
#include <vector>
#include <memory>
using std::move;
using std::vector;
using std::unique_ptr;
using std::ostream;
TextSlice::TextSlice(Text &text) : text{&text}, start_index{0}, end_index{text.size()} {}
TextSlice::TextSlice(Text *text, size_t start_index, size_t end_index)
: text{text}, start_index{start_index}, end_index{end_index} {}
Text::iterator TextSlice::begin() {
return text->begin() + start_index;
}
size_t TextSlice::size() {
return end_index - start_index;
}
Text::iterator TextSlice::end() {
return text->begin() + end_index;
}
Text TextSlice::Concat(TextSlice a, TextSlice b) {
Text result;
result.reserve(a.size() + b.size());
result.insert(
result.end(),
a.begin(),
a.end()
);
result.insert(
result.end(),
b.begin(),
b.end()
);
return result;
}
Text TextSlice::Concat(TextSlice a, TextSlice b, TextSlice c) {
Text result;
result.reserve(a.size() + b.size() + c.size());
result.insert(
result.end(),
a.begin(),
a.end()
);
result.insert(
result.end(),
b.begin(),
b.end()
);
result.insert(
result.end(),
c.begin(),
c.end()
);
return result;
}
TextSlice::operator Text() const {
return Text(text->begin() + start_index, text->begin() + end_index);
}
std::pair<TextSlice, TextSlice> TextSlice::Split(Point position) {
size_t index = CharacterIndexForPosition(position);
return {
TextSlice{text, start_index, start_index + index},
TextSlice{text, start_index + index, end_index}
};
}
TextSlice TextSlice::Suffix(Point suffix_start) {
return Split(suffix_start).second;
}
TextSlice TextSlice::Prefix(Point prefix_end) {
return Split(prefix_end).first;
}
size_t TextSlice::CharacterIndexForPosition(Point target) {
Point position;
auto begin = text->begin() + start_index;
auto end = text->begin() + end_index;
auto iter = begin;
while (iter != end && position < target) {
if (*iter == '\n') {
position.row++;
position.column = 0;
} else {
position.column++;
}
++iter;
}
return iter - begin;
}
ostream &operator<<(ostream &stream, const Text *text) {
if (text) {
stream << "'";
for (uint16_t character : *text) {
if (character < CHAR_MAX) {
stream << (char)character;
} else {
stream << "\\u" << character;
}
}
stream << "'";
return stream;
} else {
return stream << "null";
}
}
<commit_msg>Include limits.h for CHAR_MAX<commit_after>#include "text.h"
#include <limits.h>
#include <vector>
#include <memory>
using std::move;
using std::vector;
using std::unique_ptr;
using std::ostream;
TextSlice::TextSlice(Text &text) : text{&text}, start_index{0}, end_index{text.size()} {}
TextSlice::TextSlice(Text *text, size_t start_index, size_t end_index)
: text{text}, start_index{start_index}, end_index{end_index} {}
Text::iterator TextSlice::begin() {
return text->begin() + start_index;
}
size_t TextSlice::size() {
return end_index - start_index;
}
Text::iterator TextSlice::end() {
return text->begin() + end_index;
}
Text TextSlice::Concat(TextSlice a, TextSlice b) {
Text result;
result.reserve(a.size() + b.size());
result.insert(
result.end(),
a.begin(),
a.end()
);
result.insert(
result.end(),
b.begin(),
b.end()
);
return result;
}
Text TextSlice::Concat(TextSlice a, TextSlice b, TextSlice c) {
Text result;
result.reserve(a.size() + b.size() + c.size());
result.insert(
result.end(),
a.begin(),
a.end()
);
result.insert(
result.end(),
b.begin(),
b.end()
);
result.insert(
result.end(),
c.begin(),
c.end()
);
return result;
}
TextSlice::operator Text() const {
return Text(text->begin() + start_index, text->begin() + end_index);
}
std::pair<TextSlice, TextSlice> TextSlice::Split(Point position) {
size_t index = CharacterIndexForPosition(position);
return {
TextSlice{text, start_index, start_index + index},
TextSlice{text, start_index + index, end_index}
};
}
TextSlice TextSlice::Suffix(Point suffix_start) {
return Split(suffix_start).second;
}
TextSlice TextSlice::Prefix(Point prefix_end) {
return Split(prefix_end).first;
}
size_t TextSlice::CharacterIndexForPosition(Point target) {
Point position;
auto begin = text->begin() + start_index;
auto end = text->begin() + end_index;
auto iter = begin;
while (iter != end && position < target) {
if (*iter == '\n') {
position.row++;
position.column = 0;
} else {
position.column++;
}
++iter;
}
return iter - begin;
}
ostream &operator<<(ostream &stream, const Text *text) {
if (text) {
stream << "'";
for (uint16_t character : *text) {
if (character < CHAR_MAX) {
stream << (char)character;
} else {
stream << "\\u" << character;
}
}
stream << "'";
return stream;
} else {
return stream << "null";
}
}
<|endoftext|>
|
<commit_before>/** \mainpage
# Contents
- Overview
- Requirements
- Building
- Design and Rationale
- Examples
# Overview
This library consists of a set of templated functions for doing basic arithmetic
operations on ranges and containers. It assumes that the elements of the
ranges/containers support the arithmetic operators: +, -, *, /.
From a mathematical point of view it works on vector spaces in arbitrary dimensions.
It does not define any specific data structure for the vectors.
Instead it provides functions that implement vector space operations
for arbitrary ranges/containers.
The library consists of the modules:
- **Vector space operations**. This module defines the algorithms:
- **add**. Does elementwise addition of either two ranges/containers,
or a scalar and a range/container.
- **subtract**. Does elementwise subtraction of either two ranges/containers,
or a scalar and a range/container.
- **negate**. Does elementwise negation of a range/container.
- **multiply**. Does elementwise multiplication of either two ranges/containers,
or a scalar and a range/container.
- **divide**. Does elementwise division of either two ranges/containers,
or a scalar and a range/container.
- **Euclidean space operations**. This module defines the algorithms:
- **norm**. Computes the Euclidean norm of a range/container.
- **squared_norm**. Computes the squared Euclidean norm of a range/container.
- **dot**. Computes the Euclidean inner product of two ranges/containers.
- **distance**. Computes the Euclidean distance of two ranges/containers.
- **squared_distance**. Computes the squared Euclidean distance of two
ranges/containers.
- **Taxicab space operations**. This module defines the algorithms:
- **norm_l1**. Computes the Taxicab/Manhattan/L1 norm of a range/container.
- **squared_norm_l1**. Computes the squared Taxicab/Manhattan/L1 norm of a range/container.
- **distance_l1**. Computes the Taxicab/Manhattan/L1 distance of two ranges/containers.
- **squared_distance_l1**. Computes the squared Taxicab/Manhattan/L1 distance of two
ranges/containers.
- **Chebyshev space operations**. This module defines the algorithms:
- **norm_max**. Computes the Chebyshev/Infinity/Max norm of a range/container.
- **squared_norm_max**. Computes the squared Chebyshev/Infinity/Max norm of a range/container.
- **distance_max**. Computes the Chebyshev/Infinity/Max distance of two ranges/containers.
- **squared_distance_max**. Computes the squared Chebyshev/Infinity/Max distance of two
ranges/containers.
- **Misc algorithms**. This module defines the aglorithms:
- **sum**. Computes the sum of the elements of a range/container.
- **convert**. Does elementwise `static_cast` on the elements from one
range/container to another range/container.
- **STD algorithms**. This module defines container versions of some range
algorithms from the standard library header `<algorithm>`. It only does it for
the algorithms that are used a lot for arithmetic types:
- **copy**.
- **fill**.
- **min_element**.
- **max_element**.
- **minmax_element**.
- **Logical operations**. This module works on Ranges/Containers with elements
of type `bool`. The module defines the algorithms:
- **logical_and**. Does elementwise boolean `and` on two ranges/containers.
- **logical_or**. Does elementwise boolean `or` on two ranges/containers.
- **logical_not**. Does elementwise boolean `not` on a range/container.
Go to the **Modules** pages to learn more about each module.
# Requirements
All the functions of this library assume that the input and output is:
- Either ranges of iterators, or standard like containers, i.e. they have begin
and end functions that give iterators.
- The elements of the ranges/containers should support arithmetic operations:
+, -, *, /. The functions in the module *Logical Operations* is the only
exception to this. It assumes that the elements have type `bool`.
# Building
The library is header only, which makes it easy to use and build. Download it
and add it to the include directory of your project and `#include <aaa.hpp>`.
# Design and Rationale
This library deals with arithmetic operations on mathematical vectors,
represented as ranges or containers.
It is designed for vectors in arbitrary dimensions. It is NOT optimized for small
vectors, which you typically use to represent geometry in 2D and 3D. For that
use case it might be more optimal to use other libraries like:
[GLM](http://glm.g-truc.net/) and [Eigen](http://eigen.tuxfamily.org/).
C++ libraries that deals with mathematical vectors in arbitrary dimensions
can usually be divided into two categories:
-# Those that implement a vector class and overload its arithmetic operators.
Examples of this are:
[std::valarray](http://www.cplusplus.com/reference/valarray/),
[Eigen](http://eigen.tuxfamily.org/),
[Blitz++](https://sourceforge.net/projects/blitz/),
[OpenCV](http://opencv.org/).
-# Those that implement general algorithms that work on any container or
range of iterators. An example of this is the standard library and the headers
[algorithm](http://www.cplusplus.com/reference/algorithm/)
and [numeric](http://www.cplusplus.com/reference/numeric/).
This library follows the second approach. It implements some common arithmetic
algorithms that are missing in the standard library.
The two approaches have different advantages and disadvantages:
-# The advantage of the first approach is that the syntax can be very concise,
when you overload the arithmetic operators to act directly on the vector class.
This approach can also have performance advantages, since it couples the
algorithm to the data structure. It is then possible to use techniques
like *expression templates* or *aligned memory* and *vectorization*.
-# The advantage of the second approach is that it allows *generic programming*.
Code that uses such libraries is more general since it is less coupled to a
specific data structure. This is good for readability and reuse of the code.
# Examples
The algorithms can be used on arbitrary containers like this:
```
// Blend two images.
void blend(const Image& in1, const Image& in2, Image& out)
{
using namespace aaa;
add(in1, in2, out); // Add the images together elementwise.
divide(out, 2, out);// Divide the result elementwise with 2 to get the mean image.
}
// Returns the projection of a on b.
std::vector<float> project(const std::vector<float>& a, const std::vector<float>& b)
{
using namespace aaa;
// First we compute the scaling factor of the projection by taking the dot
// product of the vectors. We normalize with the squared_norm of the vector
// that we are projecting on.
const auto scaling = dot(a, b) / squared_norm(b);
// The projection of a on b is like b,
// but multiplied elementwise with the scaling factor.
auto projection = b;
multiply(scaling, b, projection);
return projection;
}
```
*/
// TODO: should the elements be passed by value or const reference?
#pragma once
#include "std_algorithms_container.hpp"
#include "algorithms_range.hpp"
#include "algorithms_container.hpp"
#include "vector_space_range.hpp"
#include "vector_space_container.hpp"
#include "vector_space_functional.hpp"
#include "euclidean_space_range.hpp"
#include "euclidean_space_container.hpp"
#include "taxicab_space_range.hpp"
#include "taxicab_space_container.hpp"
#include "chebyshev_space_range.hpp"
#include "chebyshev_space_container.hpp"
#include "logical_range.hpp"
#include "logical_container.hpp"
#include "logical_functional.hpp"
<commit_msg>Update documentation<commit_after>/** \mainpage
# Contents
- Overview
- Requirements
- Building
- Design and Rationale
- Examples
# Overview
This library consists of a set of templated functions for doing basic arithmetic
operations on containers and ranges of iterators. The elements of the
ranges/containers can be any built in aritmetic type, e.g.
`float`, `double`, `int`, or any other type that supports the arithmetic
operations: +, -, *, /. We refer to a range/container of arithmetic elements as
a mathematical vector. This library defines vector operations for arbitrary
finite vector spaces. This library does not define any specific data structure
for the vectors, but operates on general vectors/ranges/containers.
The library consists of different modules:
- **General operations for vector spaces**.
This includes various versions of the functions: `add`, `subtract`, `negate`, `multiply`, `divide`.
- **Norms and metrics for vector spaces**.
This includes various versions of the functions: `norm`, `distance`, `squared_norm`, `squared_distance`.
The norms and distances are defined for the following vectors spaces:
`eclidean` (L2), `tacixab` (L1), `chebyshev` (L-infinity).
- **Misc algorithms**. `sum`, `convert`.
- **Logical operations**. `logical_and`, `logical_or`, `logical_not`.
- **STD algorithms**. `fill`, `copy`, `min_element`, `max_element`, `minmax_element`.
## General Operations for Vector Spaces
This module defines elementwise arithmetic operations on vectors.
The input is two vectors/ranges/containers and the output is one vector/range/container.
- **add**. Does elementwise addition of either two vectors/ranges/containers,
or a scalar and a vector/range/container.
- **subtract**. Does elementwise subtraction of either two vector/ranges/containers,
or a scalar and a vector/range/container.
- **negate**. Does elementwise negation of a single vector/range/container.
- **multiply**. Does elementwise multiplication of either two vector/ranges/containers,
or a scalar and a vector/range/container.
- **divide**. Does elementwise division of either two vectors/ranges/containers,
or a scalar and a vector/range/container.
## Norms and Metrics for Vector Spaces
This module defines norms/lengths and metrics/distances for vectors.
These functions take one or two vectors/ranges/containers and returns a
single scalar:
- **norm**. Computes the norm/magnitude/length of a vecor/range/container.
- **distance**. Computes the distance of two vectors/ranges/containers.
- **squared_norm**. Computes the squared norm of a vector/range/container.
- **squared_distance**. Computes the squared distance of two
vectors/ranges/containers.
- **dot**. Computes the the dot-product of two vecors/ranges/containers.
We consider three different kinds of vector spaces: `euclidean` (L2),
`taxicab` (L1), `chebyshev` (L-infinity). Each kind of vector spaces has its
own namespace, with its own versions of the functions above in it.
However, the `dot` product is only defined for `euclidean` vector spaces.
All the functions in this module assume that the default construction of a
scalar gives zero, which is true for the built-in arithmetic types.
## Misc algorithms
This module defines the aglorithms:
- **sum**. Computes the sum of the elements of a range/container.
It assume that the default construction of a scalar gives zero,
which is true for the built-in arithmetic types.
- **convert**. Does elementwise `static_cast` on the elements from one
range/container to another range/container.
##Logical operations
This module works on ranges/containers with elements of type `bool`,
or any other type that supports the the boolean operations &&, ||, !.
The input is one or two ranges/containers and the output is a single
range/container.
- **logical_and**. Does elementwise boolean `and` on two ranges/containers.
- **logical_or**. Does elementwise boolean `or` on two ranges/containers.
- **logical_not**. Does elementwise boolean `not` on a single range/container.
##STD algorithms
This module defines container versions of some range
algorithms from the standard library header `<algorithm>`. It only does it for
the algorithms that are used a lot for arithmetic types:
- **copy**.
- **fill**.
- **min_element**.
- **max_element**.
- **minmax_element**.
Go to the **Modules** pages to learn more about each module.
# Requirements
All the functions of this library assume that the input and output is:
- Either ranges of iterators, or standard like containers, i.e. they have begin
and end functions that give iterators.
- The elements of the ranges/containers should support arithmetic operations:
+, -, *, /. The functions in the module *Logical Operations* is the only
exception to this. It assumes that the elements support the boolean operations
&&, ||, !.
- The functions in the norms and metrics module assume that the default
construction of a scalar gives zero, which is true for the built-in arithmetic
types. The function `sum` also assumes this.
# Building
The library is header only, which makes it easy to use and build. Download it
and add it to the include directory of your project and `#include <aaa.hpp>`.
# Design and Rationale
This library deals with arithmetic operations on mathematical vectors,
represented as ranges or containers.
It is designed for vectors in arbitrary dimensions. It is NOT optimized for small
vectors, which you typically use to represent geometry in 2D and 3D. For that
use case it might be more optimal to use other libraries like:
[GLM](http://glm.g-truc.net/) and [Eigen](http://eigen.tuxfamily.org/).
C++ libraries that deals with mathematical vectors in arbitrary dimensions
can usually be divided into two categories:
-# Those that implement a vector class and overload its arithmetic operators.
Examples of this are:
[std::valarray](http://www.cplusplus.com/reference/valarray/),
[Eigen](http://eigen.tuxfamily.org/),
[Blitz++](https://sourceforge.net/projects/blitz/),
[OpenCV](http://opencv.org/).
-# Those that implement general algorithms that work on any container or
range of iterators. An example of this is the standard library and the headers
[algorithm](http://www.cplusplus.com/reference/algorithm/)
and [numeric](http://www.cplusplus.com/reference/numeric/).
This library follows the second approach. It implements some common arithmetic
algorithms that are missing in the standard library.
The two approaches have different advantages and disadvantages:
-# The advantage of the first approach is that the syntax can be very concise,
when you overload the arithmetic operators to act directly on the vector class.
This approach can also have performance advantages, since it couples the
algorithm to the data structure. It is then possible to use techniques
like *expression templates* or *aligned memory* and *vectorization*.
-# The advantage of the second approach is that it allows *generic programming*.
Code that uses such libraries is more general since it is less coupled to a
specific data structure. This is good for readability and reuse of the code.
# Examples
The algorithms can be used on arbitrary containers like this:
```
// Blend two images.
void blend(const Image& in1, const Image& in2, Image& out)
{
using namespace aaa;
add(in1, in2, out); // Add the images together elementwise.
divide(out, 2, out);// Divide the result elementwise with 2 to get the mean image.
}
// Returns the projection of a on b.
std::vector<float> project(const std::vector<float>& a, const std::vector<float>& b)
{
using namespace aaa::euclidean;
// First we compute the scaling factor of the projection by taking the dot
// product of the vectors. We normalize with the squared_norm of the vector
// that we are projecting on.
const auto scaling = dot(a, b) / squared_norm(b);
// The projection of a on b is like b,
// but multiplied elementwise with the scaling factor.
auto projection = b;
multiply(scaling, b, projection);
return projection;
}
```
*/
// TODO: should the elements be passed by value or const reference?
#pragma once
#include "std_algorithms_container.hpp"
#include "algorithms_range.hpp"
#include "algorithms_container.hpp"
#include "vector_space_range.hpp"
#include "vector_space_container.hpp"
#include "vector_space_functional.hpp"
#include "euclidean_space_range.hpp"
#include "euclidean_space_container.hpp"
#include "taxicab_space_range.hpp"
#include "taxicab_space_container.hpp"
#include "chebyshev_space_range.hpp"
#include "chebyshev_space_container.hpp"
#include "logical_range.hpp"
#include "logical_container.hpp"
#include "logical_functional.hpp"
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdDatabaseModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdDatasetModel.h"
#include "mvdI18nApplication.h"
namespace mvd
{
/*
TRANSLATOR mvd::DatabaseModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
DatabaseModel
::DatabaseModel( QObject* parent ) :
AbstractModel( parent ),
m_DatasetModels(),
m_SelectedDatasetModel( NULL )
{
}
/*******************************************************************************/
DatabaseModel
::~DatabaseModel()
{
}
/*******************************************************************************/
QStringList
DatabaseModel
::ListAvailableDatasets() const
{
QDir cacheDir( I18nApplication::ConstInstance()->GetCacheDir() );
QStringList nameFilters;
nameFilters << QString( "*%1" ).arg( I18nApplication::DATASET_EXT );
return cacheDir.entryList(
nameFilters,
QDir::Dirs | QDir::NoDotAndDotDot,
QDir::Name
);
}
/*******************************************************************************/
StringPairListType
DatabaseModel
::QueryDatasetModels() const
{
StringPairListType list;
// need to send a list of pairs <alias, id> to know what is the
// corresponding model to each alias in the WidgetTree
DatasetModelMap::const_iterator it = m_DatasetModels.begin();
while( it != m_DatasetModels.end() )
{
// store alias <-> name
StringPairType spair;
spair.first = it.value()->GetAlias();
spair.second = it.value()->GetName();
// insert the pair in the list
list.append( spair);
++it;
}
return list;
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::SelectDatasetModel( const DatasetId& id )
{
qDebug() << this << "::SelectDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = FindDatasetModel( id );
assert( datasetModel!=NULL );
try
{
// Load dataset sub-models.
datasetModel->LoadImageModels( -1, -1 );
// If dataset model has been loaded, select it.
SetSelectedDatasetModel( datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
DatabaseModel::DatasetId
DatabaseModel
::RegisterDatasetModel( DatasetModel* model )
{
assert( model!=NULL );
// Construct DatasetId.
DatasetId id( model->GetName() );
// Find possible previously registerd dataset-model...
DatasetModelMap::iterator it( m_DatasetModels.find( id ) );
if( it!=m_DatasetModels.end() )
{
// BUGFIX: Clear selected dataset-model if it is to be deleted below.
if( it.value()==m_SelectedDatasetModel )
{
SetSelectedDatasetModel( NULL );
}
// ...and destroy it.
delete it.value();
it.value() = NULL;
}
// Insert new dataset-model...
it = m_DatasetModels.insert( id, model );
// Re-parent dataset-model.
model->setParent( this );
// Signal model has changed.
emit DatabaseChanged();
// Return registered ID.
return id;
}
/*******************************************************************************/
void
DatabaseModel
::ReleaseDatasetModel( const DatasetId& id )
{
qDebug() << this << "::ReleaseDatasetModel(" << id << ")";
// Find (key, value) pair.
DatasetModelMap::iterator it( DatasetModelIterator( id ) );
// release model
delete it.value();
it.value() = NULL;
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::NewDatasetModel( const DatasetId& id )
{
qDebug() << this << "::NewDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = NULL;
// Otherwise, load it from disk.
try
{
// Create empty dataset model.
datasetModel = new DatasetModel( this );
// Build dataset model.
assert( I18nApplication::ConstInstance() );
DatasetModel::BuildContext context(
I18nApplication::ConstInstance()->GetCacheDir().path(),
id,
id,
false
);
datasetModel->BuildModel( &context );
}
catch( std::exception& exc )
{
// If loading was interrupted, delete allocated memory.
delete datasetModel;
datasetModel = NULL;
// And forward interrupting exception.
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
void
DatabaseModel
::virtual_BuildModel( void* context )
{
InitializeDatasetModels();
}
/*******************************************************************************/
void
DatabaseModel
::InitializeDatasetModels()
{
QStringList datasets( ListAvailableDatasets() );
ClearDatasetModels();
for( QStringList::const_iterator it( datasets.begin() );
it!=datasets.end();
++it )
{
try
{
DatasetModel* datasetModel = NewDatasetModel( *it );
assert( datasetModel!=NULL );
// by default alias == name
m_DatasetModels.insert( datasetModel->GetName(), datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
}
}
/*******************************************************************************/
void
DatabaseModel
::ClearDatasetModels()
{
while( !m_DatasetModels.empty() )
{
DatasetModelMap::iterator it( m_DatasetModels.begin() );
delete it.value();
it.value() = NULL;
it = m_DatasetModels.erase( it );
}
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
DatabaseModel
::OnDatasetToDeleteSelected( const QString& id)
{
// pop up a Dialog widget to confirm the user choice
QMessageBox msgBox;
msgBox.setWindowTitle( tr( "Warning") );
msgBox.setText(tr("You are about to remove the dataset : \n %1 \n\n"
" Are your sure ? ").arg(id) );
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int ret = msgBox.exec();
// if choice confirmed
if (ret == QMessageBox::Yes)
{
qDebug() << this << " ::OnDatasetToDeleteSelected -> About to remove : "<< id;
// if current selected item is removed, make the TreeWidget
// focusing on the root item
if ( FindDatasetModel( id ) == GetSelectedDatasetModel() )
{
// set the Tree browser to point on nothing
emit CurrentSelectedItemDeleted();
//
SetSelectedDatasetModel( NULL );
}
// get the full path to the dataset dir
QDir datasetQDir(
I18nApplication::Instance()->GetCacheDir().absolutePath() +
"/" +
id
);
QString datasetDir = datasetQDir.absolutePath();
//
// remove the files in this directory
bool removingFilesStatus = true;
QStringList fileList = datasetQDir.entryList( QDir::NoDotAndDotDot | QDir::Files );
for( int i = 0; i < fileList.count(); ++i )
{
qDebug()<< "Removing file "<< fileList.at(i);
removingFilesStatus &= datasetQDir.remove( fileList.at(i) );
}
// go to parent dir
QDir datasetQDirParent = datasetQDir;
datasetQDirParent.cdUp();
// if path removed successfuly :
// - release dataset model
// - notify change to update the database browser
if ( removingFilesStatus && datasetQDirParent.rmpath( datasetDir ) )
{
qDebug() << this
<< " ::OnDatasetToDeleteSelected -> Removing : "
<< datasetQDir.absolutePath();
// release the model relative to 'id'
ReleaseDatasetModel( id );
// remove the key from the map
m_DatasetModels.remove( id );
// notify database changed
emit DatabaseChanged();
}
// rmpath() removes the parent directory (i.e mvd2 ) when no files
// (datasets ) in it -> recreate "mvd2" if removed
// TODO : find a better solution to replace this hack
if (! datasetQDirParent.exists() )
{
qDebug() << this<< "::OnDatasetToDeleteSelected Making removed dir "
<< datasetQDirParent.absolutePath();
datasetQDirParent.mkpath( datasetQDirParent.absolutePath() );
}
}
}
/*******************************************************************************/
void
DatabaseModel
::OnDatasetRenamed( const QString& alias, const QString & id)
{
// get the model relative to the previous key
DatasetModel * datasetModel = FindDatasetModel(id);
// update the alias
datasetModel->SetAlias( alias );
}
} // end namespace 'mvd'
<commit_msg>ENH: use the dataset alias in the popup<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdDatabaseModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdDatasetModel.h"
#include "mvdI18nApplication.h"
namespace mvd
{
/*
TRANSLATOR mvd::DatabaseModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
DatabaseModel
::DatabaseModel( QObject* parent ) :
AbstractModel( parent ),
m_DatasetModels(),
m_SelectedDatasetModel( NULL )
{
}
/*******************************************************************************/
DatabaseModel
::~DatabaseModel()
{
}
/*******************************************************************************/
QStringList
DatabaseModel
::ListAvailableDatasets() const
{
QDir cacheDir( I18nApplication::ConstInstance()->GetCacheDir() );
QStringList nameFilters;
nameFilters << QString( "*%1" ).arg( I18nApplication::DATASET_EXT );
return cacheDir.entryList(
nameFilters,
QDir::Dirs | QDir::NoDotAndDotDot,
QDir::Name
);
}
/*******************************************************************************/
StringPairListType
DatabaseModel
::QueryDatasetModels() const
{
StringPairListType list;
// need to send a list of pairs <alias, id> to know what is the
// corresponding model to each alias in the WidgetTree
DatasetModelMap::const_iterator it = m_DatasetModels.begin();
while( it != m_DatasetModels.end() )
{
// store alias <-> name
StringPairType spair;
spair.first = it.value()->GetAlias();
spair.second = it.value()->GetName();
// insert the pair in the list
list.append( spair);
++it;
}
return list;
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::SelectDatasetModel( const DatasetId& id )
{
qDebug() << this << "::SelectDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = FindDatasetModel( id );
assert( datasetModel!=NULL );
try
{
// Load dataset sub-models.
datasetModel->LoadImageModels( -1, -1 );
// If dataset model has been loaded, select it.
SetSelectedDatasetModel( datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
DatabaseModel::DatasetId
DatabaseModel
::RegisterDatasetModel( DatasetModel* model )
{
assert( model!=NULL );
// Construct DatasetId.
DatasetId id( model->GetName() );
// Find possible previously registerd dataset-model...
DatasetModelMap::iterator it( m_DatasetModels.find( id ) );
if( it!=m_DatasetModels.end() )
{
// BUGFIX: Clear selected dataset-model if it is to be deleted below.
if( it.value()==m_SelectedDatasetModel )
{
SetSelectedDatasetModel( NULL );
}
// ...and destroy it.
delete it.value();
it.value() = NULL;
}
// Insert new dataset-model...
it = m_DatasetModels.insert( id, model );
// Re-parent dataset-model.
model->setParent( this );
// Signal model has changed.
emit DatabaseChanged();
// Return registered ID.
return id;
}
/*******************************************************************************/
void
DatabaseModel
::ReleaseDatasetModel( const DatasetId& id )
{
qDebug() << this << "::ReleaseDatasetModel(" << id << ")";
// Find (key, value) pair.
DatasetModelMap::iterator it( DatasetModelIterator( id ) );
// release model
delete it.value();
it.value() = NULL;
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::NewDatasetModel( const DatasetId& id )
{
qDebug() << this << "::NewDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = NULL;
// Otherwise, load it from disk.
try
{
// Create empty dataset model.
datasetModel = new DatasetModel( this );
// Build dataset model.
assert( I18nApplication::ConstInstance() );
DatasetModel::BuildContext context(
I18nApplication::ConstInstance()->GetCacheDir().path(),
id,
id,
false
);
datasetModel->BuildModel( &context );
}
catch( std::exception& exc )
{
// If loading was interrupted, delete allocated memory.
delete datasetModel;
datasetModel = NULL;
// And forward interrupting exception.
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
void
DatabaseModel
::virtual_BuildModel( void* context )
{
InitializeDatasetModels();
}
/*******************************************************************************/
void
DatabaseModel
::InitializeDatasetModels()
{
QStringList datasets( ListAvailableDatasets() );
ClearDatasetModels();
for( QStringList::const_iterator it( datasets.begin() );
it!=datasets.end();
++it )
{
try
{
DatasetModel* datasetModel = NewDatasetModel( *it );
assert( datasetModel!=NULL );
// by default alias == name
m_DatasetModels.insert( datasetModel->GetName(), datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
}
}
/*******************************************************************************/
void
DatabaseModel
::ClearDatasetModels()
{
while( !m_DatasetModels.empty() )
{
DatasetModelMap::iterator it( m_DatasetModels.begin() );
delete it.value();
it.value() = NULL;
it = m_DatasetModels.erase( it );
}
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
DatabaseModel
::OnDatasetToDeleteSelected( const QString& id)
{
// get the datasetModel to be deleted
DatasetModel * model = FindDatasetModel( id );
assert (model!=NULL);
// pop up a Dialog widget to confirm the user choice
QMessageBox msgBox;
msgBox.setWindowTitle( tr( "Warning") );
msgBox.setText(tr("You are about to remove the dataset : \n %1 \n\n"
" Are your sure ? ").arg( model->GetAlias() ) );
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int ret = msgBox.exec();
// if choice confirmed
if (ret == QMessageBox::Yes)
{
qDebug() << this << " ::OnDatasetToDeleteSelected -> About to remove : "<< id;
// if current selected item is removed, make the TreeWidget
// focusing on the root item
if (model == GetSelectedDatasetModel() )
{
// set the Tree browser to point on nothing
emit CurrentSelectedItemDeleted();
//
SetSelectedDatasetModel( NULL );
}
// get the full path to the dataset dir
QDir datasetQDir(
I18nApplication::Instance()->GetCacheDir().absolutePath() +
"/" +
id
);
QString datasetDir = datasetQDir.absolutePath();
//
// remove the files in this directory
bool removingFilesStatus = true;
QStringList fileList = datasetQDir.entryList( QDir::NoDotAndDotDot | QDir::Files );
for( int i = 0; i < fileList.count(); ++i )
{
qDebug()<< "Removing file "<< fileList.at(i);
removingFilesStatus &= datasetQDir.remove( fileList.at(i) );
}
// go to parent dir
QDir datasetQDirParent = datasetQDir;
datasetQDirParent.cdUp();
// if path removed successfuly :
// - release dataset model
// - notify change to update the database browser
if ( removingFilesStatus && datasetQDirParent.rmpath( datasetDir ) )
{
qDebug() << this
<< " ::OnDatasetToDeleteSelected -> Removing : "
<< datasetQDir.absolutePath();
// release the model relative to 'id'
ReleaseDatasetModel( id );
// remove the key from the map
m_DatasetModels.remove( id );
// notify database changed
emit DatabaseChanged();
}
// rmpath() removes the parent directory (i.e mvd2 ) when no files
// (datasets ) in it -> recreate "mvd2" if removed
// TODO : find a better solution to replace this hack
if (! datasetQDirParent.exists() )
{
qDebug() << this<< "::OnDatasetToDeleteSelected Making removed dir "
<< datasetQDirParent.absolutePath();
datasetQDirParent.mkpath( datasetQDirParent.absolutePath() );
}
}
}
/*******************************************************************************/
void
DatabaseModel
::OnDatasetRenamed( const QString& alias, const QString & id)
{
// get the model relative to the previous key
DatasetModel * datasetModel = FindDatasetModel(id);
// update the alias
datasetModel->SetAlias( alias );
}
} // end namespace 'mvd'
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <ros/ros.h>
#include <webrtc/base/ssladapter.h>
#include <webrtc/system_wrappers/include/trace.h>
#include "config.h"
#include "host.h"
#include <malloc.h>
#include <sys/resource.h>
struct Flush {
Flush(Host& host) : host(host) {}
void operator()(const ros::TimerEvent& event) {
if (!ros::isShuttingDown()) {
auto stats = host.flush();
if (stats.reaped_data_messages) {
ROS_INFO(
"flushed - reaped_data_messages=%zu",
stats.reaped_data_messages
);
}
}
}
Host &host;
};
struct Reap {
Reap(Host& host, double stale_threhold=30)
: host(host),
stale_threhold(stale_threhold) {
}
void operator()(const ros::TimerEvent& event) {
if (!ros::isShuttingDown()) {
auto stats = host.reap(stale_threhold);
if (stats.deleted_connections) {
ROS_INFO(
"reaped - deleted_connections=%zu",
stats.deleted_connections
);
}
}
}
Host &host;
double stale_threhold;
};
int main(int argc, char **argv) {
ROS_INFO("initializing ros");
ros::init(argc, argv, "host");
ros::NodeHandle nh;
ROS_INFO("loading config");
Config config(Config::get(nh));
if (!config.trace_file.empty()) {
ROS_INFO(
"setting webrtc trace file to %s w/ mask 0x%04x",
config.trace_file.c_str(), config.trace_mask
);
webrtc::Trace::set_level_filter(config.trace_mask);
webrtc::Trace::CreateTrace();
webrtc::Trace::SetTraceFile(config.trace_file.c_str());
}
ROS_INFO("initializing ssl");
if (!rtc::InitializeSSL()) {
ROS_ERROR("ssl initialization failed");
return 1;
}
struct rlimit corelimit = {0x70000000,0x70000000};
if(setrlimit(RLIMIT_CORE,&corelimit) < 0) {
ROS_ERROR("%s",strerror(errno));
return 1;
}
struct rlimit aslimit = {0x70000000,0x70000000};
if(setrlimit(RLIMIT_AS,&corelimit) < 0) {
ROS_ERROR("%s",strerror(errno));
return 1;
}
ROS_INFO("creating host");
HostFactory host_factory;
host_factory.audio_src = config.microphone;
for (size_t i = 0; i != config.cameras.size(); i++) {
host_factory.video_srcs.push_back(config.cameras[i]);
}
for (size_t i = 0; i != config.ice_servers.size(); i++) {
host_factory.ice_servers.push_back(config.ice_servers[i]);
}
host_factory.pc_constraints = config.pc_constraints;
host_factory.pc_bond_connect_timeout = config.pc_bond_connect_timeout;
host_factory.pc_bond_heartbeat_timeout = config.pc_bond_heartbeat_timeout;
host_factory.queue_sizes = config.queue_sizes;
Host host = host_factory(nh);
ROS_INFO("opening host ... ");
if (!host.open(config.open_media_sources)) {
ROS_INFO("host open failed");
return 2;
}
ROS_INFO("opened host");
Flush flush(host);
ros::Timer flush_timer = nh.createTimer(
ros::Duration(config.flush_frequency), flush
);
if (config.flush_frequency != 0) {
ROS_INFO("scheduling host flush every %0.1f sec(s) ... ", config.flush_frequency);
flush_timer.start();
}
Reap reap(host);
ros::Timer reap_timer = nh.createTimer(
ros::Duration(config.reap_frequency), reap
);
if (config.reap_frequency != 0) {
ROS_INFO("scheduling host reap every %0.1f sec(s) ... ", config.reap_frequency);
reap_timer.start();
}
ROS_INFO("start spinning");
ros::spin();
ROS_INFO("stop spinning");
ROS_INFO("closing host ...");
host.close();
ROS_INFO("closed host");
if (!config.trace_file.empty()) {
ROS_INFO("resetting webrtc trace file");
webrtc::Trace::SetTraceFile(NULL);
webrtc::Trace::ReturnTrace();
}
return 0;
}
<commit_msg>PM-2187, relax the AS limit slightly to avoid a crash on first connect that is somtimes showing up. Tested that an induced leak still didn't OOM the whole system<commit_after>#include <stdio.h>
#include <ros/ros.h>
#include <webrtc/base/ssladapter.h>
#include <webrtc/system_wrappers/include/trace.h>
#include "config.h"
#include "host.h"
#include <malloc.h>
#include <sys/resource.h>
struct Flush {
Flush(Host& host) : host(host) {}
void operator()(const ros::TimerEvent& event) {
if (!ros::isShuttingDown()) {
auto stats = host.flush();
if (stats.reaped_data_messages) {
ROS_INFO(
"flushed - reaped_data_messages=%zu",
stats.reaped_data_messages
);
}
}
}
Host &host;
};
struct Reap {
Reap(Host& host, double stale_threhold=30)
: host(host),
stale_threhold(stale_threhold) {
}
void operator()(const ros::TimerEvent& event) {
if (!ros::isShuttingDown()) {
auto stats = host.reap(stale_threhold);
if (stats.deleted_connections) {
ROS_INFO(
"reaped - deleted_connections=%zu",
stats.deleted_connections
);
}
}
}
Host &host;
double stale_threhold;
};
int main(int argc, char **argv) {
ROS_INFO("initializing ros");
ros::init(argc, argv, "host");
ros::NodeHandle nh;
ROS_INFO("loading config");
Config config(Config::get(nh));
if (!config.trace_file.empty()) {
ROS_INFO(
"setting webrtc trace file to %s w/ mask 0x%04x",
config.trace_file.c_str(), config.trace_mask
);
webrtc::Trace::set_level_filter(config.trace_mask);
webrtc::Trace::CreateTrace();
webrtc::Trace::SetTraceFile(config.trace_file.c_str());
}
ROS_INFO("initializing ssl");
if (!rtc::InitializeSSL()) {
ROS_ERROR("ssl initialization failed");
return 1;
}
struct rlimit corelimit = {0x70000000,0x70000000};
if(setrlimit(RLIMIT_CORE,&corelimit) < 0) {
ROS_ERROR("%s",strerror(errno));
return 1;
}
struct rlimit aslimit = {0xA0000000,0xA0000000};
if(setrlimit(RLIMIT_AS,&corelimit) < 0) {
ROS_ERROR("%s",strerror(errno));
return 1;
}
ROS_INFO("creating host");
HostFactory host_factory;
host_factory.audio_src = config.microphone;
for (size_t i = 0; i != config.cameras.size(); i++) {
host_factory.video_srcs.push_back(config.cameras[i]);
}
for (size_t i = 0; i != config.ice_servers.size(); i++) {
host_factory.ice_servers.push_back(config.ice_servers[i]);
}
host_factory.pc_constraints = config.pc_constraints;
host_factory.pc_bond_connect_timeout = config.pc_bond_connect_timeout;
host_factory.pc_bond_heartbeat_timeout = config.pc_bond_heartbeat_timeout;
host_factory.queue_sizes = config.queue_sizes;
Host host = host_factory(nh);
ROS_INFO("opening host ... ");
if (!host.open(config.open_media_sources)) {
ROS_INFO("host open failed");
return 2;
}
ROS_INFO("opened host");
Flush flush(host);
ros::Timer flush_timer = nh.createTimer(
ros::Duration(config.flush_frequency), flush
);
if (config.flush_frequency != 0) {
ROS_INFO("scheduling host flush every %0.1f sec(s) ... ", config.flush_frequency);
flush_timer.start();
}
Reap reap(host);
ros::Timer reap_timer = nh.createTimer(
ros::Duration(config.reap_frequency), reap
);
if (config.reap_frequency != 0) {
ROS_INFO("scheduling host reap every %0.1f sec(s) ... ", config.reap_frequency);
reap_timer.start();
}
ROS_INFO("start spinning");
ros::spin();
ROS_INFO("stop spinning");
ROS_INFO("closing host ...");
host.close();
ROS_INFO("closed host");
if (!config.trace_file.empty()) {
ROS_INFO("resetting webrtc trace file");
webrtc::Trace::SetTraceFile(NULL);
webrtc::Trace::ReturnTrace();
}
return 0;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2018 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file vectorization.hpp
* \brief Contains vectorization utilities for the vectorized assignments (done by the evaluator).
*
* This file automatically includes the correct header based on which vectorization utility is supported (AVX -> SSE -> NONE).
*/
#pragma once
#include <immintrin.h>
#include "etl/inline.hpp"
namespace etl {
/*!
* \brief SIMD pack of some type, using a vector implementation type
* \tparam V The vector implementation
* \tparam T The real type
* \tparam VT The vector type
*/
template <vector_mode_t V, typename T, typename VT>
struct simd_pack {
using value_type = T; ///< The real value type
using intrinsic_type = VT; ///< The used intrinsic type
static constexpr vector_mode_t vector_mode = V; ///< The vector implementation mode
intrinsic_type value; ///< The vector of value
/*!
* \brief Construct a new simd_pack around the given vector
* \param value The vector value to build around
*/
simd_pack(intrinsic_type value) : value(value) {
// Nothing else to init
}
/*!
* \brief Extract an element of the vector value
* \param i The index of the element to get
* \return The ith element from the vector
*/
ETL_STRONG_INLINE(value_type) operator[](size_t i) const noexcept {
return reinterpret_cast<const value_type*>(&value)[i];
}
};
} // end of namespace etl
//Include al the vector implementation
#include "etl/avx512_vectorization.hpp"
#include "etl/avx_vectorization.hpp"
#include "etl/sse_vectorization.hpp"
#include "etl/no_vectorization.hpp"
namespace etl {
/*!
* \brief Traits to get the intrinsic traits for a vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
struct get_intrinsic_traits {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = no_intrinsic_traits<T>;
};
/*!
* \brief Traits to get the vector implementation for a vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
struct get_vector_impl {
using type = no_vec; ///< The vector implementation
};
#ifdef __AVX512F__
/*!
* \brief get_intrinsic_traits for AVX-512
*/
template <>
struct get_intrinsic_traits<vector_mode_t::AVX512> {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = avx512_intrinsic_traits<T>;
};
/*!
* \copy get_vector_impl
*/
template <>
struct get_vector_impl<vector_mode_t::AVX512> {
using type = avx512_vec; ///< The vector implementation
};
#endif
#ifdef __AVX__
/*!
* \brief get_intrinsic_traits for AVX
*/
template <>
struct get_intrinsic_traits<vector_mode_t::AVX> {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = avx_intrinsic_traits<T>;
};
/*!
* \copy get_vector_impl
*/
template <>
struct get_vector_impl<vector_mode_t::AVX> {
using type = avx_vec; ///< The vector implementation
};
#endif
#ifdef __SSE3__
/*!
* \brief get_intrinsic_traits for SSE
*/
template <>
struct get_intrinsic_traits<vector_mode_t::SSE3> {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = sse_intrinsic_traits<T>;
};
/*!
* \copy get_vector_impl
*/
template <>
struct get_vector_impl<vector_mode_t::SSE3> {
using type = sse_vec; ///< The vector implementation
};
#endif
#ifdef ETL_VECTORIZE_EXPR
#ifdef __AVX512F__
/*!
* \brief The default vectorization scheme
*/
using default_vec = avx512_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = avx512_intrinsic_traits<T>;
#elif defined(__AVX__)
/*!
* \brief The default vectorization scheme
*/
using default_vec = avx_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = avx_intrinsic_traits<T>;
#elif defined(__SSE3__)
/*!
* \brief The default vectorization scheme
*/
using default_vec = sse_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = sse_intrinsic_traits<T>;
#else
/*!
* \brief The default vectorization scheme
*/
using default_vec = no_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = no_intrinsic_traits<T>;
#endif //defined(__SSE__)
#else //ETL_VECTORIZE_EXPR
/*!
* \brief The default vectorization scheme
*/
using default_vec = no_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = no_intrinsic_traits<T>;
#endif //ETL_VECTORIZE_EXPR
/*!
* \brief Helper to get the intrinsic corresponding type of a vectorizable type.
*/
template <typename T>
using default_intrinsic_type = typename default_intrinsic_traits<T>::intrinsic_type;
} //end of namespace etl
<commit_msg>Fix warning in GCC 7+<commit_after>//=======================================================================
// Copyright (c) 2014-2018 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file vectorization.hpp
* \brief Contains vectorization utilities for the vectorized assignments (done by the evaluator).
*
* This file automatically includes the correct header based on which vectorization utility is supported (AVX -> SSE -> NONE).
*/
#pragma once
#include <immintrin.h>
#include "etl/inline.hpp"
namespace etl {
/*!
* \brief SIMD pack of some type, using a vector implementation type
* \tparam V The vector implementation
* \tparam T The real type
* \tparam VT The vector type
*/
template <vector_mode_t V, typename T, typename VT>
struct simd_pack {
using value_type = T; ///< The real value type
using intrinsic_type = VT; ///< The used intrinsic type
static constexpr vector_mode_t vector_mode = V; ///< The vector implementation mode
intrinsic_type value; ///< The vector of value
/*!
* \brief Construct a new simd_pack around the given vector
* \param value The vector value to build around
*/
simd_pack(intrinsic_type value) : value(value) {
// Nothing else to init
}
/*!
* \brief Extract an element of the vector value
* \param i The index of the element to get
* \return The ith element from the vector
*/
ETL_STRONG_INLINE(value_type) operator[](size_t i) const noexcept {
return reinterpret_cast<const value_type*>(&value)[i];
}
};
} // end of namespace etl
#if defined __GNUC__ && __GNUC__>=6
#pragma GCC diagnostic ignored "-Wignored-attributes"
#endif
//Include al the vector implementation
#include "etl/avx512_vectorization.hpp"
#include "etl/avx_vectorization.hpp"
#include "etl/sse_vectorization.hpp"
#include "etl/no_vectorization.hpp"
#if defined __GNUC__ && __GNUC__>=6
#pragma GCC diagnostic pop
#endif
namespace etl {
/*!
* \brief Traits to get the intrinsic traits for a vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
struct get_intrinsic_traits {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = no_intrinsic_traits<T>;
};
/*!
* \brief Traits to get the vector implementation for a vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
struct get_vector_impl {
using type = no_vec; ///< The vector implementation
};
#ifdef __AVX512F__
/*!
* \brief get_intrinsic_traits for AVX-512
*/
template <>
struct get_intrinsic_traits<vector_mode_t::AVX512> {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = avx512_intrinsic_traits<T>;
};
/*!
* \copy get_vector_impl
*/
template <>
struct get_vector_impl<vector_mode_t::AVX512> {
using type = avx512_vec; ///< The vector implementation
};
#endif
#ifdef __AVX__
/*!
* \brief get_intrinsic_traits for AVX
*/
template <>
struct get_intrinsic_traits<vector_mode_t::AVX> {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = avx_intrinsic_traits<T>;
};
/*!
* \copy get_vector_impl
*/
template <>
struct get_vector_impl<vector_mode_t::AVX> {
using type = avx_vec; ///< The vector implementation
};
#endif
#ifdef __SSE3__
/*!
* \brief get_intrinsic_traits for SSE
*/
template <>
struct get_intrinsic_traits<vector_mode_t::SSE3> {
/*!
* \brief The type of the intrinsic traits for T
* \tparam T The type to get the intrinsic traits for
*/
template <typename T>
using type = sse_intrinsic_traits<T>;
};
/*!
* \copy get_vector_impl
*/
template <>
struct get_vector_impl<vector_mode_t::SSE3> {
using type = sse_vec; ///< The vector implementation
};
#endif
#ifdef ETL_VECTORIZE_EXPR
#ifdef __AVX512F__
/*!
* \brief The default vectorization scheme
*/
using default_vec = avx512_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = avx512_intrinsic_traits<T>;
#elif defined(__AVX__)
/*!
* \brief The default vectorization scheme
*/
using default_vec = avx_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = avx_intrinsic_traits<T>;
#elif defined(__SSE3__)
/*!
* \brief The default vectorization scheme
*/
using default_vec = sse_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = sse_intrinsic_traits<T>;
#else
/*!
* \brief The default vectorization scheme
*/
using default_vec = no_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = no_intrinsic_traits<T>;
#endif //defined(__SSE__)
#else //ETL_VECTORIZE_EXPR
/*!
* \brief The default vectorization scheme
*/
using default_vec = no_vec;
/*!
* \brief The default intrinsic traits
*/
template <typename T>
using default_intrinsic_traits = no_intrinsic_traits<T>;
#endif //ETL_VECTORIZE_EXPR
/*!
* \brief Helper to get the intrinsic corresponding type of a vectorizable type.
*/
template <typename T>
using default_intrinsic_type = typename default_intrinsic_traits<T>::intrinsic_type;
} //end of namespace etl
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string.h>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/globals.h"
#include "parse/forbiddenChars.h"
/* ****************************************************************************
*
* commonForbidden
*/
inline static bool commonForbidden(char c)
{
switch (c)
{
case '<':
case '>':
case '"':
case '\'':
case '=':
case ';':
case '(':
case ')':
return true;
}
return false;
}
/* ****************************************************************************
*
* forbiddenChars -
*/
bool forbiddenChars(const char* s, const char* exceptions)
{
if (s == (void*) 0)
{
return false;
}
while (*s != 0)
{
if ((exceptions != NULL) && (strchr(exceptions, *s) != NULL))
{
++s;
continue;
}
if (commonForbidden(*s))
{
return true;
}
++s;
}
return false;
}
/* ****************************************************************************
*
* forbiddenIdChars -
*/
bool forbiddenIdChars(int api, const char* s, const char* exceptions)
{
if (api == 1 && !checkIdv1)
{
return forbiddenChars(s, exceptions); // old behavior
}
return forbiddenIdCharsV2(s, exceptions);
}
/* ****************************************************************************
*
* forbiddenIdCharsV2 -
*/
bool forbiddenIdCharsV2(const char* s, const char* exceptions)
{
if (s == (void*) 0)
{
return false;
}
while (*s != 0)
{
if ((exceptions != NULL) && (strchr(exceptions, *s) != NULL))
{
++s;
continue;
}
if (*s >= 127 || *s <= 32)
{
return true;
}
switch (*s)
{
case '?':
case '/':
case '#':
case '&':
return true;
}
// Plus common set of forbidden chars
if(commonForbidden(*s))
{
return true;
}
++s;
}
return false;
}
/* ****************************************************************************
*
* forbiddenQuotes - any unauthorized quotes?
*
* Quotes are used to delimit attribute/metadata/compound-node names that contain a dot.
*
* Example:
* We have an attribute A with a metadata called 'M.x'.
* To do a string filter (mq) on M.x, we need to use quotes.
* A.M.x is interpreted as attribute A, metadata M, compound node x
* A.'M.x' is what we need to reach the metadata M.x.
*
* So, quotes are allowed as first and last character, and if there is a dot
* before or after the quote.
*
* If a dot is found elsewhere, an error should be returned.
*/
bool forbiddenQuotes(char* s)
{
int ix = 0;
while (s[ix] != 0)
{
++ix; // Remember, quote is allowed as first char, ok to step over ix==0
if (s[ix] == '\'')
{
if (s[ix - 1] == '.') {} // OK - a.'x.b' is allowed (see quote in pos 2 - dot before)
else if (s[ix + 1] == '.') {} // OK - a.'x.b'.c is allowed (see quote in pos 6 - dot after)
else if (s[ix + 1] == 0) {} // OK - quote as last char is allowed
else
{
return true; // NOT OK - unauthorized quote found
}
}
}
return false;
}
<commit_msg>improved explanation of forbiddenQuotes<commit_after>/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string.h>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/globals.h"
#include "parse/forbiddenChars.h"
/* ****************************************************************************
*
* commonForbidden
*/
inline static bool commonForbidden(char c)
{
switch (c)
{
case '<':
case '>':
case '"':
case '\'':
case '=':
case ';':
case '(':
case ')':
return true;
}
return false;
}
/* ****************************************************************************
*
* forbiddenChars -
*/
bool forbiddenChars(const char* s, const char* exceptions)
{
if (s == (void*) 0)
{
return false;
}
while (*s != 0)
{
if ((exceptions != NULL) && (strchr(exceptions, *s) != NULL))
{
++s;
continue;
}
if (commonForbidden(*s))
{
return true;
}
++s;
}
return false;
}
/* ****************************************************************************
*
* forbiddenIdChars -
*/
bool forbiddenIdChars(int api, const char* s, const char* exceptions)
{
if (api == 1 && !checkIdv1)
{
return forbiddenChars(s, exceptions); // old behavior
}
return forbiddenIdCharsV2(s, exceptions);
}
/* ****************************************************************************
*
* forbiddenIdCharsV2 -
*/
bool forbiddenIdCharsV2(const char* s, const char* exceptions)
{
if (s == (void*) 0)
{
return false;
}
while (*s != 0)
{
if ((exceptions != NULL) && (strchr(exceptions, *s) != NULL))
{
++s;
continue;
}
if (*s >= 127 || *s <= 32)
{
return true;
}
switch (*s)
{
case '?':
case '/':
case '#':
case '&':
return true;
}
// Plus common set of forbidden chars
if(commonForbidden(*s))
{
return true;
}
++s;
}
return false;
}
/* ****************************************************************************
*
* forbiddenQuotes - any unauthorized quotes?
*
* Quotes (') are used to delimit attribute/metadata/compound-node names that contain a dot (.).
*
* Example (of metadata, but valid also for attribute name and compound node name):
* We have an attribute A with a metadata called "M.x" (without double-quotes - 3 chars).
* For a string filter (mq) on M.x, we need to use quotes.
* A.M.x is interpreted as attribute A, metadata M, compound node x
* A.'M.x' is what we need to reach the metadata M.x.
*
* So, quotes are allowed as first and last character, and if there is a dot
* before or after the quote.
*
* If a quote is found elsewhere, an error should be returned.
*/
bool forbiddenQuotes(char* s)
{
int ix = 0;
while (s[ix] != 0)
{
++ix; // Remember, quote is allowed as first char, ok to step over ix==0
if (s[ix] == '\'')
{
if (s[ix - 1] == '.') {} // OK - a.'x.b' is allowed (see quote in pos 2 - dot before)
else if (s[ix + 1] == '.') {} // OK - a.'x.b'.c is allowed (see quote in pos 6 - dot after)
else if (s[ix + 1] == 0) {} // OK - quote as last char is allowed
else
{
return true; // NOT OK - unauthorized quote found
}
}
}
return false;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 Rasterbar Software 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.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
#include <memory>
#include <cstring>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval()
: begin(0)
, end(0)
{}
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(interval const& i)
: begin(i.begin)
, end(i.end)
{}
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
bool operator==(const const_interval& p_interval)
{
return (begin == p_interval.begin
&& end == p_interval.end);
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
buffer(std::size_t n = 0)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (n) resize(n);
}
buffer(buffer const& b)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (b.size() == 0) return;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
}
buffer& operator=(buffer const& b)
{
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
return *this;
}
~buffer()
{
::operator delete (m_begin);
}
buffer::interval data() { return interval(m_begin, m_end); }
buffer::const_interval data() const { return const_interval(m_begin, m_end); }
void resize(std::size_t n)
{
reserve(n);
m_end = m_begin + n;
}
void insert(char* point, char const* first, char const* last)
{
std::size_t p = point - m_begin;
if (point == m_end)
{
resize(size() + last - first);
std::memcpy(m_begin + p, first, last - first);
return;
}
resize(size() + last - first);
std::memmove(m_begin + p + (last - first), m_begin + p, last - first);
std::memcpy(m_begin + p, first, last - first);
}
void erase(char* begin, char* end)
{
TORRENT_ASSERT(end <= m_end);
TORRENT_ASSERT(begin >= m_begin);
TORRENT_ASSERT(begin <= end);
if (end == m_end)
{
resize(begin - m_begin);
return;
}
std::memmove(begin, end, m_end - end);
m_end = begin + (m_end - end);
}
void clear() { m_end = m_begin; }
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_last - m_begin; }
void reserve(std::size_t n)
{
if (n <= capacity()) return;
TORRENT_ASSERT(n > 0);
char* buf = (char*)::operator new(n);
std::size_t s = size();
std::memcpy(buf, m_begin, s);
::operator delete (m_begin);
m_begin = buf;
m_end = buf + s;
m_last = m_begin + n;
}
bool empty() const { return m_begin == m_end; }
char& operator[](std::size_t i) { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char const& operator[](std::size_t i) const { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char* begin() { return m_begin; }
char const* begin() const { return m_begin; }
char* end() { return m_end; }
char const* end() const { return m_end; }
void swap(buffer& b)
{
using std::swap;
swap(m_begin, b.m_begin);
swap(m_end, b.m_end);
swap(m_last, b.m_last);
}
private:
char* m_begin; // first
char* m_end; // one passed end of size
char* m_last; // one passed end of allocation
};
}
#endif // LIBTORRENT_BUFFER_HPP
<commit_msg>switched over buffer to use realloc/free<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 Rasterbar Software 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.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
#include <memory>
#include <cstring>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval()
: begin(0)
, end(0)
{}
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(interval const& i)
: begin(i.begin)
, end(i.end)
{}
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
bool operator==(const const_interval& p_interval)
{
return (begin == p_interval.begin
&& end == p_interval.end);
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
buffer(std::size_t n = 0)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (n) resize(n);
}
buffer(buffer const& b)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (b.size() == 0) return;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
}
buffer& operator=(buffer const& b)
{
if (&b == this) return *this;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
return *this;
}
~buffer()
{
std::free(m_begin);
}
buffer::interval data() { return interval(m_begin, m_end); }
buffer::const_interval data() const { return const_interval(m_begin, m_end); }
void resize(std::size_t n)
{
reserve(n);
m_end = m_begin + n;
}
void insert(char* point, char const* first, char const* last)
{
std::size_t p = point - m_begin;
if (point == m_end)
{
resize(size() + last - first);
std::memcpy(m_begin + p, first, last - first);
return;
}
resize(size() + last - first);
std::memmove(m_begin + p + (last - first), m_begin + p, last - first);
std::memcpy(m_begin + p, first, last - first);
}
void erase(char* begin, char* end)
{
TORRENT_ASSERT(end <= m_end);
TORRENT_ASSERT(begin >= m_begin);
TORRENT_ASSERT(begin <= end);
if (end == m_end)
{
resize(begin - m_begin);
return;
}
std::memmove(begin, end, m_end - end);
m_end = begin + (m_end - end);
}
void clear() { m_end = m_begin; }
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_last - m_begin; }
void reserve(std::size_t n)
{
if (n <= capacity()) return;
TORRENT_ASSERT(n > 0);
std::size_t s = size();
m_begin = (char*)std::realloc(m_begin, n);
m_end = m_begin + s;
m_last = m_begin + n;
}
bool empty() const { return m_begin == m_end; }
char& operator[](std::size_t i) { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char const& operator[](std::size_t i) const { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char* begin() { return m_begin; }
char const* begin() const { return m_begin; }
char* end() { return m_end; }
char const* end() const { return m_end; }
void swap(buffer& b)
{
using std::swap;
swap(m_begin, b.m_begin);
swap(m_end, b.m_end);
swap(m_last, b.m_last);
}
private:
char* m_begin; // first
char* m_end; // one passed end of size
char* m_last; // one passed end of allocation
};
}
#endif // LIBTORRENT_BUFFER_HPP
<|endoftext|>
|
<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#include "IncoherentAcquirer.hpp"
#include "common.hpp"
#include "Statistics.hpp"
#include <limits>
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_ams, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_ams_bytes, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_blocked, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_blocked_ticks_total, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_network_ticks_total, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_wakeup_ticks_total, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_blocked_ticks_max, std::numeric_limits<uint64_t>::min());
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_blocked_ticks_min, std::numeric_limits<uint64_t>::min());
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_network_ticks_max, std::numeric_limits<uint64_t>::min());
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_network_ticks_min, std::numeric_limits<uint64_t>::min());
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_wakeup_ticks_max, std::numeric_limits<uint64_t>::min());
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_wakeup_ticks_min, std::numeric_limits<uint64_t>::min());
void IAStatistics::count_acquire_ams( uint64_t bytes ) {
acquire_ams++;
acquire_ams_bytes+=bytes;
}
void IAStatistics::record_wakeup_latency( int64_t start_time, int64_t network_time ) {
acquire_blocked++;
int64_t current_time = Grappa::timestamp();
int64_t blocked_latency = current_time - start_time;
int64_t wakeup_latency = current_time - network_time;
acquire_blocked_ticks_total += blocked_latency;
acquire_wakeup_ticks_total += wakeup_latency;
if( blocked_latency > acquire_blocked_ticks_max )
acquire_blocked_ticks_max = blocked_latency;
if( blocked_latency < acquire_blocked_ticks_min )
acquire_blocked_ticks_min = blocked_latency;
if( wakeup_latency > acquire_wakeup_ticks_max )
acquire_wakeup_ticks_max = wakeup_latency;
if( wakeup_latency < acquire_wakeup_ticks_min )
acquire_wakeup_ticks_min = wakeup_latency;
}
void IAStatistics::record_network_latency( int64_t start_time ) {
int64_t current_time = Grappa::timestamp();
int64_t latency = current_time - start_time;
acquire_network_ticks_total += latency;
if( latency > acquire_network_ticks_max )
acquire_network_ticks_max = latency;
if( latency < acquire_network_ticks_min )
acquire_network_ticks_min = latency;
}
<commit_msg>fix max min stats and consolidate in cache acquirer<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#include "IncoherentAcquirer.hpp"
#include "common.hpp"
#include "Statistics.hpp"
#include <limits>
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_ams, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_ams_bytes, 0);
GRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, acquire_blocked, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<uint64_t>, acquire_blocked_ticks_total, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<uint64_t>, acquire_network_ticks_total, 0);
GRAPPA_DEFINE_STAT(SummarizingStatistic<uint64_t>, acquire_wakeup_ticks_total, 0);
void IAStatistics::count_acquire_ams( uint64_t bytes ) {
acquire_ams++;
acquire_ams_bytes+=bytes;
}
void IAStatistics::record_wakeup_latency( int64_t start_time, int64_t network_time ) {
acquire_blocked++;
int64_t current_time = Grappa::timestamp();
int64_t blocked_latency = current_time - start_time;
int64_t wakeup_latency = current_time - network_time;
acquire_blocked_ticks_total += blocked_latency;
acquire_wakeup_ticks_total += wakeup_latency;
}
void IAStatistics::record_network_latency( int64_t start_time ) {
int64_t current_time = Grappa::timestamp();
int64_t latency = current_time - start_time;
acquire_network_ticks_total += latency;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQuadraticEdge.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkQuadraticEdge.h"
#include "vtkObjectFactory.h"
#include "vtkMath.h"
#include "vtkLine.h"
#include "vtkDoubleArray.h"
#include "vtkPoints.h"
vtkStandardNewMacro(vtkQuadraticEdge);
//----------------------------------------------------------------------------
// Construct the line with two points.
vtkQuadraticEdge::vtkQuadraticEdge()
{
this->Scalars = vtkDoubleArray::New();
this->Scalars->SetNumberOfTuples(2);
this->Points->SetNumberOfPoints(3);
this->PointIds->SetNumberOfIds(3);
for (int i = 0; i < 3; i++)
{
this->Points->SetPoint(i, 0.0, 0.0, 0.0);
this->PointIds->SetId(i,0);
}
this->Line = vtkLine::New();
}
//----------------------------------------------------------------------------
vtkQuadraticEdge::~vtkQuadraticEdge()
{
this->Line->Delete();
this->Scalars->Delete();
}
//----------------------------------------------------------------------------
int vtkQuadraticEdge::EvaluatePosition(double* x, double* closestPoint,
int& subId, double pcoords[3],
double& minDist2, double *weights)
{
double closest[3];
double pc[3], dist2;
int ignoreId, i, returnStatus, status;
double lineWeights[2];
pcoords[1] = pcoords[2] = 0.0;
returnStatus = -1;
weights[0] = 0.0;
for (minDist2=VTK_DOUBLE_MAX,i=0; i < 2; i++)
{
if ( i == 0)
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(0));
this->Line->Points->SetPoint(1,this->Points->GetPoint(2));
}
else
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(2));
this->Line->Points->SetPoint(1,this->Points->GetPoint(1));
}
status = this->Line->EvaluatePosition(x,closest,ignoreId,pc,
dist2,lineWeights);
if ( status != -1 && dist2 < minDist2 )
{
returnStatus = status;
minDist2 = dist2;
subId = i;
pcoords[0] = pc[0];
}
}
// adjust parametric coordinate
if ( returnStatus != -1 )
{
if ( subId == 0 ) //first part
{
pcoords[0] = pcoords[0]/2.0;
}
else
{
pcoords[0] = 0.5 + pcoords[0]/2.0;
}
if(closestPoint!=0)
{
// Compute both closestPoint and weights
this->EvaluateLocation(subId,pcoords,closestPoint,weights);
}
else
{
// Compute weights only
this->InterpolationFunctions(pcoords,weights);
}
}
return returnStatus;
}
//----------------------------------------------------------------------------
void vtkQuadraticEdge::EvaluateLocation(int& vtkNotUsed(subId),
double pcoords[3],
double x[3], double *weights)
{
int i;
double a0[3], a1[3], a2[3];
this->Points->GetPoint(0, a0);
this->Points->GetPoint(1, a1);
this->Points->GetPoint(2, a2); //midside node
this->InterpolationFunctions(pcoords,weights);
for (i=0; i<3; i++)
{
x[i] = a0[i]*weights[0] + a1[i]*weights[1] + a2[i]*weights[2];
}
}
//----------------------------------------------------------------------------
int vtkQuadraticEdge::CellBoundary(int subId, double pcoords[3],
vtkIdList *pts)
{
return this->Line->CellBoundary(subId, pcoords, pts);
}
//----------------------------------------------------------------------------
static int LinearLines[2][2] = { {0,2}, {2,1} };
void vtkQuadraticEdge::Contour(double value, vtkDataArray *cellScalars,
vtkIncrementalPointLocator *locator, vtkCellArray *verts,
vtkCellArray *lines, vtkCellArray *polys,
vtkPointData *inPd, vtkPointData *outPd,
vtkCellData *inCd, vtkIdType cellId,
vtkCellData *outCd)
{
for (int i=0; i < 2; i++) //for each subdivided line
{
for ( int j=0; j<2; j++) //for each of the four vertices of the line
{
this->Line->Points->SetPoint(j,this->Points->GetPoint(LinearLines[i][j]));
this->Line->PointIds->SetId(j,this->PointIds->GetId(LinearLines[i][j]));
this->Scalars->SetValue(j,cellScalars->GetTuple1(LinearLines[i][j]));
}
this->Line->Contour(value, this->Scalars, locator, verts,
lines, polys, inPd, outPd, inCd, cellId, outCd);
}
}
//----------------------------------------------------------------------------
// Line-line intersection. Intersection has to occur within [0,1] parametric
// coordinates and with specified tolerance.
// The following arguments were modified to avoid warnings:
// double p1[3], double p2[3], double x[3], double pcoords[3],
int vtkQuadraticEdge::IntersectWithLine(double p1[3], double p2[3],
double tol, double& t,
double x[3], double pcoords[3],
int& subId)
{
int subTest, numLines=2;
for (subId=0; subId < numLines; subId++)
{
if ( subId == 0)
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(0));
this->Line->Points->SetPoint(1,this->Points->GetPoint(2));
}
else
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(2));
this->Line->Points->SetPoint(1,this->Points->GetPoint(1));
}
if ( this->Line->IntersectWithLine(p1, p2, tol, t, x, pcoords, subTest) )
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkQuadraticEdge::Triangulate(int vtkNotUsed(index), vtkIdList *ptIds,
vtkPoints *pts)
{
pts->Reset();
ptIds->Reset();
// The first line
ptIds->InsertId(0,this->PointIds->GetId(0));
pts->InsertPoint(0,this->Points->GetPoint(0));
ptIds->InsertId(1,this->PointIds->GetId(2));
pts->InsertPoint(1,this->Points->GetPoint(2));
// The second line
ptIds->InsertId(2,this->PointIds->GetId(2));
pts->InsertPoint(2,this->Points->GetPoint(2));
ptIds->InsertId(3,this->PointIds->GetId(1));
pts->InsertPoint(3,this->Points->GetPoint(1));
return 1;
}
//----------------------------------------------------------------------------
void vtkQuadraticEdge::Derivatives(int vtkNotUsed(subId),
double pcoords[3], double *values,
int dim, double *derivs)
{
double x0[3], x1[3], x2[3];
this->Points->GetPoint(0, x0);
this->Points->GetPoint(1, x1);
this->Points->GetPoint(2, x2); //midside node
// set up Jacobian matrix and inverse matrix
double *jTj[3], jTj0[3], jTj1[3], jTj2[3];
jTj[0] = jTj0; jTj[1] = jTj1; jTj[2] = jTj2;
double *jI[3], jI0[3], jI1[3], jI2[3];
jI[0] = jI0; jI[1] = jI1; jI[2] = jI2;
/*
double *iI[3], iI0[3], iI1[3], iI2[3];
iI[0] = iI0; iI[1] = iI1; iI[2] = iI2;
*/
// Compute dx/dt, dy/dt, dz/dt
this->InterpolationDerivs(pcoords,derivs);
double dxdt = x0[0]*derivs[0] + x1[0]*derivs[1] + x2[0]*derivs[2];
double dydt = x0[1]*derivs[0] + x1[1]*derivs[1] + x2[1]*derivs[2];
double dzdt = x0[2]*derivs[0] + x1[2]*derivs[1] + x2[2]*derivs[2];
// Compute the pseudo inverse (we are dealing with an overconstrained system,
// i.e., a non-square Jacobian matrix). The pseudo inverse is ((jT*j)-1)*jT
// with jT Jacobian transpose, -1 notation means inverse.
// Compute jT * j
jTj[0][0] = dxdt*dxdt;
jTj[0][1] = dxdt*dydt;
jTj[0][2] = dxdt*dzdt;
jTj[1][0] = dydt*dxdt;
jTj[1][1] = dydt*dydt;
jTj[1][2] = dydt*dzdt;
jTj[2][0] = dzdt*dxdt;
jTj[2][1] = dzdt*dydt;
jTj[2][2] = dzdt*dzdt;
// Compute (jT * j) inverse
// now find the inverse
if ( vtkMath::InvertMatrix(jTj,jI,3) == 0 )
{
vtkErrorMacro(<<"Jacobian inverse not found");
return;
}
// Multiply inverse by transpose (jT * j) * jT to yield pseudo inverse.
// Here the pseudo inverse is a 3x1 matrix.
double inv[3];
inv[0] = jI[0][0]*dxdt + jI[0][1]*dydt + jI[0][2]*dzdt;
inv[1] = jI[1][0]*dxdt + jI[1][1]*dydt + jI[1][2]*dzdt;
inv[2] = jI[2][0]*dxdt + jI[2][1]*dydt + jI[2][2]*dzdt;
//now compute the derivates of the data values
double sum;
int i, j, k;
for (k=0; k<dim; k++)
{
sum = 0.0;
for ( i=0; i < 3; i++) //loop over interp. function derivatives
{
sum += derivs[i] * values[dim*i + k];
}
for (j=0; j < 3; j++) //loop over derivative directions
{
derivs[3*k + j] = sum*inv[j];
}
}
}
//----------------------------------------------------------------------------
// Clip this quadratic edge using scalar value provided. Like contouring,
// except that it cuts the edge to produce linear line segments.
void vtkQuadraticEdge::Clip(double value, vtkDataArray *cellScalars,
vtkIncrementalPointLocator *locator, vtkCellArray *lines,
vtkPointData *inPd, vtkPointData *outPd,
vtkCellData *inCd, vtkIdType cellId,
vtkCellData *outCd, int insideOut)
{
for (int i=0; i < 2; i++) //for each subdivided line
{
for ( int j=0; j<2; j++) //for each of the four vertices of the line
{
this->Line->Points->SetPoint(j,this->Points->GetPoint(LinearLines[i][j]));
this->Line->PointIds->SetId(j,this->PointIds->GetId(LinearLines[i][j]));
this->Scalars->SetValue(j,cellScalars->GetTuple1(LinearLines[i][j]));
}
this->Line->Clip(value, this->Scalars, locator, lines, inPd, outPd,
inCd, cellId, outCd, insideOut);
}
}
//----------------------------------------------------------------------------
// Compute interpolation functions. Node [2] is the mid-edge node.
void vtkQuadraticEdge::InterpolationFunctions(double pcoords[3],
double weights[3])
{
double r = pcoords[0];
weights[0] = 2.0 * (r - 0.5) * (r - 1.0);
weights[1] = 2.0 * r * (r - 0.5);
weights[2] = 4.0 * r * (1.0 - r);
}
//----------------------------------------------------------------------------
// Derivatives in parametric space.
void vtkQuadraticEdge::InterpolationDerivs(double pcoords[3], double derivs[3])
{
double r = pcoords[0];
derivs[0] = 4.0 * r - 3.0;
derivs[1] = 4.0 * r - 1.0;
derivs[2] = 4.0 - r * 8.0;
}
//----------------------------------------------------------------------------
static double vtkQEdgeCellPCoords[9] = {0.0,0.0,0.0, 1.0,0.0,0.0, 0.5,0.0,0.0};
double *vtkQuadraticEdge::GetParametricCoords()
{
return vtkQEdgeCellPCoords;
}
//----------------------------------------------------------------------------
void vtkQuadraticEdge::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Line:\n";
this->Line->PrintSelf(os,indent.GetNextIndent());
}
<commit_msg>vtkQuadraticEdge: remove broken Derivatives implementation<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQuadraticEdge.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkQuadraticEdge.h"
#include "vtkObjectFactory.h"
#include "vtkMath.h"
#include "vtkLine.h"
#include "vtkDoubleArray.h"
#include "vtkPoints.h"
vtkStandardNewMacro(vtkQuadraticEdge);
//----------------------------------------------------------------------------
// Construct the line with two points.
vtkQuadraticEdge::vtkQuadraticEdge()
{
this->Scalars = vtkDoubleArray::New();
this->Scalars->SetNumberOfTuples(2);
this->Points->SetNumberOfPoints(3);
this->PointIds->SetNumberOfIds(3);
for (int i = 0; i < 3; i++)
{
this->Points->SetPoint(i, 0.0, 0.0, 0.0);
this->PointIds->SetId(i,0);
}
this->Line = vtkLine::New();
}
//----------------------------------------------------------------------------
vtkQuadraticEdge::~vtkQuadraticEdge()
{
this->Line->Delete();
this->Scalars->Delete();
}
//----------------------------------------------------------------------------
int vtkQuadraticEdge::EvaluatePosition(double* x, double* closestPoint,
int& subId, double pcoords[3],
double& minDist2, double *weights)
{
double closest[3];
double pc[3], dist2;
int ignoreId, i, returnStatus, status;
double lineWeights[2];
pcoords[1] = pcoords[2] = 0.0;
returnStatus = -1;
weights[0] = 0.0;
for (minDist2=VTK_DOUBLE_MAX,i=0; i < 2; i++)
{
if ( i == 0)
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(0));
this->Line->Points->SetPoint(1,this->Points->GetPoint(2));
}
else
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(2));
this->Line->Points->SetPoint(1,this->Points->GetPoint(1));
}
status = this->Line->EvaluatePosition(x,closest,ignoreId,pc,
dist2,lineWeights);
if ( status != -1 && dist2 < minDist2 )
{
returnStatus = status;
minDist2 = dist2;
subId = i;
pcoords[0] = pc[0];
}
}
// adjust parametric coordinate
if ( returnStatus != -1 )
{
if ( subId == 0 ) //first part
{
pcoords[0] = pcoords[0]/2.0;
}
else
{
pcoords[0] = 0.5 + pcoords[0]/2.0;
}
if(closestPoint!=0)
{
// Compute both closestPoint and weights
this->EvaluateLocation(subId,pcoords,closestPoint,weights);
}
else
{
// Compute weights only
this->InterpolationFunctions(pcoords,weights);
}
}
return returnStatus;
}
//----------------------------------------------------------------------------
void vtkQuadraticEdge::EvaluateLocation(int& vtkNotUsed(subId),
double pcoords[3],
double x[3], double *weights)
{
int i;
double a0[3], a1[3], a2[3];
this->Points->GetPoint(0, a0);
this->Points->GetPoint(1, a1);
this->Points->GetPoint(2, a2); //midside node
this->InterpolationFunctions(pcoords,weights);
for (i=0; i<3; i++)
{
x[i] = a0[i]*weights[0] + a1[i]*weights[1] + a2[i]*weights[2];
}
}
//----------------------------------------------------------------------------
int vtkQuadraticEdge::CellBoundary(int subId, double pcoords[3],
vtkIdList *pts)
{
return this->Line->CellBoundary(subId, pcoords, pts);
}
//----------------------------------------------------------------------------
static int LinearLines[2][2] = { {0,2}, {2,1} };
void vtkQuadraticEdge::Contour(double value, vtkDataArray *cellScalars,
vtkIncrementalPointLocator *locator, vtkCellArray *verts,
vtkCellArray *lines, vtkCellArray *polys,
vtkPointData *inPd, vtkPointData *outPd,
vtkCellData *inCd, vtkIdType cellId,
vtkCellData *outCd)
{
for (int i=0; i < 2; i++) //for each subdivided line
{
for ( int j=0; j<2; j++) //for each of the four vertices of the line
{
this->Line->Points->SetPoint(j,this->Points->GetPoint(LinearLines[i][j]));
this->Line->PointIds->SetId(j,this->PointIds->GetId(LinearLines[i][j]));
this->Scalars->SetValue(j,cellScalars->GetTuple1(LinearLines[i][j]));
}
this->Line->Contour(value, this->Scalars, locator, verts,
lines, polys, inPd, outPd, inCd, cellId, outCd);
}
}
//----------------------------------------------------------------------------
// Line-line intersection. Intersection has to occur within [0,1] parametric
// coordinates and with specified tolerance.
// The following arguments were modified to avoid warnings:
// double p1[3], double p2[3], double x[3], double pcoords[3],
int vtkQuadraticEdge::IntersectWithLine(double p1[3], double p2[3],
double tol, double& t,
double x[3], double pcoords[3],
int& subId)
{
int subTest, numLines=2;
for (subId=0; subId < numLines; subId++)
{
if ( subId == 0)
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(0));
this->Line->Points->SetPoint(1,this->Points->GetPoint(2));
}
else
{
this->Line->Points->SetPoint(0,this->Points->GetPoint(2));
this->Line->Points->SetPoint(1,this->Points->GetPoint(1));
}
if ( this->Line->IntersectWithLine(p1, p2, tol, t, x, pcoords, subTest) )
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkQuadraticEdge::Triangulate(int vtkNotUsed(index), vtkIdList *ptIds,
vtkPoints *pts)
{
pts->Reset();
ptIds->Reset();
// The first line
ptIds->InsertId(0,this->PointIds->GetId(0));
pts->InsertPoint(0,this->Points->GetPoint(0));
ptIds->InsertId(1,this->PointIds->GetId(2));
pts->InsertPoint(1,this->Points->GetPoint(2));
// The second line
ptIds->InsertId(2,this->PointIds->GetId(2));
pts->InsertPoint(2,this->Points->GetPoint(2));
ptIds->InsertId(3,this->PointIds->GetId(1));
pts->InsertPoint(3,this->Points->GetPoint(1));
return 1;
}
//----------------------------------------------------------------------------
void vtkQuadraticEdge::Derivatives(int vtkNotUsed(subId),
double vtkNotUsed(pcoords)[3],
double *vtkNotUsed(values),
int vtkNotUsed(dim),
double *vtkNotUsed(derivs))
{
// TODO - if the effort is justified, someone should implement a correct
// version of this method
vtkErrorMacro( "Derivatives() is not implemented for this cell.");
}
//----------------------------------------------------------------------------
// Clip this quadratic edge using scalar value provided. Like contouring,
// except that it cuts the edge to produce linear line segments.
void vtkQuadraticEdge::Clip(double value, vtkDataArray *cellScalars,
vtkIncrementalPointLocator *locator, vtkCellArray *lines,
vtkPointData *inPd, vtkPointData *outPd,
vtkCellData *inCd, vtkIdType cellId,
vtkCellData *outCd, int insideOut)
{
for (int i=0; i < 2; i++) //for each subdivided line
{
for ( int j=0; j<2; j++) //for each of the four vertices of the line
{
this->Line->Points->SetPoint(j,this->Points->GetPoint(LinearLines[i][j]));
this->Line->PointIds->SetId(j,this->PointIds->GetId(LinearLines[i][j]));
this->Scalars->SetValue(j,cellScalars->GetTuple1(LinearLines[i][j]));
}
this->Line->Clip(value, this->Scalars, locator, lines, inPd, outPd,
inCd, cellId, outCd, insideOut);
}
}
//----------------------------------------------------------------------------
// Compute interpolation functions. Node [2] is the mid-edge node.
void vtkQuadraticEdge::InterpolationFunctions(double pcoords[3],
double weights[3])
{
double r = pcoords[0];
weights[0] = 2.0 * (r - 0.5) * (r - 1.0);
weights[1] = 2.0 * r * (r - 0.5);
weights[2] = 4.0 * r * (1.0 - r);
}
//----------------------------------------------------------------------------
// Derivatives in parametric space.
void vtkQuadraticEdge::InterpolationDerivs(double pcoords[3], double derivs[3])
{
double r = pcoords[0];
derivs[0] = 4.0 * r - 3.0;
derivs[1] = 4.0 * r - 1.0;
derivs[2] = 4.0 - r * 8.0;
}
//----------------------------------------------------------------------------
static double vtkQEdgeCellPCoords[9] = {0.0,0.0,0.0, 1.0,0.0,0.0, 0.5,0.0,0.0};
double *vtkQuadraticEdge::GetParametricCoords()
{
return vtkQEdgeCellPCoords;
}
//----------------------------------------------------------------------------
void vtkQuadraticEdge::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Line:\n";
this->Line->PrintSelf(os,indent.GetNextIndent());
}
<|endoftext|>
|
<commit_before>#pragma once
#include <vector>
#include <iterator>
#include <functional>
namespace helene
{
template <class PropertyType>
class persistent_iterator_
{
template <class NodeType, class EdgeType>
friend class dag;
public:
typedef typename std::vector<PropertyType>::size_type size_type;
typedef typename std::vector<PropertyType>::difference_type difference_type;
typedef PropertyType value_type;
typedef PropertyType* pointer;
typedef PropertyType& reference;
public:
persistent_iterator_(size_type current_index,
std::vector<PropertyType>& nodes)
: current_index_(current_index), nodes_ref_(nodes)
{
}
public:
// Iterator concept member functions
reference operator*()
{
return nodes_ref_.get()[current_index_];
}
persistent_iterator_& operator++()
{
++current_index_;
return *this;
}
// EqualityComparable
bool
operator==(const persistent_iterator_& other) const
{
return (current_index_ == other.current_index_) &&
(&(nodes_ref_.get()) == &(other.nodes_ref_.get()));
}
// InputIterator
bool
operator!=(const persistent_iterator_& other) const
{
return !(*this == other);
}
pointer operator->()
{
return &(nodes_ref_.get()[current_index_]);
}
persistent_iterator_ operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
// BidirectionalIterator
persistent_iterator_& operator--()
{
--current_index_;
return *this;
}
persistent_iterator_ operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
// RandomAccessIterator
persistent_iterator_&
operator+=(difference_type n)
{
current_index_ += n;
return *this;
}
persistent_iterator_
operator+(difference_type n) const
{
return persistent_iterator_(current_index_ + n, nodes_ref_);
}
friend persistent_iterator_
operator+(difference_type lhs, const persistent_iterator_& rhs)
{
return rhs + lhs;
}
persistent_iterator_&
operator-=(difference_type n)
{
current_index_ -= n;
return *this;
}
persistent_iterator_
operator-(difference_type n) const
{
return persistent_iterator_(current_index_ - n, nodes_ref_);
}
difference_type
operator-(const persistent_iterator_& other) const
{
return current_index_ - other.current_index_;
}
reference operator[](difference_type n)
{
return nodes_ref_.get()[current_index_ + n];
}
bool
operator<(const persistent_iterator_& other) const
{
return current_index_ < other.current_index_;
}
bool
operator>(const persistent_iterator_& other) const
{
return current_index_ > other.current_index_;
}
bool
operator<=(const persistent_iterator_& other) const
{
return current_index_ <= other.current_index_;
}
bool
operator>=(const persistent_iterator_& other) const
{
return current_index_ >= other.current_index_;
}
private:
std::reference_wrapper<std::vector<PropertyType>> nodes_ref_;
size_type current_index_;
};
template <class NodeType, class EdgeType>
class dag
{
public:
////////////////////////////////////////////////////////////////////////////
// public typedefs
// node typedefs
typedef NodeType value_type;
typedef NodeType& reference;
typedef const NodeType& const_reference;
typedef typename std::vector<NodeType>::difference_type difference_type;
typedef typename std::vector<NodeType>::size_type size_type;
typedef persistent_iterator_<NodeType> iterator;
// edge typedefs
typedef EdgeType edge_value_type;
typedef EdgeType& edge_reference;
typedef const EdgeType& const_edge_reference;
typedef typename std::vector<EdgeType>::size_type edge_size_type;
typedef
typename std::vector<EdgeType>::difference_type edge_difference_type;
typedef persistent_iterator_<EdgeType> edge_iterator;
private:
////////////////////////////////////////////////////////////////////////////
// internal classes
// indices to properties of the associated edge
struct edge
{
edge(size_type from, size_type to)
: from_property(from), to_property(to)
{
}
size_type from_property;
size_type to_property;
bool
operator==(const edge& other) const
{
return (from_property == other.from_property) &&
(to_property == other.to_property);
}
};
public:
////////////////////////////////////////////////////////////////////////////
// Container concept member functions
dag() = default;
dag(const dag&) = default;
dag& operator=(const dag&) = default;
iterator
begin()
{
return iterator(0, node_properties_);
}
iterator
end()
{
return iterator(node_properties_.size(), node_properties_);
}
edge_iterator
edge_begin()
{
return edge_iterator(0, edge_properties_);
}
edge_iterator
edge_end()
{
return edge_iterator(edge_properties_.size(), edge_properties_);
}
bool
operator==(const dag& other) const
{
return (node_properties_ == other.node_properties_) &&
(edge_properties_ == other.edge_properties_) &&
(edges_ == other.edges_);
}
bool
operator!=(const dag& other) const
{
return !(*this == other);
}
void
swap(dag& other)
{
node_properties_.swap(other.node_properties_);
edge_properties_.swap(other.edge_properties_);
edges_.swap(other.edges_);
}
size_type
size() const
{
return node_properties_.size();
}
edge_size_type
edge_size() const
{
return edge_properties_.size();
}
bool
empty() const
{
return node_properties_.empty();
}
bool
edge_empty() const
{
return edge_properties_.empty();
}
public:
////////////////////////////////////////////////////////////////////////////
// dag specific member functions
// Add node
iterator
add_node(const NodeType& prop)
{
const auto index = node_properties_.size();
node_properties_.push_back(prop);
return iterator(index, node_properties_);
}
// Add edge between nodes.
// If edge introduces cycle edge will not be inserted.
// Returns iterator to edge property or edge_end() if edge was prevented
// from being inserted.
edge_iterator
add_edge(iterator from, iterator to, const EdgeType& prop)
{
const auto index = edge_properties_.size();
const auto from_index = from.current_index_;
const auto to_index = to.current_index_;
edge_properties_.push_back(prop);
edges_.emplace_back(from_index, to_index);
return edge_iterator(index, edge_properties_);
}
std::pair<iterator, iterator>
edge_endpoints(edge_iterator ed)
{
const auto edge_index = ed.current_index_;
return std::make_pair(
iterator(edges_[edge_index].from_property, node_properties_),
iterator(edges_[edge_index].to_property, node_properties_));
}
private:
std::vector<NodeType> node_properties_;
std::vector<EdgeType> edge_properties_;
std::vector<edge> edges_;
};
}
namespace std
{
template <class PropertyType>
struct iterator_traits<helene::persistent_iterator_<PropertyType>>
{
typedef typename helene::persistent_iterator_<PropertyType>::difference_type
difference_type;
typedef typename helene::persistent_iterator_<PropertyType>::value_type
value_type;
typedef
typename helene::persistent_iterator_<PropertyType>::pointer pointer;
typedef typename helene::persistent_iterator_<PropertyType>::reference
reference;
typedef random_access_iterator_tag iterator_category;
};
}
<commit_msg>Comments. modified: include/dag.hpp<commit_after>#pragma once
#include <vector>
#include <iterator>
#include <functional>
namespace helene
{
template <class PropertyType>
class persistent_iterator_
{
template <class NodeType, class EdgeType>
friend class dag;
public:
typedef typename std::vector<PropertyType>::size_type size_type;
typedef typename std::vector<PropertyType>::difference_type difference_type;
typedef PropertyType value_type;
typedef PropertyType* pointer;
typedef PropertyType& reference;
public:
persistent_iterator_(size_type current_index,
std::vector<PropertyType>& nodes)
: current_index_(current_index), nodes_ref_(nodes)
{
}
public:
// Iterator concept member functions
reference operator*()
{
return nodes_ref_.get()[current_index_];
}
persistent_iterator_& operator++()
{
++current_index_;
return *this;
}
// EqualityComparable
bool
operator==(const persistent_iterator_& other) const
{
return (current_index_ == other.current_index_) &&
(&(nodes_ref_.get()) == &(other.nodes_ref_.get()));
}
// InputIterator
bool
operator!=(const persistent_iterator_& other) const
{
return !(*this == other);
}
pointer operator->()
{
return &(nodes_ref_.get()[current_index_]);
}
persistent_iterator_ operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
// BidirectionalIterator
persistent_iterator_& operator--()
{
--current_index_;
return *this;
}
persistent_iterator_ operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
// RandomAccessIterator
persistent_iterator_&
operator+=(difference_type n)
{
current_index_ += n;
return *this;
}
persistent_iterator_
operator+(difference_type n) const
{
return persistent_iterator_(current_index_ + n, nodes_ref_);
}
friend persistent_iterator_
operator+(difference_type lhs, const persistent_iterator_& rhs)
{
return rhs + lhs;
}
persistent_iterator_&
operator-=(difference_type n)
{
current_index_ -= n;
return *this;
}
persistent_iterator_
operator-(difference_type n) const
{
return persistent_iterator_(current_index_ - n, nodes_ref_);
}
difference_type
operator-(const persistent_iterator_& other) const
{
return current_index_ - other.current_index_;
}
reference operator[](difference_type n)
{
return nodes_ref_.get()[current_index_ + n];
}
bool
operator<(const persistent_iterator_& other) const
{
return current_index_ < other.current_index_;
}
bool
operator>(const persistent_iterator_& other) const
{
return current_index_ > other.current_index_;
}
bool
operator<=(const persistent_iterator_& other) const
{
return current_index_ <= other.current_index_;
}
bool
operator>=(const persistent_iterator_& other) const
{
return current_index_ >= other.current_index_;
}
private:
std::reference_wrapper<std::vector<PropertyType>> nodes_ref_;
size_type current_index_;
};
template <class NodeType, class EdgeType>
class dag
{
public:
////////////////////////////////////////////////////////////////////////////
// public typedefs
// node typedefs
typedef NodeType value_type;
typedef NodeType& reference;
typedef const NodeType& const_reference;
typedef typename std::vector<NodeType>::difference_type difference_type;
typedef typename std::vector<NodeType>::size_type size_type;
typedef persistent_iterator_<NodeType> iterator;
// edge typedefs
typedef EdgeType edge_value_type;
typedef EdgeType& edge_reference;
typedef const EdgeType& const_edge_reference;
typedef typename std::vector<EdgeType>::size_type edge_size_type;
typedef
typename std::vector<EdgeType>::difference_type edge_difference_type;
typedef persistent_iterator_<EdgeType> edge_iterator;
private:
////////////////////////////////////////////////////////////////////////////
// internal classes
// indices to properties of the associated edge
struct edge
{
edge(size_type from, size_type to)
: from_property(from), to_property(to)
{
}
size_type from_property;
size_type to_property;
bool
operator==(const edge& other) const
{
return (from_property == other.from_property) &&
(to_property == other.to_property);
}
};
public:
////////////////////////////////////////////////////////////////////////////
// Container concept member functions
dag() = default;
dag(const dag&) = default;
dag& operator=(const dag&) = default;
iterator
begin()
{
return iterator(0, node_properties_);
}
iterator
end()
{
return iterator(node_properties_.size(), node_properties_);
}
edge_iterator
edge_begin()
{
return edge_iterator(0, edge_properties_);
}
edge_iterator
edge_end()
{
return edge_iterator(edge_properties_.size(), edge_properties_);
}
bool
operator==(const dag& other) const
{
return (node_properties_ == other.node_properties_) &&
(edge_properties_ == other.edge_properties_) &&
(edges_ == other.edges_);
}
bool
operator!=(const dag& other) const
{
return !(*this == other);
}
void
swap(dag& other)
{
node_properties_.swap(other.node_properties_);
edge_properties_.swap(other.edge_properties_);
edges_.swap(other.edges_);
}
size_type
size() const
{
return node_properties_.size();
}
edge_size_type
edge_size() const
{
return edge_properties_.size();
}
bool
empty() const
{
return node_properties_.empty();
}
bool
edge_empty() const
{
return edge_properties_.empty();
}
public:
////////////////////////////////////////////////////////////////////////////
// dag specific member functions
// Add node
iterator
add_node(const NodeType& prop)
{
const auto index = node_properties_.size();
node_properties_.push_back(prop);
return iterator(index, node_properties_);
}
// Add edge between nodes.
// If edge introduces cycle edge will not be inserted.
// Returns iterator to edge property or edge_end() if edge was prevented
// from being inserted.
edge_iterator
add_edge(iterator from, iterator to, const EdgeType& prop)
{
const auto index = edge_properties_.size();
const auto from_index = from.current_index_;
const auto to_index = to.current_index_;
edge_properties_.push_back(prop);
edges_.emplace_back(from_index, to_index);
return edge_iterator(index, edge_properties_);
}
// returns pair of iterator to nodes connected by edge ed <from , to>
std::pair<iterator, iterator>
edge_endpoints(edge_iterator ed)
{
const auto edge_index = ed.current_index_;
return std::make_pair(
iterator(edges_[edge_index].from_property, node_properties_),
iterator(edges_[edge_index].to_property, node_properties_));
}
private:
std::vector<NodeType> node_properties_;
std::vector<EdgeType> edge_properties_;
std::vector<edge> edges_;
};
}
namespace std
{
template <class PropertyType>
struct iterator_traits<helene::persistent_iterator_<PropertyType>>
{
typedef typename helene::persistent_iterator_<PropertyType>::difference_type
difference_type;
typedef typename helene::persistent_iterator_<PropertyType>::value_type
value_type;
typedef
typename helene::persistent_iterator_<PropertyType>::pointer pointer;
typedef typename helene::persistent_iterator_<PropertyType>::reference
reference;
typedef random_access_iterator_tag iterator_category;
};
}
<|endoftext|>
|
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2015 Pedro Côrte-Real
Copyright (C) 2017 Axel Waggershauser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/TiffIFD.h"
#include "common/Common.h" // for getHostEndianness, uint32, make_...
#include "common/NORangesSet.h" // for NORangesSet
#include "common/RawspeedException.h" // for RawspeedException
#include "io/IOException.h" // for IOException
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffTag.h" // for TiffTag, ::DNGPRIVATEDATA, ::EXI...
#include <algorithm> // for move
#include <cstdint> // for UINT32_MAX
#include <map> // for map, _Rb_tree_const_iterator, al...
#include <memory> // for default_delete, unique_ptr
#include <string> // for operator==, string, basic_string
#include <utility> // for pair
#include <vector> // for vector
using std::string;
using std::vector;
namespace rawspeed {
void TiffIFD::parseIFDEntry(NORangesSet<Buffer>* ifds, ByteStream* bs) {
TiffEntryOwner t;
auto origPos = bs->getPosition();
try {
t = std::make_unique<TiffEntry>(this, bs);
} catch (IOException&) { // Ignore unparsable entry
// fix probably broken position due to interruption by exception
// i.e. setting it to the next entry.
bs->setPosition(origPos + 12);
return;
}
try {
switch (t->tag) {
case DNGPRIVATEDATA:
add(parseDngPrivateData(ifds, t.get()));
break;
case MAKERNOTE:
case MAKERNOTE_ALT:
add(parseMakerNote(ifds, t.get()));
break;
case FUJI_RAW_IFD:
case SUBIFDS:
case EXIFIFDPOINTER:
for (uint32 j = 0; j < t->count; j++)
add(std::make_unique<TiffIFD>(this, ifds, *bs, t->getU32(j)));
break;
default:
add(move(t));
}
} catch (RawspeedException&) { // Unparsable private data are added as entries
add(move(t));
}
}
TiffIFD::TiffIFD(TiffIFD* parent_) : parent(parent_) {}
TiffIFD::TiffIFD(TiffIFD* parent_, NORangesSet<Buffer>* ifds,
const DataBuffer& data, uint32 offset)
: TiffIFD(parent_) {
// see TiffParser::parse: UINT32_MAX is used to mark the "virtual" top level
// TiffRootIFD in a tiff file
if (offset == UINT32_MAX)
return;
checkOverflow();
ByteStream bs(data);
bs.setPosition(offset);
// Directory entries in this IFD
auto numEntries = bs.getU16();
// 2 bytes for entry count
// each entry is 12 bytes
// 4-byte offset to the next IFD at the end
const auto IFDFullSize = 2 + 4 + 12 * numEntries;
const Buffer IFDBuf(data.getSubView(offset, IFDFullSize));
if (ifds && !ifds->emplace(IFDBuf).second)
ThrowTPE("Two IFD's overlap. Raw corrupt!");
for (uint32 i = 0; i < numEntries; i++)
parseIFDEntry(ifds, &bs);
nextIFD = bs.getU32();
}
TiffRootIFDOwner TiffIFD::parseDngPrivateData(NORangesSet<Buffer>* ifds,
TiffEntry* t) {
/*
1. Six bytes containing the zero-terminated string "Adobe". (The DNG specification calls for the DNGPrivateData tag to start with an ASCII string identifying the creator/format).
2. 4 bytes: an ASCII string ("MakN" for a Makernote), indicating what sort of data is being stored here. Note that this is not zero-terminated.
3. A four-byte count (number of data bytes following); this is the length of the original MakerNote data. (This is always in "most significant byte first" format).
4. 2 bytes: the byte-order indicator from the original file (the usual 'MM'/4D4D or 'II'/4949).
5. 4 bytes: the original file offset for the MakerNote tag data (stored according to the byte order given above).
6. The contents of the MakerNote tag. This is a simple byte-for-byte copy, with no modification.
*/
ByteStream& bs = t->getData();
if (!bs.skipPrefix("Adobe", 6))
ThrowTPE("Not Adobe Private data");
if (!bs.skipPrefix("MakN", 4))
ThrowTPE("Not Makernote");
bs.setByteOrder(Endianness::big);
uint32 makerNoteSize = bs.getU32();
if (makerNoteSize != bs.getRemainSize())
ThrowTPE("Error reading TIFF structure (invalid size). File Corrupt");
bs.setByteOrder(getTiffByteOrder(bs, 0, "DNG makernote"));
bs.skipBytes(2);
uint32 makerNoteOffset = bs.getU32();
makerNoteSize -= 6; // update size of orinial maker note, we skipped 2+4 bytes
// Update the underlying buffer of t, such that the maker note data starts at its original offset
bs.rebase(makerNoteOffset, makerNoteSize);
return parseMakerNote(ifds, t);
}
/* This will attempt to parse makernotes and return it as an IFD */
TiffRootIFDOwner TiffIFD::parseMakerNote(NORangesSet<Buffer>* ifds,
TiffEntry* t) {
// go up the IFD tree and try to find the MAKE entry on each level.
// we can not go all the way to the top first because this partial tree
// is not yet added to the TiffRootIFD.
TiffIFD* p = this;
TiffEntry* makeEntry;
do {
makeEntry = p->getEntryRecursive(MAKE);
p = p->parent;
} while (!makeEntry && p);
string make = makeEntry != nullptr ? trimSpaces(makeEntry->getString()) : "";
ByteStream bs = t->getData();
// helper function for easy setup of ByteStream buffer for the different maker note types
// 'rebase' means position 0 of new stream equals current position
// 'newPosition' is the position where the IFD starts
// 'byteOrderOffset' is the position wher the 2 magic bytes (II/MM) may be found
// 'context' is a string providing error information in case the byte order parsing should fail
auto setup = [&bs](bool rebase, uint32 newPosition,
uint32 byteOrderOffset = 0,
const char *context = nullptr) {
if (rebase)
bs = bs.getSubStream(bs.getPosition(), bs.getRemainSize());
if (context)
bs.setByteOrder(getTiffByteOrder(bs, byteOrderOffset, context));
bs.skipBytes(newPosition);
};
if (bs.hasPrefix("AOC\0", 4)) {
setup(false, 6, 4, "Pentax makernote");
} else if (bs.hasPrefix("PENTAX", 6)) {
setup(true, 10, 8, "Pentax makernote");
} else if (bs.hasPrefix("FUJIFILM\x0c\x00\x00\x00", 12)) {
bs.setByteOrder(Endianness::little);
setup(true, 12);
} else if (bs.hasPrefix("Nikon\x00\x02", 7)) {
// this is Nikon type 3 maker note format
// TODO: implement Nikon type 1 maker note format
// see http://www.ozhiker.com/electronics/pjmt/jpeg_info/nikon_mn.html
bs.skipBytes(10);
setup(true, 8, 0, "Nikon makernote");
} else if (bs.hasPrefix("OLYMPUS", 7)) { // new Olympus
setup(true, 12);
} else if (bs.hasPrefix("OLYMP", 5)) { // old Olympus
setup(true, 8);
} else if (bs.hasPrefix("EPSON", 5)) {
setup(false, 8);
} else if (bs.hasPatternAt("Exif", 4, 6)) {
// TODO: for none of the rawsamples.ch files from Panasonic is this true, instead their MakerNote start with "Panasonic"
// Panasonic has the word Exif at byte 6, a complete Tiff header starts at byte 12
// This TIFF is 0 offset based
setup(false, 20, 12, "Panosonic makernote");
} else if (make == "SAMSUNG") {
// Samsung has no identification in its MakerNote but starts with the IFD right away
setup(true, 0);
} else {
// cerr << "default MakerNote from " << make << endl; // Canon, Nikon (type 2), Sony, Minolta, Ricoh, Leica, Hasselblad, etc.
// At least one MAKE has not been handled explicitly and starts its MakerNote with an endian prefix: Kodak
if (bs.skipPrefix("II", 2)) {
bs.setByteOrder(Endianness::little);
} else if (bs.skipPrefix("MM", 2)) {
bs.setByteOrder(Endianness::big);
}
}
// Attempt to parse the rest as an IFD
return std::make_unique<TiffRootIFD>(this, ifds, bs, bs.getPosition());
}
std::vector<const TiffIFD*> TiffIFD::getIFDsWithTag(TiffTag tag) const {
vector<const TiffIFD*> matchingIFDs;
if (entries.find(tag) != entries.end()) {
matchingIFDs.push_back(this);
}
for (auto& i : subIFDs) {
vector<const TiffIFD*> t = i->getIFDsWithTag(tag);
matchingIFDs.insert(matchingIFDs.end(), t.begin(), t.end());
}
return matchingIFDs;
}
const TiffIFD* TiffIFD::getIFDWithTag(TiffTag tag, uint32 index) const
{
auto ifds = getIFDsWithTag(tag);
if (index >= ifds.size())
ThrowTPE("failed to find %u ifs with tag 0x%04x", index + 1, tag);
return ifds[index];
}
TiffEntry* __attribute__((pure)) TiffIFD::getEntryRecursive(TiffTag tag) const {
auto i = entries.find(tag);
if (i != entries.end()) {
return i->second.get();
}
for (auto &j : subIFDs) {
TiffEntry *entry = j->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
void TiffIFD::checkOverflow() {
TiffIFD* p = this;
int i = 0;
while ((p = p->parent) != nullptr) {
i++;
if (i > 5)
ThrowTPE("TiffIFD cascading overflow.");
}
}
void TiffIFD::add(TiffIFDOwner subIFD) {
checkOverflow();
if (subIFDs.size() > 100)
ThrowTPE("TIFF file has too many SubIFDs, probably broken");
subIFD->parent = this;
subIFDs.push_back(move(subIFD));
}
void TiffIFD::add(TiffEntryOwner entry) {
entry->parent = this;
entries[entry->tag] = move(entry);
}
TiffEntry* TiffIFD::getEntry(TiffTag tag) const {
auto i = entries.find(tag);
if (i == entries.end())
ThrowTPE("Entry 0x%x not found.", tag);
return i->second.get();
}
TiffID TiffRootIFD::getID() const
{
TiffID id;
auto makeE = getEntryRecursive(MAKE);
auto modelE = getEntryRecursive(MODEL);
if (!makeE)
ThrowTPE("Failed to find MAKE entry.");
if (!modelE)
ThrowTPE("Failed to find MODEL entry.");
id.make = trimSpaces(makeE->getString());
id.model = trimSpaces(modelE->getString());
return id;
}
} // namespace rawspeed
<commit_msg>TiffRootIFD: assert that NORangesSet is always passed.<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2015 Pedro Côrte-Real
Copyright (C) 2017 Axel Waggershauser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/TiffIFD.h"
#include "common/Common.h" // for getHostEndianness, uint32, make_...
#include "common/NORangesSet.h" // for NORangesSet
#include "common/RawspeedException.h" // for RawspeedException
#include "io/IOException.h" // for IOException
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffTag.h" // for TiffTag, ::DNGPRIVATEDATA, ::EXI...
#include <algorithm> // for move
#include <cstdint> // for UINT32_MAX
#include <map> // for map, _Rb_tree_const_iterator, al...
#include <memory> // for default_delete, unique_ptr
#include <string> // for operator==, string, basic_string
#include <utility> // for pair
#include <vector> // for vector
using std::string;
using std::vector;
namespace rawspeed {
void TiffIFD::parseIFDEntry(NORangesSet<Buffer>* ifds, ByteStream* bs) {
assert(ifds);
TiffEntryOwner t;
auto origPos = bs->getPosition();
try {
t = std::make_unique<TiffEntry>(this, bs);
} catch (IOException&) { // Ignore unparsable entry
// fix probably broken position due to interruption by exception
// i.e. setting it to the next entry.
bs->setPosition(origPos + 12);
return;
}
try {
switch (t->tag) {
case DNGPRIVATEDATA:
add(parseDngPrivateData(ifds, t.get()));
break;
case MAKERNOTE:
case MAKERNOTE_ALT:
add(parseMakerNote(ifds, t.get()));
break;
case FUJI_RAW_IFD:
case SUBIFDS:
case EXIFIFDPOINTER:
for (uint32 j = 0; j < t->count; j++)
add(std::make_unique<TiffIFD>(this, ifds, *bs, t->getU32(j)));
break;
default:
add(move(t));
}
} catch (RawspeedException&) { // Unparsable private data are added as entries
add(move(t));
}
}
TiffIFD::TiffIFD(TiffIFD* parent_) : parent(parent_) {}
TiffIFD::TiffIFD(TiffIFD* parent_, NORangesSet<Buffer>* ifds,
const DataBuffer& data, uint32 offset)
: TiffIFD(parent_) {
// see TiffParser::parse: UINT32_MAX is used to mark the "virtual" top level
// TiffRootIFD in a tiff file
if (offset == UINT32_MAX)
return;
assert(ifds);
checkOverflow();
ByteStream bs(data);
bs.setPosition(offset);
// Directory entries in this IFD
auto numEntries = bs.getU16();
// 2 bytes for entry count
// each entry is 12 bytes
// 4-byte offset to the next IFD at the end
const auto IFDFullSize = 2 + 4 + 12 * numEntries;
const Buffer IFDBuf(data.getSubView(offset, IFDFullSize));
if (!ifds->emplace(IFDBuf).second)
ThrowTPE("Two IFD's overlap. Raw corrupt!");
for (uint32 i = 0; i < numEntries; i++)
parseIFDEntry(ifds, &bs);
nextIFD = bs.getU32();
}
TiffRootIFDOwner TiffIFD::parseDngPrivateData(NORangesSet<Buffer>* ifds,
TiffEntry* t) {
assert(ifds);
/*
1. Six bytes containing the zero-terminated string "Adobe". (The DNG specification calls for the DNGPrivateData tag to start with an ASCII string identifying the creator/format).
2. 4 bytes: an ASCII string ("MakN" for a Makernote), indicating what sort of data is being stored here. Note that this is not zero-terminated.
3. A four-byte count (number of data bytes following); this is the length of the original MakerNote data. (This is always in "most significant byte first" format).
4. 2 bytes: the byte-order indicator from the original file (the usual 'MM'/4D4D or 'II'/4949).
5. 4 bytes: the original file offset for the MakerNote tag data (stored according to the byte order given above).
6. The contents of the MakerNote tag. This is a simple byte-for-byte copy, with no modification.
*/
ByteStream& bs = t->getData();
if (!bs.skipPrefix("Adobe", 6))
ThrowTPE("Not Adobe Private data");
if (!bs.skipPrefix("MakN", 4))
ThrowTPE("Not Makernote");
bs.setByteOrder(Endianness::big);
uint32 makerNoteSize = bs.getU32();
if (makerNoteSize != bs.getRemainSize())
ThrowTPE("Error reading TIFF structure (invalid size). File Corrupt");
bs.setByteOrder(getTiffByteOrder(bs, 0, "DNG makernote"));
bs.skipBytes(2);
uint32 makerNoteOffset = bs.getU32();
makerNoteSize -= 6; // update size of orinial maker note, we skipped 2+4 bytes
// Update the underlying buffer of t, such that the maker note data starts at its original offset
bs.rebase(makerNoteOffset, makerNoteSize);
return parseMakerNote(ifds, t);
}
/* This will attempt to parse makernotes and return it as an IFD */
TiffRootIFDOwner TiffIFD::parseMakerNote(NORangesSet<Buffer>* ifds,
TiffEntry* t) {
assert(ifds);
// go up the IFD tree and try to find the MAKE entry on each level.
// we can not go all the way to the top first because this partial tree
// is not yet added to the TiffRootIFD.
TiffIFD* p = this;
TiffEntry* makeEntry;
do {
makeEntry = p->getEntryRecursive(MAKE);
p = p->parent;
} while (!makeEntry && p);
string make = makeEntry != nullptr ? trimSpaces(makeEntry->getString()) : "";
ByteStream bs = t->getData();
// helper function for easy setup of ByteStream buffer for the different maker note types
// 'rebase' means position 0 of new stream equals current position
// 'newPosition' is the position where the IFD starts
// 'byteOrderOffset' is the position wher the 2 magic bytes (II/MM) may be found
// 'context' is a string providing error information in case the byte order parsing should fail
auto setup = [&bs](bool rebase, uint32 newPosition,
uint32 byteOrderOffset = 0,
const char *context = nullptr) {
if (rebase)
bs = bs.getSubStream(bs.getPosition(), bs.getRemainSize());
if (context)
bs.setByteOrder(getTiffByteOrder(bs, byteOrderOffset, context));
bs.skipBytes(newPosition);
};
if (bs.hasPrefix("AOC\0", 4)) {
setup(false, 6, 4, "Pentax makernote");
} else if (bs.hasPrefix("PENTAX", 6)) {
setup(true, 10, 8, "Pentax makernote");
} else if (bs.hasPrefix("FUJIFILM\x0c\x00\x00\x00", 12)) {
bs.setByteOrder(Endianness::little);
setup(true, 12);
} else if (bs.hasPrefix("Nikon\x00\x02", 7)) {
// this is Nikon type 3 maker note format
// TODO: implement Nikon type 1 maker note format
// see http://www.ozhiker.com/electronics/pjmt/jpeg_info/nikon_mn.html
bs.skipBytes(10);
setup(true, 8, 0, "Nikon makernote");
} else if (bs.hasPrefix("OLYMPUS", 7)) { // new Olympus
setup(true, 12);
} else if (bs.hasPrefix("OLYMP", 5)) { // old Olympus
setup(true, 8);
} else if (bs.hasPrefix("EPSON", 5)) {
setup(false, 8);
} else if (bs.hasPatternAt("Exif", 4, 6)) {
// TODO: for none of the rawsamples.ch files from Panasonic is this true, instead their MakerNote start with "Panasonic"
// Panasonic has the word Exif at byte 6, a complete Tiff header starts at byte 12
// This TIFF is 0 offset based
setup(false, 20, 12, "Panosonic makernote");
} else if (make == "SAMSUNG") {
// Samsung has no identification in its MakerNote but starts with the IFD right away
setup(true, 0);
} else {
// cerr << "default MakerNote from " << make << endl; // Canon, Nikon (type 2), Sony, Minolta, Ricoh, Leica, Hasselblad, etc.
// At least one MAKE has not been handled explicitly and starts its MakerNote with an endian prefix: Kodak
if (bs.skipPrefix("II", 2)) {
bs.setByteOrder(Endianness::little);
} else if (bs.skipPrefix("MM", 2)) {
bs.setByteOrder(Endianness::big);
}
}
// Attempt to parse the rest as an IFD
return std::make_unique<TiffRootIFD>(this, ifds, bs, bs.getPosition());
}
std::vector<const TiffIFD*> TiffIFD::getIFDsWithTag(TiffTag tag) const {
vector<const TiffIFD*> matchingIFDs;
if (entries.find(tag) != entries.end()) {
matchingIFDs.push_back(this);
}
for (auto& i : subIFDs) {
vector<const TiffIFD*> t = i->getIFDsWithTag(tag);
matchingIFDs.insert(matchingIFDs.end(), t.begin(), t.end());
}
return matchingIFDs;
}
const TiffIFD* TiffIFD::getIFDWithTag(TiffTag tag, uint32 index) const
{
auto ifds = getIFDsWithTag(tag);
if (index >= ifds.size())
ThrowTPE("failed to find %u ifs with tag 0x%04x", index + 1, tag);
return ifds[index];
}
TiffEntry* __attribute__((pure)) TiffIFD::getEntryRecursive(TiffTag tag) const {
auto i = entries.find(tag);
if (i != entries.end()) {
return i->second.get();
}
for (auto &j : subIFDs) {
TiffEntry *entry = j->getEntryRecursive(tag);
if (entry)
return entry;
}
return nullptr;
}
void TiffIFD::checkOverflow() {
TiffIFD* p = this;
int i = 0;
while ((p = p->parent) != nullptr) {
i++;
if (i > 5)
ThrowTPE("TiffIFD cascading overflow.");
}
}
void TiffIFD::add(TiffIFDOwner subIFD) {
checkOverflow();
if (subIFDs.size() > 100)
ThrowTPE("TIFF file has too many SubIFDs, probably broken");
subIFD->parent = this;
subIFDs.push_back(move(subIFD));
}
void TiffIFD::add(TiffEntryOwner entry) {
entry->parent = this;
entries[entry->tag] = move(entry);
}
TiffEntry* TiffIFD::getEntry(TiffTag tag) const {
auto i = entries.find(tag);
if (i == entries.end())
ThrowTPE("Entry 0x%x not found.", tag);
return i->second.get();
}
TiffID TiffRootIFD::getID() const
{
TiffID id;
auto makeE = getEntryRecursive(MAKE);
auto modelE = getEntryRecursive(MODEL);
if (!makeE)
ThrowTPE("Failed to find MAKE entry.");
if (!modelE)
ThrowTPE("Failed to find MODEL entry.");
id.make = trimSpaces(makeE->getString());
id.model = trimSpaces(modelE->getString());
return id;
}
} // namespace rawspeed
<|endoftext|>
|
<commit_before><commit_msg>fixed call to p objects<commit_after><|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $
#ifndef DATASOURCE_HPP
#define DATASOURCE_HPP
// stl
#include <map>
#include <string>
// boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/ctrans.hpp>
#include <mapnik/params.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/query.hpp>
#include <mapnik/feature_layer_desc.hpp>
namespace mapnik {
typedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr;
struct MAPNIK_DECL Featureset
{
virtual feature_ptr next()=0;
virtual ~Featureset() {};
};
typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr;
class MAPNIK_DECL datasource_exception : public std::exception
{
private:
const std::string message_;
public:
datasource_exception(const std::string& message=std::string())
:message_(message) {}
~datasource_exception() throw() {}
virtual const char* what() const throw()
{
return message_.c_str();
}
};
class MAPNIK_DECL datasource : private boost::noncopyable
{
parameters params_;
public:
enum {
Vector,
Raster
};
datasource (parameters const& params)
: params_(params) {}
parameters const& params() const
{
return params_;
}
virtual int type() const=0;
virtual featureset_ptr features(const query& q) const=0;
virtual featureset_ptr features_at_point(coord2d const& pt) const=0;
virtual Envelope<double> envelope() const=0;
virtual layer_descriptor get_descriptor() const=0;
virtual ~datasource() {};
};
typedef std::string datasource_name();
typedef datasource* create_ds(const parameters& params);
typedef void destroy_ds(datasource *ds);
class datasource_deleter
{
public:
void operator() (datasource* ds)
{
delete ds;
}
};
typedef boost::shared_ptr<datasource> datasource_ptr;
#define DATASOURCE_PLUGIN(classname) \
extern "C" MAPNIK_DECL std::string datasource_name() \
{ \
return classname::name(); \
} \
extern "C" MAPNIK_DECL datasource* create(const parameters ¶ms) \
{ \
return new classname(params); \
} \
extern "C" MAPNIK_DECL void destroy(datasource *ds) \
{ \
delete ds; \
} \
//
}
#endif //DATASOURCE_HPP
<commit_msg>make params_ accessible from derived classes<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $
#ifndef DATASOURCE_HPP
#define DATASOURCE_HPP
// stl
#include <map>
#include <string>
// boost
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/ctrans.hpp>
#include <mapnik/params.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/query.hpp>
#include <mapnik/feature_layer_desc.hpp>
namespace mapnik {
typedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr;
struct MAPNIK_DECL Featureset
{
virtual feature_ptr next()=0;
virtual ~Featureset() {};
};
typedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr;
class MAPNIK_DECL datasource_exception : public std::exception
{
private:
const std::string message_;
public:
datasource_exception(const std::string& message=std::string())
:message_(message) {}
~datasource_exception() throw() {}
virtual const char* what() const throw()
{
return message_.c_str();
}
};
class MAPNIK_DECL datasource : private boost::noncopyable
{
public:
enum {
Vector,
Raster
};
datasource (parameters const& params)
: params_(params) {}
parameters const& params() const
{
return params_;
}
virtual int type() const=0;
virtual featureset_ptr features(const query& q) const=0;
virtual featureset_ptr features_at_point(coord2d const& pt) const=0;
virtual Envelope<double> envelope() const=0;
virtual layer_descriptor get_descriptor() const=0;
virtual ~datasource() {};
protected:
parameters params_;
};
typedef std::string datasource_name();
typedef datasource* create_ds(const parameters& params);
typedef void destroy_ds(datasource *ds);
class datasource_deleter
{
public:
void operator() (datasource* ds)
{
delete ds;
}
};
typedef boost::shared_ptr<datasource> datasource_ptr;
#define DATASOURCE_PLUGIN(classname) \
extern "C" MAPNIK_DECL std::string datasource_name() \
{ \
return classname::name(); \
} \
extern "C" MAPNIK_DECL datasource* create(const parameters ¶ms) \
{ \
return new classname(params); \
} \
extern "C" MAPNIK_DECL void destroy(datasource *ds) \
{ \
delete ds; \
} \
//
}
#endif //DATASOURCE_HPP
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "detailswidget.h"
#include "detailsbutton.h"
#include <QtCore/QStack>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QPainter>
namespace Utils {
static const int MARGIN=8;
// This widget is using a grid layout and places the items
// in the following way:
//
// +------------+-------------------------+---------------+
// + toolWidget | summaryLabel | detailsButton |
// +------------+-------------------------+---------------+
// | | widget |
// +------------+-------------------------+---------------+
struct DetailsWidgetPrivate {
DetailsWidgetPrivate();
DetailsButton *m_detailsButton;
QGridLayout *m_grid;
QLabel *m_summaryLabel;
QWidget *m_toolWidget;
QWidget *m_widget;
QPixmap m_collapsedPixmap;
QPixmap m_expandedPixmap;
DetailsWidget::State m_state;
bool m_hovered;
};
DetailsWidgetPrivate::DetailsWidgetPrivate() :
m_detailsButton(new DetailsButton),
m_grid(new QGridLayout),
m_summaryLabel(new QLabel),
m_toolWidget(0),
m_widget(0),
m_state(DetailsWidget::Collapsed),
m_hovered(false)
{
}
DetailsWidget::DetailsWidget(QWidget *parent) :
QWidget(parent),
d(new DetailsWidgetPrivate)
{
d->m_summaryLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
d->m_summaryLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
d->m_summaryLabel->setContentsMargins(MARGIN, MARGIN, MARGIN, MARGIN);
d->m_grid->setContentsMargins(0, 0, 0, 0);
d->m_grid->setSpacing(0);
d->m_grid->addWidget(d->m_summaryLabel, 0, 1);
d->m_grid->addWidget(d->m_detailsButton, 0, 2);
setLayout(d->m_grid);
connect(d->m_detailsButton, SIGNAL(toggled(bool)),
this, SLOT(setExpanded(bool)));
updateControls();
}
DetailsWidget::~DetailsWidget()
{
delete d;
}
void DetailsWidget::paintEvent(QPaintEvent *paintEvent)
{
QWidget::paintEvent(paintEvent);
QPainter p(this);
QPoint topLeft(d->m_summaryLabel->geometry().left(), contentsRect().top());
const QRect paintArea(topLeft, contentsRect().bottomRight());
if (d->m_state != Expanded) {
if (d->m_collapsedPixmap.isNull() ||
d->m_collapsedPixmap.size() != size())
d->m_collapsedPixmap = cacheBackground(paintArea.size(), false);
p.drawPixmap(paintArea, d->m_collapsedPixmap);
} else {
if (d->m_expandedPixmap.isNull() ||
d->m_expandedPixmap.size() != size())
d->m_expandedPixmap = cacheBackground(paintArea.size(), true);
p.drawPixmap(paintArea, d->m_expandedPixmap);
}
}
void DetailsWidget::enterEvent(QEvent * event)
{
QWidget::enterEvent(event);
changeHoverState(true);
}
void DetailsWidget::leaveEvent(QEvent * event)
{
QWidget::leaveEvent(event);
changeHoverState(false);
}
void DetailsWidget::setSummaryText(const QString &text)
{
d->m_summaryLabel->setText(text);
}
QString DetailsWidget::summaryText() const
{
return d->m_summaryLabel->text();
}
DetailsWidget::State DetailsWidget::state() const
{
return d->m_state;
}
void DetailsWidget::setState(State state)
{
if (state == d->m_state)
return;
d->m_state = state;
updateControls();
}
void DetailsWidget::setExpanded(bool expanded)
{
setState(expanded ? Expanded : Collapsed);
}
void DetailsWidget::updateControls()
{
if (d->m_widget)
d->m_widget->setVisible(d->m_state == Expanded || d->m_state == NoSummary);
d->m_detailsButton->setChecked(d->m_state == Expanded && d->m_widget);
d->m_summaryLabel->setEnabled(d->m_state == Collapsed && d->m_widget);
d->m_detailsButton->setVisible(d->m_state != NoSummary);
d->m_summaryLabel->setVisible(d->m_state != NoSummary);
}
QWidget *DetailsWidget::widget() const
{
return d->m_widget;
}
void DetailsWidget::setWidget(QWidget *widget)
{
if (d->m_widget == widget)
return;
if (d->m_widget) {
d->m_grid->removeWidget(d->m_widget);
delete d->m_widget;
}
d->m_widget = widget;
if (d->m_widget) {
d->m_widget->setContentsMargins(MARGIN, MARGIN, MARGIN, MARGIN);
d->m_grid->addWidget(d->m_widget, 1, 1, 1, 2);
}
updateControls();
}
void DetailsWidget::setToolWidget(QWidget *widget)
{
if (d->m_toolWidget == widget)
return;
d->m_toolWidget = widget;
if (!d->m_toolWidget)
return;
d->m_toolWidget->adjustSize();
d->m_grid->addWidget(d->m_toolWidget, 0, 0, 1, 1, Qt::AlignCenter);
d->m_grid->setColumnMinimumWidth(0, d->m_toolWidget->width());
d->m_grid->setRowMinimumHeight(0, d->m_toolWidget->height());
changeHoverState(d->m_hovered);
}
QWidget *DetailsWidget::toolWidget() const
{
return d->m_toolWidget;
}
QPixmap DetailsWidget::cacheBackground(const QSize &size, bool expanded)
{
QLinearGradient lg;
lg.setCoordinateMode(QGradient::ObjectBoundingMode);
lg.setFinalStop(0, 1);
lg.setColorAt(0, palette().color(QPalette::Midlight));
lg.setColorAt(1, palette().color(QPalette::Button));
QPixmap pixmap(size);
QPainter p(&pixmap);
p.setBrush(lg);
p.setPen(QPen(palette().color(QPalette::Mid)));
p.drawRect(0, 0, size.width() - 1, size.height() - 1);
if (expanded) {
p.drawLine(0, d->m_widget->geometry().top() - 1,
d->m_summaryLabel->width(), d->m_widget->geometry().top() - 1);
}
return pixmap;
}
void DetailsWidget::changeHoverState(bool hovered)
{
if (!d->m_toolWidget)
return;
d->m_toolWidget->setVisible(hovered);
d->m_hovered = hovered;
}
} // namespace Utils
<commit_msg>Remove more/less-flicker in the projects tab<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "detailswidget.h"
#include "detailsbutton.h"
#include <QtCore/QStack>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QPainter>
#include <QtGui/QScrollArea>
#include <QtGui/QApplication>
namespace Utils {
static const int MARGIN=8;
// This widget is using a grid layout and places the items
// in the following way:
//
// +------------+-------------------------+---------------+
// + toolWidget | summaryLabel | detailsButton |
// +------------+-------------------------+---------------+
// | | widget |
// +------------+-------------------------+---------------+
struct DetailsWidgetPrivate {
DetailsWidgetPrivate();
DetailsButton *m_detailsButton;
QGridLayout *m_grid;
QLabel *m_summaryLabel;
QWidget *m_toolWidget;
QWidget *m_widget;
QPixmap m_collapsedPixmap;
QPixmap m_expandedPixmap;
DetailsWidget::State m_state;
bool m_hovered;
};
DetailsWidgetPrivate::DetailsWidgetPrivate() :
m_detailsButton(new DetailsButton),
m_grid(new QGridLayout),
m_summaryLabel(new QLabel),
m_toolWidget(0),
m_widget(0),
m_state(DetailsWidget::Collapsed),
m_hovered(false)
{
}
DetailsWidget::DetailsWidget(QWidget *parent) :
QWidget(parent),
d(new DetailsWidgetPrivate)
{
d->m_summaryLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
d->m_summaryLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
d->m_summaryLabel->setContentsMargins(MARGIN, MARGIN, MARGIN, MARGIN);
d->m_grid->setContentsMargins(0, 0, 0, 0);
d->m_grid->setSpacing(0);
d->m_grid->addWidget(d->m_summaryLabel, 0, 1);
d->m_grid->addWidget(d->m_detailsButton, 0, 2);
setLayout(d->m_grid);
connect(d->m_detailsButton, SIGNAL(toggled(bool)),
this, SLOT(setExpanded(bool)));
updateControls();
}
DetailsWidget::~DetailsWidget()
{
delete d;
}
void DetailsWidget::paintEvent(QPaintEvent *paintEvent)
{
QWidget::paintEvent(paintEvent);
QPainter p(this);
QPoint topLeft(d->m_summaryLabel->geometry().left(), contentsRect().top());
const QRect paintArea(topLeft, contentsRect().bottomRight());
if (d->m_state != Expanded) {
if (d->m_collapsedPixmap.isNull() ||
d->m_collapsedPixmap.size() != size())
d->m_collapsedPixmap = cacheBackground(paintArea.size(), false);
p.drawPixmap(paintArea, d->m_collapsedPixmap);
} else {
if (d->m_expandedPixmap.isNull() ||
d->m_expandedPixmap.size() != size())
d->m_expandedPixmap = cacheBackground(paintArea.size(), true);
p.drawPixmap(paintArea, d->m_expandedPixmap);
}
}
void DetailsWidget::enterEvent(QEvent * event)
{
QWidget::enterEvent(event);
changeHoverState(true);
}
void DetailsWidget::leaveEvent(QEvent * event)
{
QWidget::leaveEvent(event);
changeHoverState(false);
}
void DetailsWidget::setSummaryText(const QString &text)
{
d->m_summaryLabel->setText(text);
}
QString DetailsWidget::summaryText() const
{
return d->m_summaryLabel->text();
}
DetailsWidget::State DetailsWidget::state() const
{
return d->m_state;
}
void DetailsWidget::setState(State state)
{
if (state == d->m_state)
return;
d->m_state = state;
updateControls();
}
void DetailsWidget::setExpanded(bool expanded)
{
setState(expanded ? Expanded : Collapsed);
}
void DetailsWidget::updateControls()
{
if (d->m_widget)
d->m_widget->setVisible(d->m_state == Expanded || d->m_state == NoSummary);
d->m_detailsButton->setChecked(d->m_state == Expanded && d->m_widget);
d->m_summaryLabel->setEnabled(d->m_state == Collapsed && d->m_widget);
d->m_detailsButton->setVisible(d->m_state != NoSummary);
d->m_summaryLabel->setVisible(d->m_state != NoSummary);
{
QWidget *w = this;
while (w) {
if (w->layout())
w->layout()->activate();
if (QScrollArea *area = qobject_cast<QScrollArea*>(w)) {
QEvent e(QEvent::LayoutRequest);
QCoreApplication::sendEvent(area, &e);
}
w = w->parentWidget();
}
}
}
QWidget *DetailsWidget::widget() const
{
return d->m_widget;
}
void DetailsWidget::setWidget(QWidget *widget)
{
if (d->m_widget == widget)
return;
if (d->m_widget) {
d->m_grid->removeWidget(d->m_widget);
delete d->m_widget;
}
d->m_widget = widget;
if (d->m_widget) {
d->m_widget->setContentsMargins(MARGIN, MARGIN, MARGIN, MARGIN);
d->m_grid->addWidget(d->m_widget, 1, 1, 1, 2);
}
updateControls();
}
void DetailsWidget::setToolWidget(QWidget *widget)
{
if (d->m_toolWidget == widget)
return;
d->m_toolWidget = widget;
if (!d->m_toolWidget)
return;
d->m_toolWidget->adjustSize();
d->m_grid->addWidget(d->m_toolWidget, 0, 0, 1, 1, Qt::AlignCenter);
d->m_grid->setColumnMinimumWidth(0, d->m_toolWidget->width());
d->m_grid->setRowMinimumHeight(0, d->m_toolWidget->height());
changeHoverState(d->m_hovered);
}
QWidget *DetailsWidget::toolWidget() const
{
return d->m_toolWidget;
}
QPixmap DetailsWidget::cacheBackground(const QSize &size, bool expanded)
{
QLinearGradient lg;
lg.setCoordinateMode(QGradient::ObjectBoundingMode);
lg.setFinalStop(0, 1);
lg.setColorAt(0, palette().color(QPalette::Midlight));
lg.setColorAt(1, palette().color(QPalette::Button));
QPixmap pixmap(size);
QPainter p(&pixmap);
p.setBrush(lg);
p.setPen(QPen(palette().color(QPalette::Mid)));
p.drawRect(0, 0, size.width() - 1, size.height() - 1);
if (expanded) {
p.drawLine(0, d->m_widget->geometry().top() - 1,
d->m_summaryLabel->width(), d->m_widget->geometry().top() - 1);
}
return pixmap;
}
void DetailsWidget::changeHoverState(bool hovered)
{
if (!d->m_toolWidget)
return;
d->m_toolWidget->setVisible(hovered);
d->m_hovered = hovered;
}
} // namespace Utils
<|endoftext|>
|
<commit_before>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Parses a module and ETW trace files, generating an ordering of the
// blocks in the decomposed image.
#include "syzygy/reorder/reorder_app.h"
#include <objbase.h>
#include <iostream>
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/strings/string_split.h"
#include "syzygy/grinder/basic_block_entry_count_serializer.h"
#include "syzygy/grinder/basic_block_util.h"
#include "syzygy/pe/find.h"
#include "syzygy/reorder/basic_block_optimizer.h"
#include "syzygy/reorder/dead_code_finder.h"
#include "syzygy/reorder/linear_order_generator.h"
#include "syzygy/reorder/random_order_generator.h"
namespace reorder {
namespace {
using grinder::basic_block_util::EntryCountMap;
using grinder::basic_block_util::ModuleEntryCountMap;
using grinder::basic_block_util::LoadBasicBlockRanges;
using grinder::basic_block_util::FindEntryCountMap;
using grinder::basic_block_util::RelativeAddressRangeVector;
using grinder::BasicBlockEntryCountSerializer;
static const char kUsageFormatStr[] =
"Usage: %ls [options] [log files ...]\n"
" Required Options:\n"
" --instrumented-image=<path> the path to the instrumented image file.\n"
" --output-file=<path> the output file.\n"
" Optional Options:\n"
" --input-image=<path> the input image file to reorder. If this is not\n"
" specified it will be inferred from the instrumented image's\n"
" metadata.\n"
" --basic-block-entry-counts=PATH the path to the JSON file containing\n"
" the summary basic-block entry counts for the image. If this is\n"
" given then the input image is also required.\n"
" --seed=INT generates a random ordering; don't specify ETW log files.\n"
" --list-dead-code instead of an ordering, output the set of functions\n"
" not visited during the trace.\n"
" --pretty-print enables pretty printing of the JSON output file.\n"
" --reorderer-flags=<comma separated reorderer flags>\n"
" Reorderer Flags:\n"
" no-code: Do not reorder code sections.\n"
" no-data: Do not reorder data sections.\n"
" Deprecated Options:\n"
" --instrumented-dll=<path> aliases to --instrumented-image.\n"
" --input-dll=<path> aliases to --input-image.\n";
// Parses reorderer flags. Returns true on success, false otherwise. On
// failure, also outputs Usage with an error message.
bool ParseFlags(const std::string& flags_str, Reorderer::Flags* flags) {
DCHECK(flags != NULL);
// Set the default flags value.
Reorderer::Flags out_flags =
Reorderer::kFlagReorderData | Reorderer::kFlagReorderCode;
// If there is a string to process then extract its flags.
if (!flags_str.empty()) {
typedef std::vector<std::string> StringVector;
StringVector text_flags;
base::SplitString(flags_str, ',', &text_flags);
StringVector::const_iterator flag_iter = text_flags.begin();
for (; flag_iter != text_flags.end(); ++flag_iter) {
if (*flag_iter == "no-data") {
out_flags &= ~Reorderer::kFlagReorderData;
} else if (*flag_iter == "no-code") {
out_flags &= ~Reorderer::kFlagReorderCode;
} else if (!flag_iter->empty()) {
LOG(ERROR) << "Unknown reorderer flag: " << *flag_iter << ".";
return false;
}
}
}
// Set the return value.
*flags = out_flags;
return true;
}
} // namespace
const char ReorderApp::kInstrumentedImage[] = "instrumented-image";
const char ReorderApp::kOutputFile[] = "output-file";
const char ReorderApp::kInputImage[] = "input-image";
const char ReorderApp::kBasicBlockEntryCounts[] = "basic-block-entry-counts";
const char ReorderApp::kSeed[] = "seed";
const char ReorderApp::kListDeadCode[] = "list-dead-code";
const char ReorderApp::kPrettyPrint[] = "pretty-print";
const char ReorderApp::kReordererFlags[] = "reorderer-flags";
const char ReorderApp::kInstrumentedDll[] = "instrumented-dll";
const char ReorderApp::kInputDll[] = "input-dll";
ReorderApp::ReorderApp()
: AppImplBase("Reorder"),
mode_(kInvalidMode),
seed_(0),
pretty_print_(false),
flags_(0) {
}
bool ReorderApp::ParseCommandLine(const CommandLine* command_line) {
DCHECK(command_line != NULL);
DCHECK_EQ(kInvalidMode, mode_);
// Parse the instrumented image path.
if (!GetDeprecatedSwitch(command_line,
kInstrumentedImage,
kInstrumentedDll,
&CommandLine::GetSwitchValuePath,
&instrumented_image_path_) ||
instrumented_image_path_.empty()) {
return Usage(command_line, "Invalid or missing instrumented image path.");
}
// Parse the output file path.
output_file_path_ = command_line->GetSwitchValuePath(kOutputFile);
if (output_file_path_.empty()) {
return Usage(command_line, "Invalid or missing output file path.");
}
// Parse the (optional) input image path.
if (!GetDeprecatedSwitch(command_line,
kInputImage,
kInputDll,
&CommandLine::GetSwitchValuePath,
&input_image_path_)) {
return Usage(command_line, "Invalid input image path.");
}
bb_entry_count_file_path_ =
command_line->GetSwitchValuePath(kBasicBlockEntryCounts);
// Parse the reorderer flags.
std::string flags_str(command_line->GetSwitchValueASCII(kReordererFlags));
if (!ParseFlags(flags_str, &flags_)) {
return Usage(command_line, "Invalid reorderer flags");
}
// Parse the pretty-print switch.
pretty_print_ = command_line->HasSwitch(kPrettyPrint);
// Make all of the input paths absolute.
input_image_path_ = AbsolutePath(input_image_path_);
instrumented_image_path_ = AbsolutePath(instrumented_image_path_);
output_file_path_ = AbsolutePath(output_file_path_);
bb_entry_count_file_path_ = AbsolutePath(bb_entry_count_file_path_);
// Capture the (possibly empty) set of trace files to read.
for (size_t i = 0; i < command_line->GetArgs().size(); ++i) {
const base::FilePath pattern(command_line->GetArgs()[i]);
if (!AppendMatchingPaths(pattern, &trace_file_paths_)) {
LOG(ERROR) << "Found no files matching '" << pattern.value() << "'.";
return Usage(command_line, "");
}
}
// Check if we are in random order mode. Look for and parse --seed.
if (command_line->HasSwitch(kSeed)) {
if (!trace_file_paths_.empty()) {
return Usage(command_line,
"Trace files are not accepted in random order mode.");
}
std::string seed_str(command_line->GetSwitchValueASCII(kSeed));
int tmp_seed = 0;
if (seed_str.empty() || !base::StringToInt(seed_str, &tmp_seed)) {
return Usage(command_line, "Invalid seed value.");
}
seed_ = tmp_seed;
mode_ = kRandomOrderMode;
}
// Parse the list-dead-code switch.
if (command_line->HasSwitch(kListDeadCode)) {
if (mode_ != kInvalidMode) {
LOG(ERROR) << "--" << kListDeadCode << " and --" << kSeed << "=N are "
<< "mutually exclusive.";
return false;
}
mode_ = kDeadCodeFinderMode;
}
// If we haven't found anything to over-ride the default mode (linear order),
// then the default it is.
if (mode_ == kInvalidMode)
mode_ = kLinearOrderMode;
// We do not accept trace file paths in random order mode.
if (mode_ == kRandomOrderMode && !trace_file_paths_.empty()) {
return Usage(command_line,
"Trace files are not accepted in random order mode.");
}
// We only accept a basic-block entry count file in linear order mode, and
// we require the input image path when we do so.
if (!bb_entry_count_file_path_.empty()) {
if (mode_ != kLinearOrderMode) {
return Usage(command_line,
"A basic-block entry counts file is only accepted in linear "
"order mode.");
}
if (input_image_path_.empty()) {
return Usage(command_line,
"The input image is required for basic-block level "
"optimization.");
}
}
// If we get here then the command-line switches were valid.
return true;
}
bool ReorderApp::SetUp() {
switch (mode_) {
case kLinearOrderMode:
order_generator_.reset(new LinearOrderGenerator());
return true;
case kRandomOrderMode:
order_generator_.reset(new RandomOrderGenerator(seed_));
return true;
case kDeadCodeFinderMode:
order_generator_.reset(new DeadCodeFinder());
return true;
}
NOTREACHED();
return false;
}
int ReorderApp::Run() {
pe::PEFile input_image;
block_graph::BlockGraph block_graph;
pe::ImageLayout image_layout(&block_graph);
Reorderer::Order order;
Reorderer reorderer(input_image_path_,
instrumented_image_path_,
trace_file_paths_,
flags_);
// Generate a block-level ordering.
if (!reorderer.Reorder(order_generator_.get(),
&order,
&input_image,
&image_layout)) {
LOG(ERROR) << "Reorder failed.";
return 1;
}
// Basic-block optimize the resulting order if there is an entry count file.
if (mode_ == kLinearOrderMode && !bb_entry_count_file_path_.empty()) {
pe::PEFile::Signature signature;
input_image.GetSignature(&signature);
if (!OptimizeBasicBlocks(signature, image_layout, &order)) {
LOG(ERROR) << "Basic-block optimization failed.";
return 1;
}
}
// Serialize the order to JSON.
if (!order.SerializeToJSON(input_image, output_file_path_, pretty_print_)) {
LOG(ERROR) << "Unable to output order.";
return 1;
}
// We were successful.
return 0;
}
bool ReorderApp::Usage(const CommandLine* cmd_line,
const base::StringPiece& message) const {
if (!message.empty()) {
::fwrite(message.data(), 1, message.length(), err());
::fprintf(err(), "\n\n");
}
::fprintf(err(),
kUsageFormatStr,
cmd_line->GetProgram().BaseName().value().c_str());
return false;
}
bool ReorderApp::OptimizeBasicBlocks(const pe::PEFile::Signature& signature,
const pe::ImageLayout& image_layout,
Reorderer::Order* order) {
DCHECK(order != NULL);
LOG(INFO) << "Performing basic block ordering.";
// Load the basic-block entry count data.
ModuleEntryCountMap module_entry_count_map;
BasicBlockEntryCountSerializer serializer;
if (!serializer.LoadFromJson(bb_entry_count_file_path_,
&module_entry_count_map)) {
LOG(ERROR) << "Failed to load basic-block entry count data";
return false;
}
const EntryCountMap* entry_counts = NULL;
if (!FindEntryCountMap(signature, module_entry_count_map, &entry_counts)) {
LOG(ERROR) << "Failed to find entry count vector for '"
<< signature.path << "'.";
return false;
}
// Find the PDB file for the module.
base::FilePath pdb_path;
if (!pe::FindPdbForModule(instrumented_image_path_, &pdb_path) ||
pdb_path.empty()) {
LOG(ERROR) << "Failed to find PDB for instrumented image: "
<< instrumented_image_path_.value();
return false;
}
// Optimize the ordering at the basic-block level.
BasicBlockOptimizer optimizer;
if (!optimizer.Optimize(image_layout, *entry_counts, order)) {
LOG(ERROR) << "Failed to optimize basic-block ordering.";
return false;
}
return true;
}
} // namespace reorder
<commit_msg>Remove useless dead code in reorder. R=chrisha@chromium.org BUG=<commit_after>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Parses a module and ETW trace files, generating an ordering of the
// blocks in the decomposed image.
#include "syzygy/reorder/reorder_app.h"
#include <objbase.h>
#include <iostream>
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/strings/string_split.h"
#include "syzygy/grinder/basic_block_entry_count_serializer.h"
#include "syzygy/grinder/basic_block_util.h"
#include "syzygy/pe/find.h"
#include "syzygy/reorder/basic_block_optimizer.h"
#include "syzygy/reorder/dead_code_finder.h"
#include "syzygy/reorder/linear_order_generator.h"
#include "syzygy/reorder/random_order_generator.h"
namespace reorder {
namespace {
using grinder::basic_block_util::EntryCountMap;
using grinder::basic_block_util::ModuleEntryCountMap;
using grinder::basic_block_util::LoadBasicBlockRanges;
using grinder::basic_block_util::FindEntryCountMap;
using grinder::basic_block_util::RelativeAddressRangeVector;
using grinder::BasicBlockEntryCountSerializer;
static const char kUsageFormatStr[] =
"Usage: %ls [options] [log files ...]\n"
" Required Options:\n"
" --instrumented-image=<path> the path to the instrumented image file.\n"
" --output-file=<path> the output file.\n"
" Optional Options:\n"
" --input-image=<path> the input image file to reorder. If this is not\n"
" specified it will be inferred from the instrumented image's\n"
" metadata.\n"
" --basic-block-entry-counts=PATH the path to the JSON file containing\n"
" the summary basic-block entry counts for the image. If this is\n"
" given then the input image is also required.\n"
" --seed=INT generates a random ordering; don't specify ETW log files.\n"
" --list-dead-code instead of an ordering, output the set of functions\n"
" not visited during the trace.\n"
" --pretty-print enables pretty printing of the JSON output file.\n"
" --reorderer-flags=<comma separated reorderer flags>\n"
" Reorderer Flags:\n"
" no-code: Do not reorder code sections.\n"
" no-data: Do not reorder data sections.\n"
" Deprecated Options:\n"
" --instrumented-dll=<path> aliases to --instrumented-image.\n"
" --input-dll=<path> aliases to --input-image.\n";
// Parses reorderer flags. Returns true on success, false otherwise. On
// failure, also outputs Usage with an error message.
bool ParseFlags(const std::string& flags_str, Reorderer::Flags* flags) {
DCHECK(flags != NULL);
// Set the default flags value.
Reorderer::Flags out_flags =
Reorderer::kFlagReorderData | Reorderer::kFlagReorderCode;
// If there is a string to process then extract its flags.
if (!flags_str.empty()) {
typedef std::vector<std::string> StringVector;
StringVector text_flags;
base::SplitString(flags_str, ',', &text_flags);
StringVector::const_iterator flag_iter = text_flags.begin();
for (; flag_iter != text_flags.end(); ++flag_iter) {
if (*flag_iter == "no-data") {
out_flags &= ~Reorderer::kFlagReorderData;
} else if (*flag_iter == "no-code") {
out_flags &= ~Reorderer::kFlagReorderCode;
} else if (!flag_iter->empty()) {
LOG(ERROR) << "Unknown reorderer flag: " << *flag_iter << ".";
return false;
}
}
}
// Set the return value.
*flags = out_flags;
return true;
}
} // namespace
const char ReorderApp::kInstrumentedImage[] = "instrumented-image";
const char ReorderApp::kOutputFile[] = "output-file";
const char ReorderApp::kInputImage[] = "input-image";
const char ReorderApp::kBasicBlockEntryCounts[] = "basic-block-entry-counts";
const char ReorderApp::kSeed[] = "seed";
const char ReorderApp::kListDeadCode[] = "list-dead-code";
const char ReorderApp::kPrettyPrint[] = "pretty-print";
const char ReorderApp::kReordererFlags[] = "reorderer-flags";
const char ReorderApp::kInstrumentedDll[] = "instrumented-dll";
const char ReorderApp::kInputDll[] = "input-dll";
ReorderApp::ReorderApp()
: AppImplBase("Reorder"),
mode_(kInvalidMode),
seed_(0),
pretty_print_(false),
flags_(0) {
}
bool ReorderApp::ParseCommandLine(const CommandLine* command_line) {
DCHECK(command_line != NULL);
DCHECK_EQ(kInvalidMode, mode_);
// Parse the instrumented image path.
if (!GetDeprecatedSwitch(command_line,
kInstrumentedImage,
kInstrumentedDll,
&CommandLine::GetSwitchValuePath,
&instrumented_image_path_) ||
instrumented_image_path_.empty()) {
return Usage(command_line, "Invalid or missing instrumented image path.");
}
// Parse the output file path.
output_file_path_ = command_line->GetSwitchValuePath(kOutputFile);
if (output_file_path_.empty()) {
return Usage(command_line, "Invalid or missing output file path.");
}
// Parse the (optional) input image path.
if (!GetDeprecatedSwitch(command_line,
kInputImage,
kInputDll,
&CommandLine::GetSwitchValuePath,
&input_image_path_)) {
return Usage(command_line, "Invalid input image path.");
}
bb_entry_count_file_path_ =
command_line->GetSwitchValuePath(kBasicBlockEntryCounts);
// Parse the reorderer flags.
std::string flags_str(command_line->GetSwitchValueASCII(kReordererFlags));
if (!ParseFlags(flags_str, &flags_)) {
return Usage(command_line, "Invalid reorderer flags");
}
// Parse the pretty-print switch.
pretty_print_ = command_line->HasSwitch(kPrettyPrint);
// Make all of the input paths absolute.
input_image_path_ = AbsolutePath(input_image_path_);
instrumented_image_path_ = AbsolutePath(instrumented_image_path_);
output_file_path_ = AbsolutePath(output_file_path_);
bb_entry_count_file_path_ = AbsolutePath(bb_entry_count_file_path_);
// Capture the (possibly empty) set of trace files to read.
for (size_t i = 0; i < command_line->GetArgs().size(); ++i) {
const base::FilePath pattern(command_line->GetArgs()[i]);
if (!AppendMatchingPaths(pattern, &trace_file_paths_)) {
LOG(ERROR) << "Found no files matching '" << pattern.value() << "'.";
return Usage(command_line, "");
}
}
// Check if we are in random order mode. Look for and parse --seed.
if (command_line->HasSwitch(kSeed)) {
if (!trace_file_paths_.empty()) {
return Usage(command_line,
"Trace files are not accepted in random order mode.");
}
std::string seed_str(command_line->GetSwitchValueASCII(kSeed));
int tmp_seed = 0;
if (seed_str.empty() || !base::StringToInt(seed_str, &tmp_seed)) {
return Usage(command_line, "Invalid seed value.");
}
seed_ = tmp_seed;
mode_ = kRandomOrderMode;
}
// Parse the list-dead-code switch.
if (command_line->HasSwitch(kListDeadCode)) {
if (mode_ != kInvalidMode) {
LOG(ERROR) << "--" << kListDeadCode << " and --" << kSeed << "=N are "
<< "mutually exclusive.";
return false;
}
mode_ = kDeadCodeFinderMode;
}
// If we haven't found anything to over-ride the default mode (linear order),
// then the default it is.
if (mode_ == kInvalidMode)
mode_ = kLinearOrderMode;
// We do not accept trace file paths in random order mode.
if (mode_ == kRandomOrderMode && !trace_file_paths_.empty()) {
return Usage(command_line,
"Trace files are not accepted in random order mode.");
}
// We only accept a basic-block entry count file in linear order mode, and
// we require the input image path when we do so.
if (!bb_entry_count_file_path_.empty()) {
if (mode_ != kLinearOrderMode) {
return Usage(command_line,
"A basic-block entry counts file is only accepted in linear "
"order mode.");
}
if (input_image_path_.empty()) {
return Usage(command_line,
"The input image is required for basic-block level "
"optimization.");
}
}
// If we get here then the command-line switches were valid.
return true;
}
bool ReorderApp::SetUp() {
switch (mode_) {
case kLinearOrderMode:
order_generator_.reset(new LinearOrderGenerator());
return true;
case kRandomOrderMode:
order_generator_.reset(new RandomOrderGenerator(seed_));
return true;
case kDeadCodeFinderMode:
order_generator_.reset(new DeadCodeFinder());
return true;
}
NOTREACHED();
return false;
}
int ReorderApp::Run() {
pe::PEFile input_image;
block_graph::BlockGraph block_graph;
pe::ImageLayout image_layout(&block_graph);
Reorderer::Order order;
Reorderer reorderer(input_image_path_,
instrumented_image_path_,
trace_file_paths_,
flags_);
// Generate a block-level ordering.
if (!reorderer.Reorder(order_generator_.get(),
&order,
&input_image,
&image_layout)) {
LOG(ERROR) << "Reorder failed.";
return 1;
}
// Basic-block optimize the resulting order if there is an entry count file.
if (mode_ == kLinearOrderMode && !bb_entry_count_file_path_.empty()) {
pe::PEFile::Signature signature;
input_image.GetSignature(&signature);
if (!OptimizeBasicBlocks(signature, image_layout, &order)) {
LOG(ERROR) << "Basic-block optimization failed.";
return 1;
}
}
// Serialize the order to JSON.
if (!order.SerializeToJSON(input_image, output_file_path_, pretty_print_)) {
LOG(ERROR) << "Unable to output order.";
return 1;
}
// We were successful.
return 0;
}
bool ReorderApp::Usage(const CommandLine* cmd_line,
const base::StringPiece& message) const {
if (!message.empty()) {
::fwrite(message.data(), 1, message.length(), err());
::fprintf(err(), "\n\n");
}
::fprintf(err(),
kUsageFormatStr,
cmd_line->GetProgram().BaseName().value().c_str());
return false;
}
bool ReorderApp::OptimizeBasicBlocks(const pe::PEFile::Signature& signature,
const pe::ImageLayout& image_layout,
Reorderer::Order* order) {
DCHECK(order != NULL);
LOG(INFO) << "Performing basic block ordering.";
// Load the basic-block entry count data.
ModuleEntryCountMap module_entry_count_map;
BasicBlockEntryCountSerializer serializer;
if (!serializer.LoadFromJson(bb_entry_count_file_path_,
&module_entry_count_map)) {
LOG(ERROR) << "Failed to load basic-block entry count data";
return false;
}
const EntryCountMap* entry_counts = NULL;
if (!FindEntryCountMap(signature, module_entry_count_map, &entry_counts)) {
LOG(ERROR) << "Failed to find entry count vector for '"
<< signature.path << "'.";
return false;
}
// Optimize the ordering at the basic-block level.
BasicBlockOptimizer optimizer;
if (!optimizer.Optimize(image_layout, *entry_counts, order)) {
LOG(ERROR) << "Failed to optimize basic-block ordering.";
return false;
}
return true;
}
} // namespace reorder
<|endoftext|>
|
<commit_before>
#ifndef OMP_OMP_HPP
#define OMP_OMP_HPP
#include <cstdint>
#include <functional>
#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <cassert>
#include <iterator>
namespace omp
{
struct iteration_context
{
std::size_t thread_index;
std::size_t index;
};
namespace internal
{
extern std::mutex global_mutex;
extern const unsigned default_num_threads;
class thread_pool
{
public:
thread_pool(const std::function<void(std::size_t thread_idx)>& fn, unsigned num_threads = 0) :
num_threads_(num_threads ? num_threads : default_num_threads)
{
threads_.reserve(num_threads - 1);
for (unsigned i = 0; i < (num_threads_ - 1); ++i)
threads_.emplace_back(fn, i);
fn(num_threads_ - 1);
for (auto it = threads_.begin(); it != threads_.end(); ++it)
it->join();
}
private:
const std::size_t num_threads_;
std::vector<std::thread> threads_;
};
class thread_pool2
{
private:
enum class state { shutdown = 0, run, running, sleep };
std::vector<std::thread> threads_;
std::vector<state> states_;
std::mutex mtx_;
std::condition_variable cv_;
std::function<void(std::size_t)> fn_;
public:
thread_pool2(std::size_t num_threads = 0) :
states_(num_threads ? num_threads - 1 : default_num_threads - 1, state::sleep)
{
threads_.reserve(states_.size());
for (std::size_t i = 0; i < states_.size(); ++i)
{
threads_.emplace_back(std::bind(&thread_pool2::routine, this, i));
}
}
~thread_pool2()
{
{
std::unique_lock<std::mutex> lk(mtx_);
std::fill(states_.begin(), states_.end(), state::shutdown);
}
cv_.notify_all();
for (auto& t : threads_)
t.join();
}
std::size_t thread_count() const { return threads_.size() + 1; }
void routine(std::size_t thread_idx)
{
while (true)
{
{
std::unique_lock<std::mutex> lk(mtx_);
if (states_[thread_idx] == state::shutdown)
break;
if (states_[thread_idx] == state::running)
{
states_[thread_idx] = state::sleep;
cv_.notify_all();
}
cv_.wait(lk, [this, thread_idx] { return states_[thread_idx] != state::sleep; });
if (states_[thread_idx] == state::shutdown)
break;
states_[thread_idx] = state::running;
}
if (fn_)
{
fn_(thread_idx);
}
}
}
//template <typename Fn>
void operator()(std::function<void(std::size_t)>&& fn)
{
fn_ = std::move(fn);
{
std::unique_lock<std::mutex> lk(mtx_);
std::fill(states_.begin(), states_.end(), state::run);
}
cv_.notify_all();
if (fn_)
{
fn_(states_.size());
}
{
// Wait for child threads to complete.
std::unique_lock<std::mutex> lk(mtx_);
if (std::count(states_.begin(), states_.end(), state::sleep) != states_.size()) // If I remember correctly, this check is redundant.
{
cv_.wait(lk, [this] { return std::count(states_.begin(), states_.end(), state::sleep) == states_.size(); });
}
}
fn_ = nullptr;
}
};
template<typename Iter>
class dynamic_iterator_thread_pool
{
public:
dynamic_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference, const iteration_context&)>& fn, unsigned num_threads) :
fn_(fn),
cur_(begin),
end_(end),
index_(0),
chunk_size_(chunk_size ? chunk_size : 1),
num_threads_(num_threads ? num_threads : default_num_threads)
{
threads_.reserve(num_threads_ - 1);
for (unsigned i = 0; i < (num_threads_ - 1); ++i)
threads_.emplace_back(std::bind(&dynamic_iterator_thread_pool::routine, this, i));
this->routine(num_threads_ - 1);
for (auto it = threads_.begin(); it != threads_.end(); ++it)
it->join();
}
private:
std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_;
std::vector<std::thread> threads_;
Iter cur_;
const Iter end_;
std::size_t index_;
std::mutex mtx_;
const std::size_t chunk_size_;
const std::size_t num_threads_;
void routine(std::size_t thread_index)
{
bool done = false;
while (!done)
{
std::vector<Iter> chunk(chunk_size_);
std::unique_lock<std::mutex> lk(mtx_);
std::size_t index = index_;
for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset)
{
++index_;
chunk[chunk_offset] = cur_;
if (cur_ != end_)
++cur_;
}
lk.unlock();
for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset)
{
if (chunk[chunk_offset] == end_)
{
done = true;
}
else
{
fn_(*chunk[chunk_offset], {thread_index, index + chunk_offset}); //fn_ ? fn_(*it, i) : void();
}
}
}
}
};
template<typename Iter>
class static_iterator_thread_pool
{
public:
static_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads = 0) :
fn_(fn),
num_threads_(num_threads ? num_threads : default_num_threads),
beg_(begin),
end_(end),
total_elements_(std::distance(beg_, end_)),
chunk_size_(chunk_size ? chunk_size : static_cast<std::size_t>(total_elements_) / num_threads_)
{
threads_.reserve(num_threads_ - 1);
for (unsigned i = 0; i < (num_threads_ - 1); ++i)
threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i));
this->routine(num_threads_ - 1);
for (auto it = threads_.begin(); it != threads_.end(); ++it)
it->join();
}
private:
std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_;
const std::size_t num_threads_;
std::vector<std::thread> threads_;
const Iter beg_;
const Iter end_;
long total_elements_;
const std::size_t chunk_size_;
public:
void routine(std::size_t thread_index)
{
auto cur = beg_;
std::advance(cur, thread_index * chunk_size_);
for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_))
{
for (std::size_t chunk_offset = 0; chunk_offset < chunk_size_ && index < total_elements_; ++chunk_offset)
{
assert(cur != end_);
fn_(*cur, {thread_index,index}); //fn_ ? fn_(*it, i) : void();
++cur;
++index;
}
}
}
};
template<typename Iter>
class static_iterator_functor
{
public:
static_iterator_functor(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads) :
fn_(fn),
num_threads_(num_threads ? num_threads : default_num_threads),
beg_(begin),
end_(end),
total_elements_(std::distance(beg_, end_)),
chunk_size_(chunk_size ? chunk_size : static_cast<std::size_t>(total_elements_) / num_threads_)
{
// threads_.reserve(num_threads_ - 1);
// for (unsigned i = 0; i < (num_threads_ - 1); ++i)
// threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i));
// this->routine(num_threads_ - 1);
//
// for (auto it = threads_.begin(); it != threads_.end(); ++it)
// it->join();
}
private:
std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_;
const std::size_t num_threads_;
const Iter beg_;
const Iter end_;
long total_elements_;
const std::size_t chunk_size_;
public:
void operator()(std::size_t thread_index)
{
auto cur = beg_;
std::advance(cur, thread_index * chunk_size_);
for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_))
{
for (std::size_t chunk_offset = 0; chunk_offset < chunk_size_ && index < total_elements_; ++chunk_offset)
{
assert(cur != end_);
fn_(*cur, {thread_index,index}); //fn_ ? fn_(*it, i) : void();
++cur;
++index;
}
}
}
};
}
class sequence_iterator
{
public:
typedef sequence_iterator self_type;
typedef int difference_type;
typedef int value_type;
typedef value_type& reference;
typedef value_type* pointer;
typedef std::random_access_iterator_tag iterator_category;
sequence_iterator() : val_(0) {}
sequence_iterator(value_type val) :
val_(val)
{
}
//reference operator [] (difference_type);
bool operator < (const self_type& other) { return val_ < other.val_; }
bool operator > (const self_type& other) { return val_ > other.val_; }
bool operator <= (const self_type& other) { return val_ <= other.val_; }
bool operator >= (const self_type& other) { return val_ >= other.val_; }
self_type operator++()
{
self_type ret = *this;
++val_;
return ret;
}
self_type operator--()
{
self_type ret = *this;
--val_;
return ret;
}
self_type& operator += (difference_type i) { val_ += i; return *this; }
self_type& operator -= (difference_type i) { val_ -= i; return *this; }
self_type operator + (difference_type i) { return self_type(val_ + i); }
self_type operator - (difference_type i) { return self_type(val_ - i); }
difference_type operator - (const self_type& other) { return val_ - other.val_; }
void operator++(int) { ++val_; }
void operator--(int) { --val_; }
reference operator*() { return val_; }
pointer operator->() { return &val_; }
bool operator==(const self_type& rhs) const { return (val_ == rhs.val_); }
bool operator!=(const self_type& rhs) const { return (val_ != rhs.val_); }
private:
value_type val_;
};
class schedule
{
public:
schedule(std::size_t chunk_size);
std::size_t chunk_size() const;
protected:
std::size_t chunk_size_;
};
class dynamic_schedule : public schedule
{
public:
dynamic_schedule(std::size_t chunk_size = 0);
};
class static_schedule : public schedule
{
public:
static_schedule(std::size_t chunk_size = 0);
};
void parallel(const std::function<void(std::size_t)>& operation, unsigned thread_cnt = 0);
template <typename Iterator>
void parallel_for(const dynamic_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0)
{
internal::dynamic_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt);
}
template <typename Iterator>
void parallel_for(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0)
{
internal::static_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt);
}
template <typename Iterator>
void parallel_for_exp(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, internal::thread_pool2& tp)
{
tp(internal::static_iterator_functor<Iterator>(sched.chunk_size(), begin, end, operation, tp.thread_count())); //std::bind(&internal::static_iterator_functor<Iterator>::routine, &static_fn, std::placeholders::_1));
}
template <typename Iterator>
void parallel_for(Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0)
{
parallel_for(static_schedule(), begin, end, operation, thread_cnt);
}
template <typename Handler>
void critical(std::mutex& mtx, Handler fn)
{
std::lock_guard<std::mutex> lk(mtx);
fn();
}
template <typename Handler>
void critical(Handler fn)
{
std::lock_guard<std::mutex> lk(internal::global_mutex);
fn();
}
}
#endif //OMP_OMP_HPP
<commit_msg>Fixes build error on linux.<commit_after>
#ifndef OMP_OMP_HPP
#define OMP_OMP_HPP
#include <cstdint>
#include <functional>
#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>
#include <cassert>
#include <iterator>
#include <algorithm>
namespace omp
{
struct iteration_context
{
std::size_t thread_index;
std::size_t index;
};
namespace internal
{
extern std::mutex global_mutex;
extern const unsigned default_num_threads;
class thread_pool
{
public:
thread_pool(const std::function<void(std::size_t thread_idx)>& fn, unsigned num_threads = 0) :
num_threads_(num_threads ? num_threads : default_num_threads)
{
threads_.reserve(num_threads - 1);
for (unsigned i = 0; i < (num_threads_ - 1); ++i)
threads_.emplace_back(fn, i);
fn(num_threads_ - 1);
for (auto it = threads_.begin(); it != threads_.end(); ++it)
it->join();
}
private:
const std::size_t num_threads_;
std::vector<std::thread> threads_;
};
class thread_pool2
{
private:
enum class state { shutdown = 0, run, running, sleep };
std::vector<std::thread> threads_;
std::vector<state> states_;
std::mutex mtx_;
std::condition_variable cv_;
std::function<void(std::size_t)> fn_;
public:
thread_pool2(std::size_t num_threads = 0) :
states_(num_threads ? num_threads - 1 : default_num_threads - 1, state::sleep)
{
threads_.reserve(states_.size());
for (std::size_t i = 0; i < states_.size(); ++i)
{
threads_.emplace_back(std::bind(&thread_pool2::routine, this, i));
}
}
~thread_pool2()
{
{
std::unique_lock<std::mutex> lk(mtx_);
std::fill(states_.begin(), states_.end(), state::shutdown);
}
cv_.notify_all();
for (auto& t : threads_)
t.join();
}
std::size_t thread_count() const { return threads_.size() + 1; }
void routine(std::size_t thread_idx)
{
while (true)
{
{
std::unique_lock<std::mutex> lk(mtx_);
if (states_[thread_idx] == state::shutdown)
break;
if (states_[thread_idx] == state::running)
{
states_[thread_idx] = state::sleep;
cv_.notify_all();
}
cv_.wait(lk, [this, thread_idx] { return states_[thread_idx] != state::sleep; });
if (states_[thread_idx] == state::shutdown)
break;
states_[thread_idx] = state::running;
}
if (fn_)
{
fn_(thread_idx);
}
}
}
//template <typename Fn>
void operator()(std::function<void(std::size_t)>&& fn)
{
fn_ = std::move(fn);
{
std::unique_lock<std::mutex> lk(mtx_);
std::fill(states_.begin(), states_.end(), state::run);
}
cv_.notify_all();
if (fn_)
{
fn_(states_.size());
}
{
// Wait for child threads to complete.
std::unique_lock<std::mutex> lk(mtx_);
if (std::count(states_.begin(), states_.end(), state::sleep) != states_.size()) // If I remember correctly, this check is redundant.
{
cv_.wait(lk, [this] { return std::count(states_.begin(), states_.end(), state::sleep) == states_.size(); });
}
}
fn_ = nullptr;
}
};
template<typename Iter>
class dynamic_iterator_thread_pool
{
public:
dynamic_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference, const iteration_context&)>& fn, unsigned num_threads) :
fn_(fn),
cur_(begin),
end_(end),
index_(0),
chunk_size_(chunk_size ? chunk_size : 1),
num_threads_(num_threads ? num_threads : default_num_threads)
{
threads_.reserve(num_threads_ - 1);
for (unsigned i = 0; i < (num_threads_ - 1); ++i)
threads_.emplace_back(std::bind(&dynamic_iterator_thread_pool::routine, this, i));
this->routine(num_threads_ - 1);
for (auto it = threads_.begin(); it != threads_.end(); ++it)
it->join();
}
private:
std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_;
std::vector<std::thread> threads_;
Iter cur_;
const Iter end_;
std::size_t index_;
std::mutex mtx_;
const std::size_t chunk_size_;
const std::size_t num_threads_;
void routine(std::size_t thread_index)
{
bool done = false;
while (!done)
{
std::vector<Iter> chunk(chunk_size_);
std::unique_lock<std::mutex> lk(mtx_);
std::size_t index = index_;
for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset)
{
++index_;
chunk[chunk_offset] = cur_;
if (cur_ != end_)
++cur_;
}
lk.unlock();
for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset)
{
if (chunk[chunk_offset] == end_)
{
done = true;
}
else
{
fn_(*chunk[chunk_offset], {thread_index, index + chunk_offset}); //fn_ ? fn_(*it, i) : void();
}
}
}
}
};
template<typename Iter>
class static_iterator_thread_pool
{
public:
static_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads = 0) :
fn_(fn),
num_threads_(num_threads ? num_threads : default_num_threads),
beg_(begin),
end_(end),
total_elements_(std::distance(beg_, end_)),
chunk_size_(chunk_size ? chunk_size : static_cast<std::size_t>(total_elements_) / num_threads_)
{
threads_.reserve(num_threads_ - 1);
for (unsigned i = 0; i < (num_threads_ - 1); ++i)
threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i));
this->routine(num_threads_ - 1);
for (auto it = threads_.begin(); it != threads_.end(); ++it)
it->join();
}
private:
std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_;
const std::size_t num_threads_;
std::vector<std::thread> threads_;
const Iter beg_;
const Iter end_;
long total_elements_;
const std::size_t chunk_size_;
public:
void routine(std::size_t thread_index)
{
auto cur = beg_;
std::advance(cur, thread_index * chunk_size_);
for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_))
{
for (std::size_t chunk_offset = 0; chunk_offset < chunk_size_ && index < total_elements_; ++chunk_offset)
{
assert(cur != end_);
fn_(*cur, {thread_index,index}); //fn_ ? fn_(*it, i) : void();
++cur;
++index;
}
}
}
};
template<typename Iter>
class static_iterator_functor
{
public:
static_iterator_functor(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads) :
fn_(fn),
num_threads_(num_threads ? num_threads : default_num_threads),
beg_(begin),
end_(end),
total_elements_(std::distance(beg_, end_)),
chunk_size_(chunk_size ? chunk_size : static_cast<std::size_t>(total_elements_) / num_threads_)
{
// threads_.reserve(num_threads_ - 1);
// for (unsigned i = 0; i < (num_threads_ - 1); ++i)
// threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i));
// this->routine(num_threads_ - 1);
//
// for (auto it = threads_.begin(); it != threads_.end(); ++it)
// it->join();
}
private:
std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_;
const std::size_t num_threads_;
const Iter beg_;
const Iter end_;
long total_elements_;
const std::size_t chunk_size_;
public:
void operator()(std::size_t thread_index)
{
auto cur = beg_;
std::advance(cur, thread_index * chunk_size_);
for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_))
{
for (std::size_t chunk_offset = 0; chunk_offset < chunk_size_ && index < total_elements_; ++chunk_offset)
{
assert(cur != end_);
fn_(*cur, {thread_index,index}); //fn_ ? fn_(*it, i) : void();
++cur;
++index;
}
}
}
};
}
class sequence_iterator
{
public:
typedef sequence_iterator self_type;
typedef int difference_type;
typedef int value_type;
typedef value_type& reference;
typedef value_type* pointer;
typedef std::random_access_iterator_tag iterator_category;
sequence_iterator() : val_(0) {}
sequence_iterator(value_type val) :
val_(val)
{
}
//reference operator [] (difference_type);
bool operator < (const self_type& other) { return val_ < other.val_; }
bool operator > (const self_type& other) { return val_ > other.val_; }
bool operator <= (const self_type& other) { return val_ <= other.val_; }
bool operator >= (const self_type& other) { return val_ >= other.val_; }
self_type operator++()
{
self_type ret = *this;
++val_;
return ret;
}
self_type operator--()
{
self_type ret = *this;
--val_;
return ret;
}
self_type& operator += (difference_type i) { val_ += i; return *this; }
self_type& operator -= (difference_type i) { val_ -= i; return *this; }
self_type operator + (difference_type i) { return self_type(val_ + i); }
self_type operator - (difference_type i) { return self_type(val_ - i); }
difference_type operator - (const self_type& other) { return val_ - other.val_; }
void operator++(int) { ++val_; }
void operator--(int) { --val_; }
reference operator*() { return val_; }
pointer operator->() { return &val_; }
bool operator==(const self_type& rhs) const { return (val_ == rhs.val_); }
bool operator!=(const self_type& rhs) const { return (val_ != rhs.val_); }
private:
value_type val_;
};
class schedule
{
public:
schedule(std::size_t chunk_size);
std::size_t chunk_size() const;
protected:
std::size_t chunk_size_;
};
class dynamic_schedule : public schedule
{
public:
dynamic_schedule(std::size_t chunk_size = 0);
};
class static_schedule : public schedule
{
public:
static_schedule(std::size_t chunk_size = 0);
};
void parallel(const std::function<void(std::size_t)>& operation, unsigned thread_cnt = 0);
template <typename Iterator>
void parallel_for(const dynamic_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0)
{
internal::dynamic_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt);
}
template <typename Iterator>
void parallel_for(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0)
{
internal::static_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt);
}
template <typename Iterator>
void parallel_for_exp(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, internal::thread_pool2& tp)
{
tp(internal::static_iterator_functor<Iterator>(sched.chunk_size(), begin, end, operation, tp.thread_count())); //std::bind(&internal::static_iterator_functor<Iterator>::routine, &static_fn, std::placeholders::_1));
}
template <typename Iterator>
void parallel_for(Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0)
{
parallel_for(static_schedule(), begin, end, operation, thread_cnt);
}
template <typename Handler>
void critical(std::mutex& mtx, Handler fn)
{
std::lock_guard<std::mutex> lk(mtx);
fn();
}
template <typename Handler>
void critical(Handler fn)
{
std::lock_guard<std::mutex> lk(internal::global_mutex);
fn();
}
}
#endif //OMP_OMP_HPP
<|endoftext|>
|
<commit_before>#ifndef UMINTL_EVALUATION_POLICY_HPP
#define UMINTL_EVALUATION_POLICY_HPP
#include <cstddef>
#include "umintl/forwards.h"
#include "umintl/optimization_context.hpp"
#include <cmath>
namespace umintl{
/** @brief The model_base class
*
* The optimization model can be either deterministic or stochastic. The latter usually corresponds to expected losses
* evaluated accross a large amount of data points
*/
template<class BackendType>
struct model_base{
virtual ~model_base(){ }
virtual bool update(optimization_context<BackendType> & context) = 0;
virtual value_gradient get_value_gradient_tag() const = 0;
virtual hessian_vector_product get_hv_product_tag() const = 0;
};
/** @brief The deterministic class
*
* Assumes the function evaluation is the same at each call. In the case of expected losses, it means all the data-points
* are always used.
*/
template<class BackendType>
struct deterministic : public model_base<BackendType> {
bool update(optimization_context<BackendType> &){ return false; }
value_gradient get_value_gradient_tag() const { return value_gradient(DETERMINISTIC,0,0); }
hessian_vector_product get_hv_product_tag() const { return hessian_vector_product(DETERMINISTIC,0,0); }
};
template<class BackendType>
struct mini_batch : public model_base<BackendType> {
public:
mini_batch(size_t sample_size, size_t dataset_size) : sample_size_(std::min(sample_size,dataset_size)), offset_(0), dataset_size_(dataset_size){ }
bool update(optimization_context<BackendType> &){
offset_=(offset_+sample_size_)%dataset_size_;
return false;
}
value_gradient get_value_gradient_tag() const { return value_gradient(STOCHASTIC,dataset_size_,0); }
hessian_vector_product get_hv_product_tag() const { return hessian_vector_product(STOCHASTIC,sample_size_,offset_); }
private:
size_t sample_size_;
size_t offset_;
size_t dataset_size_;
};
/** @brief the dynamically_sampled class
*
* Uses the dynamic sampled procedure from Byrd et al. (2012) :
* "Sample Size Selection in Optimization Methods for Machine Learning"
* Requires that the functor overloads :
* void operator()(VectorType const & X, VectorType & variance, umintl::gradient_variance_tag tag)
*
* The parameter tag contains the information on the current offset and sample size
*/
template<class BackendType>
struct dynamically_sampled : public model_base<BackendType> {
private:
typedef typename BackendType::ScalarType ScalarType;
typedef typename BackendType::VectorType VectorType;
public:
dynamically_sampled(double r, size_t fbatch, size_t dataset_size, double theta = 0.5) : theta_(theta), r_(r), S(std::min(fbatch,dataset_size)), offset_(0), H_offset_(0), N(dataset_size){ }
bool update(optimization_context<BackendType> & c){
if(S==N){
H_offset_=(H_offset_+(int)(r_*S))%(S - (int)(r_*S) + 1);
return false;
}
else{
VectorType var = BackendType::create_vector(c.N());
c.fun().compute_gradient_variance(c.x(),var,gradient_variance(STOCHASTIC,S,offset_));
//is_descent_direction = norm1(var)/S*[(N-S)/(N-1)] <= theta^2*norm2(grad)^2
ScalarType nrm1var = BackendType::asum(c.N(),var);
ScalarType nrm2grad = BackendType::nrm2(c.N(),c.g());
//std::gradient_variance << nrm1var*scal << " " << std::pow(theta_,2)*std::pow(nrm2grad,2) << std::endl;
bool is_descent_direction = (nrm1var/S <= (std::pow(theta_,2)*std::pow(nrm2grad,2)));
//Update parameters
//size_t old_S = S;
if(is_descent_direction==false){
S = (size_t)(nrm1var/std::pow(theta_*nrm2grad,2));
S = std::min(S,N);
if(S>N/2)
S=N;
}
offset_=(offset_+S)%(N-S+1);
if(is_descent_direction==false)
H_offset_ = 0;
else
H_offset_=(H_offset_+S)%(S - (int)(r_*S) + 1);
BackendType::delete_if_dynamically_allocated(var);
return true;
}
}
value_gradient get_value_gradient_tag() const {
return value_gradient(STOCHASTIC,S,offset_);
}
hessian_vector_product get_hv_product_tag() const {
return hessian_vector_product(STOCHASTIC, (size_t)r_*S, H_offset_+offset_);
}
private:
double theta_;
double r_;
size_t S;
size_t offset_;
size_t H_offset_;
size_t N;
};
}
#endif
<commit_msg>Optimization: Fixed invalid cast<commit_after>#ifndef UMINTL_EVALUATION_POLICY_HPP
#define UMINTL_EVALUATION_POLICY_HPP
#include <cstddef>
#include "umintl/forwards.h"
#include "umintl/optimization_context.hpp"
#include <cmath>
namespace umintl{
/** @brief The model_base class
*
* The optimization model can be either deterministic or stochastic. The latter usually corresponds to expected losses
* evaluated accross a large amount of data points
*/
template<class BackendType>
struct model_base{
virtual ~model_base(){ }
virtual bool update(optimization_context<BackendType> & context) = 0;
virtual value_gradient get_value_gradient_tag() const = 0;
virtual hessian_vector_product get_hv_product_tag() const = 0;
};
/** @brief The deterministic class
*
* Assumes the function evaluation is the same at each call. In the case of expected losses, it means all the data-points
* are always used.
*/
template<class BackendType>
struct deterministic : public model_base<BackendType> {
bool update(optimization_context<BackendType> &){ return false; }
value_gradient get_value_gradient_tag() const { return value_gradient(DETERMINISTIC,0,0); }
hessian_vector_product get_hv_product_tag() const { return hessian_vector_product(DETERMINISTIC,0,0); }
};
template<class BackendType>
struct mini_batch : public model_base<BackendType> {
public:
mini_batch(size_t sample_size, size_t dataset_size) : sample_size_(std::min(sample_size,dataset_size)), offset_(0), dataset_size_(dataset_size){ }
bool update(optimization_context<BackendType> &){
offset_=(offset_+sample_size_)%dataset_size_;
return false;
}
value_gradient get_value_gradient_tag() const { return value_gradient(STOCHASTIC,dataset_size_,0); }
hessian_vector_product get_hv_product_tag() const { return hessian_vector_product(STOCHASTIC,sample_size_,offset_); }
private:
size_t sample_size_;
size_t offset_;
size_t dataset_size_;
};
/** @brief the dynamically_sampled class
*
* Uses the dynamic sampled procedure from Byrd et al. (2012) :
* "Sample Size Selection in Optimization Methods for Machine Learning"
* Requires that the functor overloads :
* void operator()(VectorType const & X, VectorType & variance, umintl::gradient_variance_tag tag)
*
* The parameter tag contains the information on the current offset and sample size
*/
template<class BackendType>
struct dynamically_sampled : public model_base<BackendType> {
private:
typedef typename BackendType::ScalarType ScalarType;
typedef typename BackendType::VectorType VectorType;
public:
dynamically_sampled(double r, size_t fbatch, size_t dataset_size, double theta = 0.5) : theta_(theta), r_(r), S(std::min(fbatch,dataset_size)), offset_(0), H_offset_(0), N(dataset_size){ }
bool update(optimization_context<BackendType> & c){
if(S==N){
H_offset_=(H_offset_+(int)(r_*S))%(S - (int)(r_*S) + 1);
return false;
}
else{
VectorType var = BackendType::create_vector(c.N());
c.fun().compute_gradient_variance(c.x(),var,gradient_variance(STOCHASTIC,S,offset_));
//is_descent_direction = norm1(var)/S*[(N-S)/(N-1)] <= theta^2*norm2(grad)^2
ScalarType nrm1var = BackendType::asum(c.N(),var);
ScalarType nrm2grad = BackendType::nrm2(c.N(),c.g());
//std::gradient_variance << nrm1var*scal << " " << std::pow(theta_,2)*std::pow(nrm2grad,2) << std::endl;
bool is_descent_direction = (nrm1var/S <= (std::pow(theta_,2)*std::pow(nrm2grad,2)));
//Update parameters
//size_t old_S = S;
if(is_descent_direction==false){
S = (size_t)(nrm1var/std::pow(theta_*nrm2grad,2));
S = std::min(S,N);
if(S>N/2)
S=N;
}
offset_=(offset_+S)%(N-S+1);
if(is_descent_direction==false)
H_offset_ = 0;
else
H_offset_=(H_offset_+S)%(S - (int)(r_*S) + 1);
BackendType::delete_if_dynamically_allocated(var);
return true;
}
}
value_gradient get_value_gradient_tag() const {
return value_gradient(STOCHASTIC,S,offset_);
}
hessian_vector_product get_hv_product_tag() const {
return hessian_vector_product(STOCHASTIC,(size_t)(r_*S),H_offset_+offset_);
}
private:
double theta_;
double r_;
size_t S;
size_t offset_;
size_t H_offset_;
size_t N;
};
}
#endif
<|endoftext|>
|
<commit_before>#ifndef UNESCAPE_COPY_ROW_HPP
#define UNESCAPE_COPY_ROW_HPP
#include <boost/noncopyable.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/format.hpp>
#include "types.hpp"
template <typename S, typename T>
struct unescape_copy_row
: public boost::noncopyable {
static const size_t s_num_columns = boost::fusion::result_of::size<T>::value;
explicit unescape_copy_row(S &source)
: m_source(source),
m_reorder(calculate_reorder(m_source.column_names())) {
}
~unescape_copy_row() {
}
size_t read(T &row) {
std::string line;
size_t num = m_source.read(line);
if (num > 0) {
unpack(line, row);
}
return num;
}
private:
void unpack(std::string &line, T &row) {
const size_t sz = s_num_columns;
std::vector<std::pair<char *, size_t> > columns, old_columns;
{
char *prev_ptr = &line[0];
char * const end_ptr = &line[line.size()];
char *ptr = &line[0];
for (; ptr != end_ptr; ++ptr) {
if (*ptr == '\t') {
*ptr = '\0';
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
prev_ptr = ptr + 1;
}
}
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
}
columns.reserve(sz);
for (size_t i = 0; i < sz; ++i) {
if (i >= m_reorder.size()) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Index %1% exceeds m_reorder.size() %2%, this is a bug.")
% i % m_reorder.size()).str()));
}
size_t j = m_reorder[i];
if (j >= old_columns.size()) {
BOOST_THROW_EXCEPTION(std::runtime_error("Reordered index exceeds old_columns.size(), this is a bug."));
}
columns.push_back(old_columns[j]);
}
if (columns.size() != sz) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Wrong number of columns: expecting %1%, got %2% in line `%3%'.")
% sz % columns.size() % line).str()));
}
try {
set_values(row, columns);
} catch (const std::exception &e) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("%1%: in line `%2%'.") % e.what() % line).str()));
}
}
inline void set_values(T &t, std::vector<std::pair<char *, size_t> > &vs) {
boost::fusion::for_each(t, set_value(vs.begin()));
}
struct set_value {
explicit set_value(std::vector<std::pair<char *, size_t> >::iterator i) : itr(i) {}
void operator()(bool &b) const {
std::pair<char *, size_t> str = *itr++;
switch (str.first[0]) {
case 't':
b = true;
break;
case 'f':
b = false;
break;
default:
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for bool: `%1%'") % str.first).str()));
}
}
void operator()(int16_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int16_t(strtol(str.first, NULL, 10));
}
void operator()(int32_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int32_t(strtol(str.first, NULL, 10));
}
void operator()(int64_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int64_t(strtoll(str.first, NULL, 10));
}
void operator()(double &d) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
d = strtod(str.first, NULL);
}
void operator()(std::string &v) const {
std::pair<char *, size_t> str = *itr++;
v.assign(str.first, str.second);
}
void operator()(boost::posix_time::ptime &t) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
// 11111111112
// 12345678901234567890
// format is 2013-09-11 13:39:52.742365
if (str.second < 19) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unexpected format for timestamp: `%1%'.")
% str.first).str()));
}
int year = ((str.first[0] - '0') * 1000 +
(str.first[1] - '0') * 100 +
(str.first[2] - '0') * 10 +
(str.first[3] - '0'));
int month = ((str.first[5] - '0') * 10 + (str.first[6] - '0'));
int day = ((str.first[8] - '0') * 10 + (str.first[9] - '0'));
int hour = ((str.first[11] - '0') * 10 + (str.first[12] - '0'));
int min = ((str.first[14] - '0') * 10 + (str.first[15] - '0'));
int sec = ((str.first[17] - '0') * 10 + (str.first[18] - '0'));
t = boost::posix_time::ptime(boost::gregorian::date(year, month, day),
boost::posix_time::time_duration(hour, min, sec));
}
template <typename V>
void operator()(boost::optional<V> &o) const {
std::pair<char *, size_t> s = *itr;
if (strncmp(s.first, "\\N", s.second) == 0) {
o = boost::none;
++itr;
} else {
V v;
operator()(v);
o = v;
}
}
void operator()(user_status_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "pending", str.second) == 0) {
e = user_status_pending;
} else if (strncmp(str.first, "active", str.second) == 0) {
e = user_status_active;
} else if (strncmp(str.first, "confirmed", str.second) == 0) {
e = user_status_confirmed;
} else if (strncmp(str.first, "suspended", str.second) == 0) {
e = user_status_suspended;
} else if (strncmp(str.first, "deleted", str.second) == 0) {
e = user_status_deleted;
} else {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for user_status_enum: `%1%'.") % str.first).str()));
}
}
void operator()(format_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "html", str.second) == 0) {
e = format_html;
} else if (strncmp(str.first, "markdown", str.second) == 0) {
e = format_markdown;
} else if (strncmp(str.first, "text", str.second) == 0) {
e = format_text;
} else {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for format_enum: `%1%'.") % str.first).str()));
}
}
void operator()(nwr_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "Node", str.second) == 0) {
e = nwr_node;
} else if (strncmp(str.first, "Way", str.second) == 0) {
e = nwr_way;
} else if (strncmp(str.first, "Relation", str.second) == 0) {
e = nwr_relation;
} else {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for nwr_enum: `%1%'.") % str.first).str()));
}
}
inline int hex2digit(char ch) const {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return int(ch - '0');
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
return 10 + int(ch - 'a');
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return 10 + int(ch - 'A');
default:
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid hex digit."));
}
}
inline int oct2digit(char ch) const {
if ((ch >= '0') && (ch <= '7')) {
return int(ch - '0');
} else {
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid octal digit."));
}
}
void unescape(std::pair<char *, size_t> &s) const {
const size_t end = s.second;
char *str = s.first;
size_t j = 0;
for (size_t i = 0; i < end; ++i) {
switch (str[i]) {
case '\\':
++i;
if (i < end) {
switch (str[i]) {
case 'b':
str[j] = '\b';
break;
case 'f':
str[j] = '\f';
break;
case 'n':
str[j] = '\n';
break;
case 'r':
str[j] = '\r';
break;
case 't':
str[j] = '\t';
break;
case 'v':
str[j] = '\v';
break;
case 'x':
i += 2;
if (i < end) {
} else {
str[j] = char(hex2digit(str[i-1]) * 16 + hex2digit(str[i]));
BOOST_THROW_EXCEPTION(std::runtime_error("Unterminated hex escape sequence."));
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
i += 2;
if (i < end) {
str[j] = char(oct2digit(str[i-2]) * 64 + oct2digit(str[i-1]) * 8 + oct2digit(str[i]));
} else {
BOOST_THROW_EXCEPTION(std::runtime_error("Unterminated octal escape sequence."));
}
break;
default:
// an unnecessary escape
str[j] = str[i];
}
} else {
BOOST_THROW_EXCEPTION(std::runtime_error("Unterminated escape sequence."));
}
break;
default:
if (i != j) {
str[j] = str[i];
}
}
++j;
}
str[j] = '\0';
s.second = j;
}
mutable std::vector<std::pair<char *, size_t> >::iterator itr;
};
static std::vector<size_t> calculate_reorder(const std::vector<std::string> &names) {
std::vector<size_t> indexes;
const std::vector<std::string> &wanted_names = T::column_names();
const size_t num_columns = wanted_names.size();
indexes.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i) {
const std::string &wanted_name = wanted_names[i];
size_t j = i;
if (wanted_name != "*") {
std::vector<std::string>::const_iterator itr = std::find(names.begin(), names.end(), wanted_name);
if (itr == names.end()) {
std::ostringstream ostr;
ostr << "Unable to find wanted column name \"" << wanted_name << "\" in available names: ";
for (std::vector<std::string>::const_iterator jtr = names.begin(); jtr != names.end(); ++jtr) {
ostr << "\"" << *jtr << "\", ";
}
BOOST_THROW_EXCEPTION(std::runtime_error(ostr.str()));
}
j = std::distance(names.begin(), itr);
}
indexes.push_back(j);
}
return indexes;
}
S &m_source;
std::vector<size_t> m_reorder;
};
#endif /* UNESCAPE_COPY_ROW_HPP */
<commit_msg>Remember to unescape strings from the PostgreSQL dump as well.<commit_after>#ifndef UNESCAPE_COPY_ROW_HPP
#define UNESCAPE_COPY_ROW_HPP
#include <boost/noncopyable.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/optional.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/format.hpp>
#include "types.hpp"
template <typename S, typename T>
struct unescape_copy_row
: public boost::noncopyable {
static const size_t s_num_columns = boost::fusion::result_of::size<T>::value;
explicit unescape_copy_row(S &source)
: m_source(source),
m_reorder(calculate_reorder(m_source.column_names())) {
}
~unescape_copy_row() {
}
size_t read(T &row) {
std::string line;
size_t num = m_source.read(line);
if (num > 0) {
unpack(line, row);
}
return num;
}
private:
void unpack(std::string &line, T &row) {
const size_t sz = s_num_columns;
std::vector<std::pair<char *, size_t> > columns, old_columns;
{
char *prev_ptr = &line[0];
char * const end_ptr = &line[line.size()];
char *ptr = &line[0];
for (; ptr != end_ptr; ++ptr) {
if (*ptr == '\t') {
*ptr = '\0';
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
prev_ptr = ptr + 1;
}
}
old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));
}
columns.reserve(sz);
for (size_t i = 0; i < sz; ++i) {
if (i >= m_reorder.size()) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Index %1% exceeds m_reorder.size() %2%, this is a bug.")
% i % m_reorder.size()).str()));
}
size_t j = m_reorder[i];
if (j >= old_columns.size()) {
BOOST_THROW_EXCEPTION(std::runtime_error("Reordered index exceeds old_columns.size(), this is a bug."));
}
columns.push_back(old_columns[j]);
}
if (columns.size() != sz) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Wrong number of columns: expecting %1%, got %2% in line `%3%'.")
% sz % columns.size() % line).str()));
}
try {
set_values(row, columns);
} catch (const std::exception &e) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("%1%: in line `%2%'.") % e.what() % line).str()));
}
}
inline void set_values(T &t, std::vector<std::pair<char *, size_t> > &vs) {
boost::fusion::for_each(t, set_value(vs.begin()));
}
struct set_value {
explicit set_value(std::vector<std::pair<char *, size_t> >::iterator i) : itr(i) {}
void operator()(bool &b) const {
std::pair<char *, size_t> str = *itr++;
switch (str.first[0]) {
case 't':
b = true;
break;
case 'f':
b = false;
break;
default:
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for bool: `%1%'") % str.first).str()));
}
}
void operator()(int16_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int16_t(strtol(str.first, NULL, 10));
}
void operator()(int32_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int32_t(strtol(str.first, NULL, 10));
}
void operator()(int64_t &i) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
i = int64_t(strtoll(str.first, NULL, 10));
}
void operator()(double &d) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
d = strtod(str.first, NULL);
}
void operator()(std::string &v) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
v.assign(str.first, str.second);
}
void operator()(boost::posix_time::ptime &t) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
// 11111111112
// 12345678901234567890
// format is 2013-09-11 13:39:52.742365
if (str.second < 19) {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unexpected format for timestamp: `%1%'.")
% str.first).str()));
}
int year = ((str.first[0] - '0') * 1000 +
(str.first[1] - '0') * 100 +
(str.first[2] - '0') * 10 +
(str.first[3] - '0'));
int month = ((str.first[5] - '0') * 10 + (str.first[6] - '0'));
int day = ((str.first[8] - '0') * 10 + (str.first[9] - '0'));
int hour = ((str.first[11] - '0') * 10 + (str.first[12] - '0'));
int min = ((str.first[14] - '0') * 10 + (str.first[15] - '0'));
int sec = ((str.first[17] - '0') * 10 + (str.first[18] - '0'));
t = boost::posix_time::ptime(boost::gregorian::date(year, month, day),
boost::posix_time::time_duration(hour, min, sec));
}
template <typename V>
void operator()(boost::optional<V> &o) const {
std::pair<char *, size_t> s = *itr;
if (strncmp(s.first, "\\N", s.second) == 0) {
o = boost::none;
++itr;
} else {
V v;
operator()(v);
o = v;
}
}
void operator()(user_status_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "pending", str.second) == 0) {
e = user_status_pending;
} else if (strncmp(str.first, "active", str.second) == 0) {
e = user_status_active;
} else if (strncmp(str.first, "confirmed", str.second) == 0) {
e = user_status_confirmed;
} else if (strncmp(str.first, "suspended", str.second) == 0) {
e = user_status_suspended;
} else if (strncmp(str.first, "deleted", str.second) == 0) {
e = user_status_deleted;
} else {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for user_status_enum: `%1%'.") % str.first).str()));
}
}
void operator()(format_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "html", str.second) == 0) {
e = format_html;
} else if (strncmp(str.first, "markdown", str.second) == 0) {
e = format_markdown;
} else if (strncmp(str.first, "text", str.second) == 0) {
e = format_text;
} else {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for format_enum: `%1%'.") % str.first).str()));
}
}
void operator()(nwr_enum &e) const {
std::pair<char *, size_t> str = *itr++;
unescape(str);
if (strncmp(str.first, "Node", str.second) == 0) {
e = nwr_node;
} else if (strncmp(str.first, "Way", str.second) == 0) {
e = nwr_way;
} else if (strncmp(str.first, "Relation", str.second) == 0) {
e = nwr_relation;
} else {
BOOST_THROW_EXCEPTION(std::runtime_error((boost::format("Unrecognised value for nwr_enum: `%1%'.") % str.first).str()));
}
}
inline int hex2digit(char ch) const {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return int(ch - '0');
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
return 10 + int(ch - 'a');
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return 10 + int(ch - 'A');
default:
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid hex digit."));
}
}
inline int oct2digit(char ch) const {
if ((ch >= '0') && (ch <= '7')) {
return int(ch - '0');
} else {
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid octal digit."));
}
}
void unescape(std::pair<char *, size_t> &s) const {
const size_t end = s.second;
char *str = s.first;
size_t j = 0;
for (size_t i = 0; i < end; ++i) {
switch (str[i]) {
case '\\':
++i;
if (i < end) {
switch (str[i]) {
case 'b':
str[j] = '\b';
break;
case 'f':
str[j] = '\f';
break;
case 'n':
str[j] = '\n';
break;
case 'r':
str[j] = '\r';
break;
case 't':
str[j] = '\t';
break;
case 'v':
str[j] = '\v';
break;
case 'x':
i += 2;
if (i < end) {
} else {
str[j] = char(hex2digit(str[i-1]) * 16 + hex2digit(str[i]));
BOOST_THROW_EXCEPTION(std::runtime_error("Unterminated hex escape sequence."));
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
i += 2;
if (i < end) {
str[j] = char(oct2digit(str[i-2]) * 64 + oct2digit(str[i-1]) * 8 + oct2digit(str[i]));
} else {
BOOST_THROW_EXCEPTION(std::runtime_error("Unterminated octal escape sequence."));
}
break;
default:
// an unnecessary escape
str[j] = str[i];
}
} else {
BOOST_THROW_EXCEPTION(std::runtime_error("Unterminated escape sequence."));
}
break;
default:
if (i != j) {
str[j] = str[i];
}
}
++j;
}
str[j] = '\0';
s.second = j;
}
mutable std::vector<std::pair<char *, size_t> >::iterator itr;
};
static std::vector<size_t> calculate_reorder(const std::vector<std::string> &names) {
std::vector<size_t> indexes;
const std::vector<std::string> &wanted_names = T::column_names();
const size_t num_columns = wanted_names.size();
indexes.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i) {
const std::string &wanted_name = wanted_names[i];
size_t j = i;
if (wanted_name != "*") {
std::vector<std::string>::const_iterator itr = std::find(names.begin(), names.end(), wanted_name);
if (itr == names.end()) {
std::ostringstream ostr;
ostr << "Unable to find wanted column name \"" << wanted_name << "\" in available names: ";
for (std::vector<std::string>::const_iterator jtr = names.begin(); jtr != names.end(); ++jtr) {
ostr << "\"" << *jtr << "\", ";
}
BOOST_THROW_EXCEPTION(std::runtime_error(ostr.str()));
}
j = std::distance(names.begin(), itr);
}
indexes.push_back(j);
}
return indexes;
}
S &m_source;
std::vector<size_t> m_reorder;
};
#endif /* UNESCAPE_COPY_ROW_HPP */
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtGui/qgraphicsanchorlayout.h>
#include <QtGui/qgraphicslinearlayout.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qgraphicsview.h>
class tst_QGraphicsAnchorLayout : public QObject
{
Q_OBJECT
public:
tst_QGraphicsAnchorLayout() {}
~tst_QGraphicsAnchorLayout() {}
private slots:
void s60_hard_complex_data();
void s60_hard_complex();
void linearVsAnchorNested_data();
void linearVsAnchorNested();
};
class RectWidget : public QGraphicsWidget
{
public:
RectWidget(QGraphicsItem *parent = 0) : QGraphicsWidget(parent){}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->drawRoundRect(rect());
painter->drawLine(rect().topLeft(), rect().bottomRight());
painter->drawLine(rect().bottomLeft(), rect().topRight());
}
};
static QGraphicsWidget *createItem(const QSizeF &minimum = QSizeF(100.0, 100.0),
const QSizeF &preferred = QSize(150.0, 100.0),
const QSizeF &maximum = QSizeF(200.0, 100.0),
const QString &name = QString())
{
QGraphicsWidget *w = new RectWidget;
w->setMinimumSize(minimum);
w->setPreferredSize(preferred);
w->setMaximumSize(maximum);
w->setData(0, name);
return w;
}
static void setAnchor(QGraphicsAnchorLayout *l,
QGraphicsLayoutItem *firstItem,
Qt::AnchorPoint firstEdge,
QGraphicsLayoutItem *secondItem,
Qt::AnchorPoint secondEdge,
qreal spacing)
{
QGraphicsAnchor *anchor = l->addAnchor(firstItem, firstEdge, secondItem, secondEdge);
anchor->setSpacing(spacing);
}
void tst_QGraphicsAnchorLayout::s60_hard_complex_data()
{
QTest::addColumn<int>("whichSizeHint");
QTest::newRow("minimumSizeHint")
<< int(Qt::MinimumSize);
QTest::newRow("preferredSizeHint")
<< int(Qt::PreferredSize);
QTest::newRow("maximumSizeHint")
<< int(Qt::MaximumSize);
// Add it as a reference to see how much overhead the body of effectiveSizeHint takes.
QTest::newRow("noSizeHint")
<< -1;
}
void tst_QGraphicsAnchorLayout::s60_hard_complex()
{
QFETCH(int, whichSizeHint);
// Test for "hard" complex case, taken from wiki
// https://cwiki.nokia.com/S60QTUI/AnchorLayoutComplexCases
QSizeF min(0, 10);
QSizeF pref(50, 10);
QSizeF max(100, 10);
QGraphicsWidget *a = createItem(min, pref, max, "a");
QGraphicsWidget *b = createItem(min, pref, max, "b");
QGraphicsWidget *c = createItem(min, pref, max, "c");
QGraphicsWidget *d = createItem(min, pref, max, "d");
QGraphicsWidget *e = createItem(min, pref, max, "e");
QGraphicsWidget *f = createItem(min, pref, max, "f");
QGraphicsWidget *g = createItem(min, pref, max, "g");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
//<!-- Trunk -->
setAnchor(l, l, Qt::AnchorLeft, a, Qt::AnchorLeft, 10);
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft, 10);
setAnchor(l, b, Qt::AnchorRight, c, Qt::AnchorLeft, 10);
setAnchor(l, c, Qt::AnchorRight, d, Qt::AnchorLeft, 10);
setAnchor(l, d, Qt::AnchorRight, l, Qt::AnchorRight, 10);
//<!-- Above trunk -->
setAnchor(l, b, Qt::AnchorLeft, e, Qt::AnchorLeft, 10);
setAnchor(l, e, Qt::AnchorRight, d, Qt::AnchorLeft, 10);
//<!-- Below trunk -->
setAnchor(l, a, Qt::AnchorHorizontalCenter, g, Qt::AnchorLeft, 10);
setAnchor(l, g, Qt::AnchorRight, f, Qt::AnchorHorizontalCenter, 10);
setAnchor(l, c, Qt::AnchorLeft, f, Qt::AnchorLeft, 10);
setAnchor(l, f, Qt::AnchorRight, d, Qt::AnchorRight, 10);
//<!-- vertical is simpler -->
setAnchor(l, l, Qt::AnchorTop, e, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, a, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, b, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, d, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, f, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, b, Qt::AnchorBottom, 0);
setAnchor(l, a, Qt::AnchorBottom, c, Qt::AnchorBottom, 0);
setAnchor(l, a, Qt::AnchorBottom, d, Qt::AnchorBottom, 0);
setAnchor(l, f, Qt::AnchorBottom, g, Qt::AnchorTop, 0);
setAnchor(l, g, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
// It won't query the size hint if it already has a size set.
// If only one of the sizes is unset it will query sizeHint only of for that hint type.
l->setMinimumSize(60,40);
l->setPreferredSize(220,40);
l->setMaximumSize(240,40);
switch (whichSizeHint) {
case Qt::MinimumSize:
l->setMinimumSize(-1, -1);
break;
case Qt::PreferredSize:
l->setPreferredSize(-1, -1);
break;
case Qt::MaximumSize:
l->setMaximumSize(-1, -1);
break;
default:
break;
}
QSizeF sizeHint;
// warm up instruction cache
l->invalidate();
sizeHint = l->effectiveSizeHint((Qt::SizeHint)whichSizeHint);
// ...then measure...
QBENCHMARK {
l->invalidate();
sizeHint = l->effectiveSizeHint((Qt::SizeHint)whichSizeHint);
}
}
void tst_QGraphicsAnchorLayout::linearVsAnchorNested_data()
{
QTest::addColumn<int>("whichLayout");
QTest::newRow("LinearLayout")
<< 0;
QTest::newRow("AnchorLayout setup with null-anchors knot")
<< 1;
QTest::newRow("AnchorLayout setup easy to simplificate")
<< 2;
}
void tst_QGraphicsAnchorLayout::linearVsAnchorNested()
{
QFETCH(int, whichLayout);
QSizeF min(10, 10);
QSizeF pref(80, 80);
QSizeF max(150, 150);
QGraphicsWidget *a = createItem(min, pref, max, "a");
QGraphicsWidget *b = createItem(min, pref, max, "b");
QGraphicsWidget *c = createItem(min, pref, max, "c");
QGraphicsWidget *d = createItem(min, pref, max, "d");
QGraphicsLayout *layout;
if (whichLayout == 0) {
QGraphicsLinearLayout *linear1 = new QGraphicsLinearLayout;
QGraphicsLinearLayout *linear2 = new QGraphicsLinearLayout(Qt::Vertical);
QGraphicsLinearLayout *linear3 = new QGraphicsLinearLayout;
linear1->addItem(a);
linear1->addItem(linear2);
linear2->addItem(b);
linear2->addItem(linear3);
linear3->addItem(c);
linear3->addItem(d);
layout = linear1;
} else if (whichLayout == 1) {
QGraphicsAnchorLayout *anchor = new QGraphicsAnchorLayout;
// A
anchor->addCornerAnchors(a, Qt::TopLeftCorner, anchor, Qt::TopLeftCorner);
anchor->addCornerAnchors(a, Qt::TopRightCorner, b, Qt::TopLeftCorner);
anchor->addCornerAnchors(a, Qt::BottomLeftCorner, anchor, Qt::BottomLeftCorner);
anchor->addCornerAnchors(a, Qt::BottomRightCorner, c, Qt::BottomLeftCorner);
// B
anchor->addCornerAnchors(b, Qt::TopRightCorner, anchor, Qt::TopRightCorner);
anchor->addCornerAnchors(b, Qt::BottomLeftCorner, c, Qt::TopLeftCorner);
anchor->addCornerAnchors(b, Qt::BottomRightCorner, d, Qt::TopRightCorner);
// C
anchor->addCornerAnchors(c, Qt::TopRightCorner, d, Qt::TopLeftCorner);
anchor->addCornerAnchors(c, Qt::BottomRightCorner, d, Qt::BottomLeftCorner);
// D
anchor->addCornerAnchors(d, Qt::BottomRightCorner, anchor, Qt::BottomRightCorner);
layout = anchor;
} else {
QGraphicsAnchorLayout *anchor = new QGraphicsAnchorLayout;
// A
anchor->addAnchor(a, Qt::AnchorLeft, anchor, Qt::AnchorLeft);
anchor->addAnchors(a, anchor, Qt::Vertical);
anchor->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
anchor->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
// B
anchor->addAnchor(b, Qt::AnchorTop, anchor, Qt::AnchorTop);
anchor->addAnchor(b, Qt::AnchorRight, anchor, Qt::AnchorRight);
anchor->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
anchor->addAnchor(b, Qt::AnchorBottom, d, Qt::AnchorTop);
// C
anchor->addAnchor(c, Qt::AnchorRight, d, Qt::AnchorLeft);
anchor->addAnchor(c, Qt::AnchorBottom, anchor, Qt::AnchorBottom);
// D
anchor->addAnchor(d, Qt::AnchorRight, anchor, Qt::AnchorRight);
anchor->addAnchor(d, Qt::AnchorBottom, anchor, Qt::AnchorBottom);
layout = anchor;
}
QSizeF sizeHint;
// warm up instruction cache
layout->invalidate();
sizeHint = layout->effectiveSizeHint(Qt::PreferredSize);
// ...then measure...
QBENCHMARK {
// To ensure that all sizeHints caches are invalidated in
// the LinearLayout setup, we must call updateGeometry on the
// children. If we didn't, only the top level layout would be
// re-calculated.
static_cast<QGraphicsLayoutItem *>(a)->updateGeometry();
static_cast<QGraphicsLayoutItem *>(b)->updateGeometry();
static_cast<QGraphicsLayoutItem *>(c)->updateGeometry();
static_cast<QGraphicsLayoutItem *>(d)->updateGeometry();
layout->invalidate();
sizeHint = layout->effectiveSizeHint(Qt::PreferredSize);
}
}
QTEST_MAIN(tst_QGraphicsAnchorLayout)
#include "tst_qgraphicsanchorlayout.moc"
<commit_msg>QGraphicsAnchorLayout: Adding two benchmarks on LinearLayout vs AnchorLayout cases<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtGui/qgraphicsanchorlayout.h>
#include <QtGui/qgraphicslinearlayout.h>
#include <QtGui/qgraphicswidget.h>
#include <QtGui/qgraphicsview.h>
class tst_QGraphicsAnchorLayout : public QObject
{
Q_OBJECT
public:
tst_QGraphicsAnchorLayout() {}
~tst_QGraphicsAnchorLayout() {}
private slots:
void s60_hard_complex_data();
void s60_hard_complex();
void linearVsAnchorSizeHints_data();
void linearVsAnchorSizeHints();
void linearVsAnchorSetGeometry_data();
void linearVsAnchorSetGeometry();
void linearVsAnchorNested_data();
void linearVsAnchorNested();
};
class RectWidget : public QGraphicsWidget
{
public:
RectWidget(QGraphicsItem *parent = 0) : QGraphicsWidget(parent){}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->drawRoundRect(rect());
painter->drawLine(rect().topLeft(), rect().bottomRight());
painter->drawLine(rect().bottomLeft(), rect().topRight());
}
};
static QGraphicsWidget *createItem(const QSizeF &minimum = QSizeF(100.0, 100.0),
const QSizeF &preferred = QSize(150.0, 100.0),
const QSizeF &maximum = QSizeF(200.0, 100.0),
const QString &name = QString())
{
QGraphicsWidget *w = new RectWidget;
w->setMinimumSize(minimum);
w->setPreferredSize(preferred);
w->setMaximumSize(maximum);
w->setData(0, name);
return w;
}
static void setAnchor(QGraphicsAnchorLayout *l,
QGraphicsLayoutItem *firstItem,
Qt::AnchorPoint firstEdge,
QGraphicsLayoutItem *secondItem,
Qt::AnchorPoint secondEdge,
qreal spacing)
{
QGraphicsAnchor *anchor = l->addAnchor(firstItem, firstEdge, secondItem, secondEdge);
anchor->setSpacing(spacing);
}
void tst_QGraphicsAnchorLayout::s60_hard_complex_data()
{
QTest::addColumn<int>("whichSizeHint");
QTest::newRow("minimumSizeHint")
<< int(Qt::MinimumSize);
QTest::newRow("preferredSizeHint")
<< int(Qt::PreferredSize);
QTest::newRow("maximumSizeHint")
<< int(Qt::MaximumSize);
// Add it as a reference to see how much overhead the body of effectiveSizeHint takes.
QTest::newRow("noSizeHint")
<< -1;
}
void tst_QGraphicsAnchorLayout::s60_hard_complex()
{
QFETCH(int, whichSizeHint);
// Test for "hard" complex case, taken from wiki
// https://cwiki.nokia.com/S60QTUI/AnchorLayoutComplexCases
QSizeF min(0, 10);
QSizeF pref(50, 10);
QSizeF max(100, 10);
QGraphicsWidget *a = createItem(min, pref, max, "a");
QGraphicsWidget *b = createItem(min, pref, max, "b");
QGraphicsWidget *c = createItem(min, pref, max, "c");
QGraphicsWidget *d = createItem(min, pref, max, "d");
QGraphicsWidget *e = createItem(min, pref, max, "e");
QGraphicsWidget *f = createItem(min, pref, max, "f");
QGraphicsWidget *g = createItem(min, pref, max, "g");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
//<!-- Trunk -->
setAnchor(l, l, Qt::AnchorLeft, a, Qt::AnchorLeft, 10);
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft, 10);
setAnchor(l, b, Qt::AnchorRight, c, Qt::AnchorLeft, 10);
setAnchor(l, c, Qt::AnchorRight, d, Qt::AnchorLeft, 10);
setAnchor(l, d, Qt::AnchorRight, l, Qt::AnchorRight, 10);
//<!-- Above trunk -->
setAnchor(l, b, Qt::AnchorLeft, e, Qt::AnchorLeft, 10);
setAnchor(l, e, Qt::AnchorRight, d, Qt::AnchorLeft, 10);
//<!-- Below trunk -->
setAnchor(l, a, Qt::AnchorHorizontalCenter, g, Qt::AnchorLeft, 10);
setAnchor(l, g, Qt::AnchorRight, f, Qt::AnchorHorizontalCenter, 10);
setAnchor(l, c, Qt::AnchorLeft, f, Qt::AnchorLeft, 10);
setAnchor(l, f, Qt::AnchorRight, d, Qt::AnchorRight, 10);
//<!-- vertical is simpler -->
setAnchor(l, l, Qt::AnchorTop, e, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, a, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, b, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, d, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, f, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, b, Qt::AnchorBottom, 0);
setAnchor(l, a, Qt::AnchorBottom, c, Qt::AnchorBottom, 0);
setAnchor(l, a, Qt::AnchorBottom, d, Qt::AnchorBottom, 0);
setAnchor(l, f, Qt::AnchorBottom, g, Qt::AnchorTop, 0);
setAnchor(l, g, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
// It won't query the size hint if it already has a size set.
// If only one of the sizes is unset it will query sizeHint only of for that hint type.
l->setMinimumSize(60,40);
l->setPreferredSize(220,40);
l->setMaximumSize(240,40);
switch (whichSizeHint) {
case Qt::MinimumSize:
l->setMinimumSize(-1, -1);
break;
case Qt::PreferredSize:
l->setPreferredSize(-1, -1);
break;
case Qt::MaximumSize:
l->setMaximumSize(-1, -1);
break;
default:
break;
}
QSizeF sizeHint;
// warm up instruction cache
l->invalidate();
sizeHint = l->effectiveSizeHint((Qt::SizeHint)whichSizeHint);
// ...then measure...
QBENCHMARK {
l->invalidate();
sizeHint = l->effectiveSizeHint((Qt::SizeHint)whichSizeHint);
}
}
static QGraphicsLayout* createLayouts(int whichLayout)
{
QSizeF min(0, 10);
QSizeF pref(50, 10);
QSizeF max(100, 10);
QGraphicsWidget *a = createItem(min, pref, max, "a");
QGraphicsWidget *b = createItem(min, pref, max, "b");
QGraphicsWidget *c = createItem(min, pref, max, "c");
QGraphicsWidget *d = createItem(min, pref, max, "d");
QGraphicsLayout *l;
if (whichLayout == 0) {
l = new QGraphicsLinearLayout;
QGraphicsLinearLayout *linear = static_cast<QGraphicsLinearLayout *>(l);
linear->setContentsMargins(0, 0, 0, 0);
linear->addItem(a);
linear->addItem(b);
linear->addItem(c);
linear->addItem(d);
} else {
l = new QGraphicsAnchorLayout;
QGraphicsAnchorLayout *anchor = static_cast<QGraphicsAnchorLayout *>(l);
anchor->setContentsMargins(0, 0, 0, 0);
// Horizontal
setAnchor(anchor, anchor, Qt::AnchorLeft, a, Qt::AnchorLeft, 0);
setAnchor(anchor, a, Qt::AnchorRight, b, Qt::AnchorLeft, 0);
setAnchor(anchor, b, Qt::AnchorRight, c, Qt::AnchorLeft, 0);
setAnchor(anchor, c, Qt::AnchorRight, d, Qt::AnchorLeft, 0);
setAnchor(anchor, d, Qt::AnchorRight, anchor, Qt::AnchorRight, 0);
// Vertical
anchor->addAnchors(anchor, a, Qt::Vertical);
anchor->addAnchors(anchor, b, Qt::Vertical);
anchor->addAnchors(anchor, c, Qt::Vertical);
anchor->addAnchors(anchor, d, Qt::Vertical);
}
return l;
}
void tst_QGraphicsAnchorLayout::linearVsAnchorSizeHints_data()
{
QTest::addColumn<int>("whichLayout");
QTest::addColumn<int>("whichSizeHint");
QTest::newRow("QGraphicsLinearLayout::minimum")
<< 0 << int(Qt::MinimumSize);
QTest::newRow("QGraphicsLinearLayout::preferred")
<< 0 << int(Qt::PreferredSize);
QTest::newRow("QGraphicsLinearLayout::maximum")
<< 0 << int(Qt::MaximumSize);
QTest::newRow("QGraphicsLinearLayout::noSizeHint")
<< 0 << -1;
QTest::newRow("QGraphicsAnchorLayout::minimum")
<< 1 << int(Qt::MinimumSize);
QTest::newRow("QGraphicsAnchorLayout::preferred")
<< 1 << int(Qt::PreferredSize);
QTest::newRow("QGraphicsAnchorLayout::maximum")
<< 1 << int(Qt::MaximumSize);
QTest::newRow("QGraphicsAnchorLayout::noSizeHint")
<< 1 << -1;
}
void tst_QGraphicsAnchorLayout::linearVsAnchorSizeHints()
{
QFETCH(int, whichSizeHint);
QFETCH(int, whichLayout);
QGraphicsLayout *l = createLayouts(whichLayout);
QSizeF sizeHint;
// warm up instruction cache
l->invalidate();
sizeHint = l->effectiveSizeHint((Qt::SizeHint)whichSizeHint);
// ...then measure...
QBENCHMARK {
l->invalidate();
sizeHint = l->effectiveSizeHint((Qt::SizeHint)whichSizeHint);
}
}
void tst_QGraphicsAnchorLayout::linearVsAnchorSetGeometry_data()
{
QTest::addColumn<int>("whichLayout");
QTest::newRow("QGraphicsLinearLayout")
<< 0;
QTest::newRow("QGraphicsAnchorLayout")
<< 1;
}
void tst_QGraphicsAnchorLayout::linearVsAnchorSetGeometry()
{
QFETCH(int, whichLayout);
QGraphicsLayout *l = createLayouts(whichLayout);
QRectF sizeHint;
qreal maxWidth;
qreal increment;
// warm up instruction cache
l->invalidate();
sizeHint.setSize(l->effectiveSizeHint(Qt::MinimumSize));
maxWidth = l->effectiveSizeHint(Qt::MaximumSize).width();
increment = (maxWidth - sizeHint.width()) / 100;
l->setGeometry(sizeHint);
// ...then measure...
QBENCHMARK {
l->invalidate();
for (qreal width = sizeHint.width(); width <= maxWidth; width += increment) {
sizeHint.setWidth(width);
l->setGeometry(sizeHint);
}
}
}
void tst_QGraphicsAnchorLayout::linearVsAnchorNested_data()
{
QTest::addColumn<int>("whichLayout");
QTest::newRow("LinearLayout")
<< 0;
QTest::newRow("AnchorLayout setup with null-anchors knot")
<< 1;
QTest::newRow("AnchorLayout setup easy to simplificate")
<< 2;
}
void tst_QGraphicsAnchorLayout::linearVsAnchorNested()
{
QFETCH(int, whichLayout);
QSizeF min(10, 10);
QSizeF pref(80, 80);
QSizeF max(150, 150);
QGraphicsWidget *a = createItem(min, pref, max, "a");
QGraphicsWidget *b = createItem(min, pref, max, "b");
QGraphicsWidget *c = createItem(min, pref, max, "c");
QGraphicsWidget *d = createItem(min, pref, max, "d");
QGraphicsLayout *layout;
if (whichLayout == 0) {
QGraphicsLinearLayout *linear1 = new QGraphicsLinearLayout;
QGraphicsLinearLayout *linear2 = new QGraphicsLinearLayout(Qt::Vertical);
QGraphicsLinearLayout *linear3 = new QGraphicsLinearLayout;
linear1->addItem(a);
linear1->addItem(linear2);
linear2->addItem(b);
linear2->addItem(linear3);
linear3->addItem(c);
linear3->addItem(d);
layout = linear1;
} else if (whichLayout == 1) {
QGraphicsAnchorLayout *anchor = new QGraphicsAnchorLayout;
// A
anchor->addCornerAnchors(a, Qt::TopLeftCorner, anchor, Qt::TopLeftCorner);
anchor->addCornerAnchors(a, Qt::TopRightCorner, b, Qt::TopLeftCorner);
anchor->addCornerAnchors(a, Qt::BottomLeftCorner, anchor, Qt::BottomLeftCorner);
anchor->addCornerAnchors(a, Qt::BottomRightCorner, c, Qt::BottomLeftCorner);
// B
anchor->addCornerAnchors(b, Qt::TopRightCorner, anchor, Qt::TopRightCorner);
anchor->addCornerAnchors(b, Qt::BottomLeftCorner, c, Qt::TopLeftCorner);
anchor->addCornerAnchors(b, Qt::BottomRightCorner, d, Qt::TopRightCorner);
// C
anchor->addCornerAnchors(c, Qt::TopRightCorner, d, Qt::TopLeftCorner);
anchor->addCornerAnchors(c, Qt::BottomRightCorner, d, Qt::BottomLeftCorner);
// D
anchor->addCornerAnchors(d, Qt::BottomRightCorner, anchor, Qt::BottomRightCorner);
layout = anchor;
} else {
QGraphicsAnchorLayout *anchor = new QGraphicsAnchorLayout;
// A
anchor->addAnchor(a, Qt::AnchorLeft, anchor, Qt::AnchorLeft);
anchor->addAnchors(a, anchor, Qt::Vertical);
anchor->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
anchor->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
// B
anchor->addAnchor(b, Qt::AnchorTop, anchor, Qt::AnchorTop);
anchor->addAnchor(b, Qt::AnchorRight, anchor, Qt::AnchorRight);
anchor->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
anchor->addAnchor(b, Qt::AnchorBottom, d, Qt::AnchorTop);
// C
anchor->addAnchor(c, Qt::AnchorRight, d, Qt::AnchorLeft);
anchor->addAnchor(c, Qt::AnchorBottom, anchor, Qt::AnchorBottom);
// D
anchor->addAnchor(d, Qt::AnchorRight, anchor, Qt::AnchorRight);
anchor->addAnchor(d, Qt::AnchorBottom, anchor, Qt::AnchorBottom);
layout = anchor;
}
QSizeF sizeHint;
// warm up instruction cache
layout->invalidate();
sizeHint = layout->effectiveSizeHint(Qt::PreferredSize);
// ...then measure...
QBENCHMARK {
// To ensure that all sizeHints caches are invalidated in
// the LinearLayout setup, we must call updateGeometry on the
// children. If we didn't, only the top level layout would be
// re-calculated.
static_cast<QGraphicsLayoutItem *>(a)->updateGeometry();
static_cast<QGraphicsLayoutItem *>(b)->updateGeometry();
static_cast<QGraphicsLayoutItem *>(c)->updateGeometry();
static_cast<QGraphicsLayoutItem *>(d)->updateGeometry();
layout->invalidate();
sizeHint = layout->effectiveSizeHint(Qt::PreferredSize);
}
}
QTEST_MAIN(tst_QGraphicsAnchorLayout)
#include "tst_qgraphicsanchorlayout.moc"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/ivf_video_source.h"
#include "./vpx_config.h"
#include "vpx/vp8dx.h"
#include "vpx/vpx_decoder.h"
namespace {
#define NELEMENTS(x) static_cast<int>(sizeof(x) / sizeof(x[0]))
TEST(DecodeAPI, InvalidParams) {
static const vpx_codec_iface_t *kCodecs[] = {
#if CONFIG_VP8_DECODER
&vpx_codec_vp8_dx_algo,
#endif
#if CONFIG_VP9_DECODER
&vpx_codec_vp9_dx_algo,
#endif
};
uint8_t buf[1] = {0};
vpx_codec_ctx_t dec;
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_dec_init(NULL, NULL, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_dec_init(&dec, NULL, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_decode(NULL, NULL, 0, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_decode(NULL, buf, 0, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(NULL, buf, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(NULL, NULL, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_destroy(NULL));
EXPECT_TRUE(vpx_codec_error(NULL) != NULL);
for (int i = 0; i < NELEMENTS(kCodecs); ++i) {
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_dec_init(NULL, kCodecs[i], NULL, 0));
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, kCodecs[i], NULL, 0));
EXPECT_EQ(VPX_CODEC_UNSUP_BITSTREAM,
vpx_codec_decode(&dec, buf, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(&dec, NULL, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(&dec, buf, 0, NULL, 0));
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_destroy(&dec));
}
}
#if CONFIG_VP9_DECODER
// Test VP9 codec controls after a decode error to ensure the code doesn't
// misbehave.
void TestVp9Controls(vpx_codec_ctx_t *dec) {
static const int kControls[] = {
VP8D_GET_LAST_REF_UPDATES,
VP8D_GET_FRAME_CORRUPTED,
VP9D_GET_DISPLAY_SIZE,
};
int val[2];
for (int i = 0; i < NELEMENTS(kControls); ++i) {
const vpx_codec_err_t res = vpx_codec_control_(dec, kControls[i], val);
switch (kControls[i]) {
case VP8D_GET_FRAME_CORRUPTED:
EXPECT_EQ(VPX_CODEC_ERROR, res) << kControls[i];
break;
default:
EXPECT_EQ(VPX_CODEC_OK, res) << kControls[i];
break;
}
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_control_(dec, kControls[i], NULL));
}
vp9_ref_frame_t ref;
ref.idx = 0;
EXPECT_EQ(VPX_CODEC_ERROR, vpx_codec_control(dec, VP9_GET_REFERENCE, &ref));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_control(dec, VP9_GET_REFERENCE, NULL));
vpx_ref_frame_t ref_copy;
const int width = 352;
const int height = 288;
ASSERT_TRUE(
vpx_img_alloc(&ref_copy.img, VPX_IMG_FMT_I420, width, height, 1) != NULL);
ref_copy.frame_type = VP8_LAST_FRAME;
EXPECT_EQ(VPX_CODEC_ERROR,
vpx_codec_control(dec, VP8_COPY_REFERENCE, &ref_copy));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_control(dec, VP8_COPY_REFERENCE, NULL));
vpx_img_free(&ref_copy.img);
}
TEST(DecodeAPI, Vp9InvalidDecode) {
const vpx_codec_iface_t *const codec = &vpx_codec_vp9_dx_algo;
const char filename[] =
"invalid-vp90-2-00-quantizer-00.webm.ivf.s5861_r01-05_b6-.v2.ivf";
libvpx_test::IVFVideoSource video(filename);
video.Init();
video.Begin();
ASSERT_TRUE(!HasFailure());
vpx_codec_ctx_t dec;
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, codec, NULL, 0));
const uint32_t frame_size = static_cast<uint32_t>(video.frame_size());
EXPECT_EQ(VPX_CODEC_MEM_ERROR,
vpx_codec_decode(&dec, video.cxdata(), frame_size, NULL, 0));
vpx_codec_iter_t iter = NULL;
EXPECT_EQ(NULL, vpx_codec_get_frame(&dec, &iter));
TestVp9Controls(&dec);
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_destroy(&dec));
}
#endif // CONFIG_VP9_DECODER
} // namespace
<commit_msg>Ensure the error-concealment code is available<commit_after>/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/ivf_video_source.h"
#include "./vpx_config.h"
#include "vpx/vp8dx.h"
#include "vpx/vpx_decoder.h"
namespace {
#define NELEMENTS(x) static_cast<int>(sizeof(x) / sizeof(x[0]))
TEST(DecodeAPI, InvalidParams) {
static const vpx_codec_iface_t *kCodecs[] = {
#if CONFIG_VP8_DECODER
&vpx_codec_vp8_dx_algo,
#endif
#if CONFIG_VP9_DECODER
&vpx_codec_vp9_dx_algo,
#endif
};
uint8_t buf[1] = {0};
vpx_codec_ctx_t dec;
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_dec_init(NULL, NULL, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_dec_init(&dec, NULL, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_decode(NULL, NULL, 0, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_decode(NULL, buf, 0, NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(NULL, buf, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(NULL, NULL, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM, vpx_codec_destroy(NULL));
EXPECT_TRUE(vpx_codec_error(NULL) != NULL);
for (int i = 0; i < NELEMENTS(kCodecs); ++i) {
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_dec_init(NULL, kCodecs[i], NULL, 0));
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, kCodecs[i], NULL, 0));
EXPECT_EQ(VPX_CODEC_UNSUP_BITSTREAM,
vpx_codec_decode(&dec, buf, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(&dec, NULL, NELEMENTS(buf), NULL, 0));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_decode(&dec, buf, 0, NULL, 0));
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_destroy(&dec));
}
}
#if CONFIG_VP8_DECODER
TEST(DecodeAPI, OptionalParams) {
vpx_codec_ctx_t dec;
#if CONFIG_ERROR_CONCEALMENT
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, &vpx_codec_vp8_dx_algo, NULL,
VPX_CODEC_USE_ERROR_CONCEALMENT));
#else
EXPECT_EQ(VPX_CODEC_INCAPABLE,
vpx_codec_dec_init(&dec, &vpx_codec_vp8_dx_algo, NULL,
VPX_CODEC_USE_ERROR_CONCEALMENT));
#endif // CONFIG_ERROR_CONCEALMENT
}
#endif // CONFIG_VP8_DECODER
#if CONFIG_VP9_DECODER
// Test VP9 codec controls after a decode error to ensure the code doesn't
// misbehave.
void TestVp9Controls(vpx_codec_ctx_t *dec) {
static const int kControls[] = {
VP8D_GET_LAST_REF_UPDATES,
VP8D_GET_FRAME_CORRUPTED,
VP9D_GET_DISPLAY_SIZE,
};
int val[2];
for (int i = 0; i < NELEMENTS(kControls); ++i) {
const vpx_codec_err_t res = vpx_codec_control_(dec, kControls[i], val);
switch (kControls[i]) {
case VP8D_GET_FRAME_CORRUPTED:
EXPECT_EQ(VPX_CODEC_ERROR, res) << kControls[i];
break;
default:
EXPECT_EQ(VPX_CODEC_OK, res) << kControls[i];
break;
}
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_control_(dec, kControls[i], NULL));
}
vp9_ref_frame_t ref;
ref.idx = 0;
EXPECT_EQ(VPX_CODEC_ERROR, vpx_codec_control(dec, VP9_GET_REFERENCE, &ref));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_control(dec, VP9_GET_REFERENCE, NULL));
vpx_ref_frame_t ref_copy;
const int width = 352;
const int height = 288;
ASSERT_TRUE(
vpx_img_alloc(&ref_copy.img, VPX_IMG_FMT_I420, width, height, 1) != NULL);
ref_copy.frame_type = VP8_LAST_FRAME;
EXPECT_EQ(VPX_CODEC_ERROR,
vpx_codec_control(dec, VP8_COPY_REFERENCE, &ref_copy));
EXPECT_EQ(VPX_CODEC_INVALID_PARAM,
vpx_codec_control(dec, VP8_COPY_REFERENCE, NULL));
vpx_img_free(&ref_copy.img);
}
TEST(DecodeAPI, Vp9InvalidDecode) {
const vpx_codec_iface_t *const codec = &vpx_codec_vp9_dx_algo;
const char filename[] =
"invalid-vp90-2-00-quantizer-00.webm.ivf.s5861_r01-05_b6-.v2.ivf";
libvpx_test::IVFVideoSource video(filename);
video.Init();
video.Begin();
ASSERT_TRUE(!HasFailure());
vpx_codec_ctx_t dec;
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, codec, NULL, 0));
const uint32_t frame_size = static_cast<uint32_t>(video.frame_size());
EXPECT_EQ(VPX_CODEC_MEM_ERROR,
vpx_codec_decode(&dec, video.cxdata(), frame_size, NULL, 0));
vpx_codec_iter_t iter = NULL;
EXPECT_EQ(NULL, vpx_codec_get_frame(&dec, &iter));
TestVp9Controls(&dec);
EXPECT_EQ(VPX_CODEC_OK, vpx_codec_destroy(&dec));
}
#endif // CONFIG_VP9_DECODER
} // namespace
<|endoftext|>
|
<commit_before>#include <curl/curl.h>
#include <cstdlib>
#include <cstring>
#include "datafeed.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "vote.h"
#include "main.h"
#include "bitcoinrpc.h"
#include "wallet.h"
using namespace std;
using namespace json_spirit;
string strDataFeedError = "";
class DataFeedRequest
{
private:
CURL *curl;
string result;
string error;
string url;
size_t ReceiveCallback(char *contents, size_t size, size_t nmemb)
{
if (size == 0 || nmemb == 0)
return 0;
size_t written = 0;
try
{
size_t realsize = size * nmemb;
int nMaxSize = GetArg("maxdatafeedsize", 10 * 1024);
if (result.size() + realsize > nMaxSize)
throw runtime_error((boost::format("Data feed size exceeds limit (%1% bytes)") % nMaxSize).str());
result.append(contents, realsize);
written = realsize;
}
catch (exception &e)
{
error = string(e.what());
}
return written;
}
static size_t WriteMemoryCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
DataFeedRequest *request = (DataFeedRequest*)userp;
return request->ReceiveCallback(contents, size, nmemb);
}
public:
DataFeedRequest(const string& sURL)
: url(sURL)
{
curl = curl_easy_init();
if (curl == NULL)
throw runtime_error("Failed to initialize curl");
curl_easy_setopt(curl, CURLOPT_URL, sURL.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)this);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
if (fUseProxy)
{
curl_easy_setopt(curl, CURLOPT_PROXY, addrProxy.ToStringIP().c_str());
curl_easy_setopt(curl, CURLOPT_PROXYPORT, addrProxy.GetPort());
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
}
~DataFeedRequest()
{
if (curl)
{
curl_easy_cleanup(curl);
curl = NULL;
}
}
void Perform()
{
CURLcode res;
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
long http_code = 0;
if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code) != CURLE_OK)
throw runtime_error("Unable to get data feed response code");
if (http_code != 200)
throw runtime_error((boost::format("Data feed failed: Response code %ld") % http_code).str());
printf("Received %lu bytes from data feed %s:\n%s\n", (long)result.size(), url.c_str(), result.c_str());
}
else
{
if (error == "")
{
error = (boost::format("Data feed failed: %s") % curl_easy_strerror(res)).str();
throw runtime_error(error);
}
else
throw runtime_error(error);
}
}
string GetResult() const
{
return result;
}
};
void VerifyDataFeedSignature(const string& strMessage, const string& strSign, const string& strAddress)
{
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw runtime_error("Invalid data feed address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw runtime_error("Data feed address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw runtime_error("Malformed base64 encoding of data feed signature");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
throw runtime_error("Unable to set key from data feed signature");
if (key.GetPubKey().GetID() != keyID)
throw runtime_error("Data feed signature check failed");
}
bool GetVoteFromDataFeed(const CDataFeed& dataFeed, CVote& voteRet)
{
bool result = false;
try
{
DataFeedRequest request(dataFeed.sURL);
request.Perform();
if (dataFeed.sSignatureAddress != "" && dataFeed.sSignatureURL != "")
{
DataFeedRequest signatureRequest(dataFeed.sSignatureURL);
signatureRequest.Perform();
VerifyDataFeedSignature(request.GetResult(), signatureRequest.GetResult(), dataFeed.sSignatureAddress);
}
Value valReply;
if (!read_string(request.GetResult(), valReply))
throw runtime_error("Data feed returned invalid data");
voteRet = ParseVote(valReply.get_obj());
result = true;
}
catch (exception &e)
{
printf("GetVoteFromDataFeed error: %s\n", e.what());
throw;
}
return result;
}
CVote ParseVote(const Object& objVote)
{
CVote vote;
BOOST_FOREACH(const Pair& voteAttribute, objVote)
{
if (voteAttribute.name_ == "motions")
{
BOOST_FOREACH(const Value& motionVoteObject, voteAttribute.value_.get_array())
vote.vMotion.push_back(uint160(motionVoteObject.get_str()));
}
else if (voteAttribute.name_ == "custodians")
{
BOOST_FOREACH(const Value& custodianVoteObject, voteAttribute.value_.get_array())
{
CCustodianVote custodianVote;
BOOST_FOREACH(const Pair& custodianVoteAttribute, custodianVoteObject.get_obj())
{
if (custodianVoteAttribute.name_ == "address")
{
CBitcoinAddress address(custodianVoteAttribute.value_.get_str());
if (!address.IsValid())
throw runtime_error("Invalid address\n");
custodianVote.SetAddress(address);
if (custodianVote.cUnit == 'S' || !ValidUnit(custodianVote.cUnit))
throw runtime_error("Invalid custodian unit\n");
}
else if (custodianVoteAttribute.name_ == "amount")
custodianVote.nAmount = AmountFromValue(custodianVoteAttribute.value_);
else
throw runtime_error("Invalid custodian vote object\n");
}
vote.vCustodianVote.push_back(custodianVote);
}
}
else if (voteAttribute.name_ == "parkrates")
{
BOOST_FOREACH(const Value& parkRateVoteObject, voteAttribute.value_.get_array())
{
CParkRateVote parkRateVote;
BOOST_FOREACH(const Pair& parkRateVoteAttribute, parkRateVoteObject.get_obj())
{
if (parkRateVoteAttribute.name_ == "unit")
{
parkRateVote.cUnit = parkRateVoteAttribute.value_.get_str()[0];
if (parkRateVote.cUnit == 'S' || !ValidUnit(parkRateVote.cUnit))
throw runtime_error("Invalid park rate unit\n");
}
else if (parkRateVoteAttribute.name_ == "rates")
{
BOOST_FOREACH(const Value& parkRateObject, parkRateVoteAttribute.value_.get_array())
{
CParkRate parkRate;
BOOST_FOREACH(const Pair& parkRateAttribute, parkRateObject.get_obj())
{
if (parkRateAttribute.name_ == "blocks")
{
int blocks = parkRateAttribute.value_.get_int();
double compactDuration = log2(blocks);
double integerPart;
if (modf(compactDuration, &integerPart) != 0.0)
throw runtime_error("Park duration is not a power of 2\n");
if (compactDuration < 0 || compactDuration > 255)
throw runtime_error("Park duration out of range\n");
parkRate.nCompactDuration = compactDuration;
}
else if (parkRateAttribute.name_ == "rate")
{
double dAmount = parkRateAttribute.value_.get_real();
if (dAmount < 0.0 || dAmount > MAX_MONEY)
throw runtime_error("Invalid park rate amount\n");
parkRate.nRate = roundint64(dAmount * COIN_PARK_RATE);
if (!MoneyRange(parkRate.nRate))
throw runtime_error("Invalid park rate amount\n");
}
else
throw runtime_error("Invalid park rate object\n");
}
parkRateVote.vParkRate.push_back(parkRate);
}
}
else
throw runtime_error("Invalid custodian vote object\n");
}
vote.vParkRateVote.push_back(parkRateVote);
}
}
else
throw runtime_error("Invalid vote object\n");
}
return vote;
}
void UpdateFromDataFeed()
{
CWallet* pwallet = GetWallet('S');
CDataFeed dataFeed;
{
LOCK(pwallet->cs_wallet);
dataFeed = pwallet->GetDataFeed();
}
if (dataFeed.sURL == "")
return;
printf("Updating from data feed %s\n", dataFeed.sURL.c_str());
CVote feedVote;
if (GetVoteFromDataFeed(dataFeed, feedVote))
{
LOCK(pwallet->cs_wallet);
CVote newVote = pwallet->vote;
BOOST_FOREACH(const string& sPart, dataFeed.vParts)
{
if (sPart == "custodians")
newVote.vCustodianVote = feedVote.vCustodianVote;
else if (sPart == "parkrates")
newVote.vParkRateVote = feedVote.vParkRateVote;
else if (sPart == "motions")
newVote.vMotion = feedVote.vMotion;
else
throw runtime_error("Invalid part");
}
pwallet->SetVote(newVote);
printf("Vote updated from data feed\n");
}
}
void ThreadUpdateFromDataFeed(void* parg)
{
printf("ThreadUpdateFromDataFeed started\n");
int delay = GetArg("-datafeeddelay", 60);
int64 lastUpdate = GetTime();
while (true)
{
#ifdef TESTING
Sleep(200);
#else
Sleep(1000);
#endif
if (fShutdown)
break;
int64 now = GetTime();
if (now >= lastUpdate + delay)
{
strDataFeedError = "";
try
{
UpdateFromDataFeed();
}
catch (exception &e)
{
printf("UpdateFromDataFeed failed: %s\n", e.what());
strDataFeedError = string(e.what());
}
lastUpdate = now;
}
}
printf("ThreadUpdateFromDataFeed exited\n");
}
void StartUpdateFromDataFeed()
{
if (!CreateThread(ThreadUpdateFromDataFeed, NULL))
printf("Error; CreateThread(ThreadUpdateFromDataFeed) failed\n");
}
<commit_msg>Removed duplicate code<commit_after>#include <curl/curl.h>
#include <cstdlib>
#include <cstring>
#include "datafeed.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "vote.h"
#include "main.h"
#include "bitcoinrpc.h"
#include "wallet.h"
using namespace std;
using namespace json_spirit;
string strDataFeedError = "";
class DataFeedRequest
{
private:
CURL *curl;
string result;
string error;
string url;
size_t ReceiveCallback(char *contents, size_t size, size_t nmemb)
{
if (size == 0 || nmemb == 0)
return 0;
size_t written = 0;
try
{
size_t realsize = size * nmemb;
int nMaxSize = GetArg("maxdatafeedsize", 10 * 1024);
if (result.size() + realsize > nMaxSize)
throw runtime_error((boost::format("Data feed size exceeds limit (%1% bytes)") % nMaxSize).str());
result.append(contents, realsize);
written = realsize;
}
catch (exception &e)
{
error = string(e.what());
}
return written;
}
static size_t WriteMemoryCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
DataFeedRequest *request = (DataFeedRequest*)userp;
return request->ReceiveCallback(contents, size, nmemb);
}
public:
DataFeedRequest(const string& sURL)
: url(sURL)
{
curl = curl_easy_init();
if (curl == NULL)
throw runtime_error("Failed to initialize curl");
curl_easy_setopt(curl, CURLOPT_URL, sURL.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)this);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
if (fUseProxy)
{
curl_easy_setopt(curl, CURLOPT_PROXY, addrProxy.ToStringIP().c_str());
curl_easy_setopt(curl, CURLOPT_PROXYPORT, addrProxy.GetPort());
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
}
~DataFeedRequest()
{
if (curl)
{
curl_easy_cleanup(curl);
curl = NULL;
}
}
void Perform()
{
CURLcode res;
res = curl_easy_perform(curl);
if (res == CURLE_OK)
{
long http_code = 0;
if (curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code) != CURLE_OK)
throw runtime_error("Unable to get data feed response code");
if (http_code != 200)
throw runtime_error((boost::format("Data feed failed: Response code %ld") % http_code).str());
printf("Received %lu bytes from data feed %s:\n%s\n", (long)result.size(), url.c_str(), result.c_str());
}
else
{
if (error == "")
error = (boost::format("Data feed failed: %s") % curl_easy_strerror(res)).str();
throw runtime_error(error);
}
}
string GetResult() const
{
return result;
}
};
void VerifyDataFeedSignature(const string& strMessage, const string& strSign, const string& strAddress)
{
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw runtime_error("Invalid data feed address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw runtime_error("Data feed address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw runtime_error("Malformed base64 encoding of data feed signature");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
throw runtime_error("Unable to set key from data feed signature");
if (key.GetPubKey().GetID() != keyID)
throw runtime_error("Data feed signature check failed");
}
bool GetVoteFromDataFeed(const CDataFeed& dataFeed, CVote& voteRet)
{
bool result = false;
try
{
DataFeedRequest request(dataFeed.sURL);
request.Perform();
if (dataFeed.sSignatureAddress != "" && dataFeed.sSignatureURL != "")
{
DataFeedRequest signatureRequest(dataFeed.sSignatureURL);
signatureRequest.Perform();
VerifyDataFeedSignature(request.GetResult(), signatureRequest.GetResult(), dataFeed.sSignatureAddress);
}
Value valReply;
if (!read_string(request.GetResult(), valReply))
throw runtime_error("Data feed returned invalid data");
voteRet = ParseVote(valReply.get_obj());
result = true;
}
catch (exception &e)
{
printf("GetVoteFromDataFeed error: %s\n", e.what());
throw;
}
return result;
}
CVote ParseVote(const Object& objVote)
{
CVote vote;
BOOST_FOREACH(const Pair& voteAttribute, objVote)
{
if (voteAttribute.name_ == "motions")
{
BOOST_FOREACH(const Value& motionVoteObject, voteAttribute.value_.get_array())
vote.vMotion.push_back(uint160(motionVoteObject.get_str()));
}
else if (voteAttribute.name_ == "custodians")
{
BOOST_FOREACH(const Value& custodianVoteObject, voteAttribute.value_.get_array())
{
CCustodianVote custodianVote;
BOOST_FOREACH(const Pair& custodianVoteAttribute, custodianVoteObject.get_obj())
{
if (custodianVoteAttribute.name_ == "address")
{
CBitcoinAddress address(custodianVoteAttribute.value_.get_str());
if (!address.IsValid())
throw runtime_error("Invalid address\n");
custodianVote.SetAddress(address);
if (custodianVote.cUnit == 'S' || !ValidUnit(custodianVote.cUnit))
throw runtime_error("Invalid custodian unit\n");
}
else if (custodianVoteAttribute.name_ == "amount")
custodianVote.nAmount = AmountFromValue(custodianVoteAttribute.value_);
else
throw runtime_error("Invalid custodian vote object\n");
}
vote.vCustodianVote.push_back(custodianVote);
}
}
else if (voteAttribute.name_ == "parkrates")
{
BOOST_FOREACH(const Value& parkRateVoteObject, voteAttribute.value_.get_array())
{
CParkRateVote parkRateVote;
BOOST_FOREACH(const Pair& parkRateVoteAttribute, parkRateVoteObject.get_obj())
{
if (parkRateVoteAttribute.name_ == "unit")
{
parkRateVote.cUnit = parkRateVoteAttribute.value_.get_str()[0];
if (parkRateVote.cUnit == 'S' || !ValidUnit(parkRateVote.cUnit))
throw runtime_error("Invalid park rate unit\n");
}
else if (parkRateVoteAttribute.name_ == "rates")
{
BOOST_FOREACH(const Value& parkRateObject, parkRateVoteAttribute.value_.get_array())
{
CParkRate parkRate;
BOOST_FOREACH(const Pair& parkRateAttribute, parkRateObject.get_obj())
{
if (parkRateAttribute.name_ == "blocks")
{
int blocks = parkRateAttribute.value_.get_int();
double compactDuration = log2(blocks);
double integerPart;
if (modf(compactDuration, &integerPart) != 0.0)
throw runtime_error("Park duration is not a power of 2\n");
if (compactDuration < 0 || compactDuration > 255)
throw runtime_error("Park duration out of range\n");
parkRate.nCompactDuration = compactDuration;
}
else if (parkRateAttribute.name_ == "rate")
{
double dAmount = parkRateAttribute.value_.get_real();
if (dAmount < 0.0 || dAmount > MAX_MONEY)
throw runtime_error("Invalid park rate amount\n");
parkRate.nRate = roundint64(dAmount * COIN_PARK_RATE);
if (!MoneyRange(parkRate.nRate))
throw runtime_error("Invalid park rate amount\n");
}
else
throw runtime_error("Invalid park rate object\n");
}
parkRateVote.vParkRate.push_back(parkRate);
}
}
else
throw runtime_error("Invalid custodian vote object\n");
}
vote.vParkRateVote.push_back(parkRateVote);
}
}
else
throw runtime_error("Invalid vote object\n");
}
return vote;
}
void UpdateFromDataFeed()
{
CWallet* pwallet = GetWallet('S');
CDataFeed dataFeed;
{
LOCK(pwallet->cs_wallet);
dataFeed = pwallet->GetDataFeed();
}
if (dataFeed.sURL == "")
return;
printf("Updating from data feed %s\n", dataFeed.sURL.c_str());
CVote feedVote;
if (GetVoteFromDataFeed(dataFeed, feedVote))
{
LOCK(pwallet->cs_wallet);
CVote newVote = pwallet->vote;
BOOST_FOREACH(const string& sPart, dataFeed.vParts)
{
if (sPart == "custodians")
newVote.vCustodianVote = feedVote.vCustodianVote;
else if (sPart == "parkrates")
newVote.vParkRateVote = feedVote.vParkRateVote;
else if (sPart == "motions")
newVote.vMotion = feedVote.vMotion;
else
throw runtime_error("Invalid part");
}
pwallet->SetVote(newVote);
printf("Vote updated from data feed\n");
}
}
void ThreadUpdateFromDataFeed(void* parg)
{
printf("ThreadUpdateFromDataFeed started\n");
int delay = GetArg("-datafeeddelay", 60);
int64 lastUpdate = GetTime();
while (true)
{
#ifdef TESTING
Sleep(200);
#else
Sleep(1000);
#endif
if (fShutdown)
break;
int64 now = GetTime();
if (now >= lastUpdate + delay)
{
strDataFeedError = "";
try
{
UpdateFromDataFeed();
}
catch (exception &e)
{
printf("UpdateFromDataFeed failed: %s\n", e.what());
strDataFeedError = string(e.what());
}
lastUpdate = now;
}
}
printf("ThreadUpdateFromDataFeed exited\n");
}
void StartUpdateFromDataFeed()
{
if (!CreateThread(ThreadUpdateFromDataFeed, NULL))
printf("Error; CreateThread(ThreadUpdateFromDataFeed) failed\n");
}
<|endoftext|>
|
<commit_before>#include "iostream"
#include "AliFMDInput.h"
#include "AliFMDHit.h"
#include "TFile.h"
#include "TTree.h"
#include "TClonesArray.h"
#include "AliTrackReference.h"
#include "AliFMDStripIndex.h"
//Script to compare the hits and the FMD track references for one event.
//To run:
//>gSystem->Load("libFMDutil")
//>.L CompareTrackRefsAndHits.C++
//>ReadHits t
//>t.Run()
//Note that the order of hits and trackrefs is different.
class ReadHits : public AliFMDInput{
private:
Int_t nHits;
public:
ReadHits(){
AddLoad(kKinematics);
AddLoad(kHits);
nHits = 0;
}
Bool_t ProcessHit(AliFMDHit* hit, TParticle* p)
{
nHits++;
std::cout<<hit->Px()<<" "<<hit->Py()<<" "<<hit->Pz()<<std::endl;
std::cout<<hit->Detector()<<" "<<hit->Ring()<<" "<<hit->Sector()<<" "<<hit->Strip()<<std::endl;
return kTRUE;
}
Bool_t Finish()
{
Int_t nTracks = 0;
TFile* f=TFile::Open("TrackRefs.root");
TTree* tree = (TTree*)f->Get("Event0/TreeTR");
TClonesArray* array=new TClonesArray("AliTrackReference");
tree->SetBranchAddress("TrackReferences",&array);
UShort_t det,sec,strip;
Char_t ring;
for (int i=0; i<tree->GetEntries(); i++) {
tree->GetEvent(i);
for(Int_t j = 0; j <array->GetEntriesFast();j++) {
AliTrackReference* track = static_cast<AliTrackReference*>(array->At(j));
if(track->DetectorId()==AliTrackReference::kFMD) {
nTracks++;
AliFMDStripIndex::Unpack(track->UserId(),det,ring,sec,strip);
std::cout<<track->Px()<<" "<<track->Py()<<" "<<track->Pz()<<" "<<track->UserId()<<endl;
std::cout<<det<<" "<<ring<<" "<<sec<<" "<<strip<<std::endl;
}
}
}
std::cout<<nTracks<<" "<<nHits<<std::endl;
return kTRUE;
}
};
<commit_msg>Fixes<commit_after>#include "iostream"
#include "AliFMDInput.h"
#include "AliFMDHit.h"
#include "TFile.h"
#include "TTree.h"
#include "TClonesArray.h"
#include "AliTrackReference.h"
#include "AliFMDStripIndex.h"
#include "TParticle.h"
//Script to compare the hits and the FMD track references for one event.
//To run:
//>gSystem->Load("libFMDutil")
//>.L CompareTrackRefsAndHits.C++
//>ReadHits t
//>t.Run()
//Note that the order of hits and trackrefs is different.
class ReadHits : public AliFMDInput{
private:
Int_t nHits;
Int_t nTracks;
public:
ReadHits(){
AddLoad(kKinematics);
AddLoad(kTracks);
AddLoad(kTrackRefs);
AddLoad(kHits);
nHits = 0;
nTracks = 0;
fGAliceFile.Form("galice.root");
}
Bool_t ProcessHit(AliFMDHit* hit, TParticle* p)
{
nHits++;
// std::cout<<hit->Px()<<" "<<hit->Py()<<" "<<hit->Pz()<<std::endl;
//std::cout<<hit->Detector()<<" "<<hit->Ring()<<" "<<hit->Sector()<<" "<<hit->Strip()<<std::endl;
return kTRUE;
}
Bool_t ProcessTrackRef(AliTrackReference* trackRef, TParticle* p)
{
UShort_t det,sec,strip;
Char_t ring;
if(trackRef->DetectorId() == AliTrackReference::kFMD) {
nTracks++;
AliFMDStripIndex::Unpack(trackRef->UserId(),det,ring,sec,strip);
//std::cout<<p->Px()<<" "<<p->Py()<<" "<<p->Pz()<<std::endl;
//std::cout<<det<<" "<<ring<<" "<<sec<<" "<<strip<<std::endl;
}
return kTRUE;
}
Bool_t Finish()
{
// Int_t nTracks = 0;
/* TFile* f=TFile::Open("TrackRefs.root");
TTree* tree = (TTree*)f->Get("Event0/TreeTR");
TClonesArray* array=new TClonesArray("AliTrackReference");
tree->SetBranchAddress("TrackReferences",&array);
UShort_t det,sec,strip;
Char_t ring;
for (int i=0; i<tree->GetEntries(); i++) {
tree->GetEvent(i);
for(Int_t j = 0; j <array->GetEntriesFast();j++) {
AliTrackReference* track = static_cast<AliTrackReference*>(array->At(j));
if(track->DetectorId()==AliTrackReference::kFMD) {
nTracks++;
AliFMDStripIndex::Unpack(track->UserId(),det,ring,sec,strip);
std::cout<<track->Px()<<" "<<track->Py()<<" "<<track->Pz()<<" "<<track->UserId()<<endl;
std::cout<<det<<" "<<ring<<" "<<sec<<" "<<strip<<std::endl;
}
}
}
*/
std::cout<<nTracks<<" "<<nHits<<std::endl;
return kTRUE;
}
};
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/autofill_helper.h"
#include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/webdata/autofill_entry.h"
using autofill_helper::AllProfilesMatch;
using autofill_helper::GetAllKeys;
using autofill_helper::GetAllProfiles;
using autofill_helper::GetKeyCount;
using autofill_helper::GetProfileCount;
using autofill_helper::RemoveKey;
using autofill_helper::SetProfiles;
static const int kNumKeys = 150;
static const int kNumProfiles = 150;
class AutofillSyncPerfTest : public SyncTest {
public:
AutofillSyncPerfTest()
: SyncTest(TWO_CLIENT),
guid_number_(0),
name_number_(0),
value_number_(0) {}
// Adds |num_profiles| new autofill profiles to the sync profile |profile|.
void AddProfiles(int profile, int num_profiles);
// Updates all autofill profiles for the sync profile |profile|.
void UpdateProfiles(int profile);
// Removes all autofill profiles from |profile|.
void RemoveProfiles(int profile);
// Adds |num_keys| new autofill keys to the sync profile |profile|.
void AddKeys(int profile, int num_keys);
// Removes all autofill keys from |profile|.
void RemoveKeys(int profile);
private:
// Returns a new unique autofill profile.
const AutofillProfile NextAutofillProfile();
// Returns a new unique autofill key.
const AutofillKey NextAutofillKey();
// Returns an unused unique guid.
const std::string NextGUID();
// Returns a unique guid based on the input integer |n|.
const std::string IntToGUID(int n);
// Returns a new unused unique name.
const std::string NextName();
// Returns a unique name based on the input integer |n|.
const std::string IntToName(int n);
// Returns a new unused unique value for autofill entries.
const std::string NextValue();
// Returnes a unique value based on the input integer |n|.
const std::string IntToValue(int n);
int guid_number_;
int name_number_;
int value_number_;
DISALLOW_COPY_AND_ASSIGN(AutofillSyncPerfTest);
};
void AutofillSyncPerfTest::AddProfiles(int profile, int num_profiles) {
const std::vector<AutofillProfile*>& all_profiles =
GetAllProfiles(profile);
std::vector<AutofillProfile> autofill_profiles;
for (size_t i = 0; i < all_profiles.size(); ++i) {
autofill_profiles.push_back(*all_profiles[i]);
}
for (int i = 0; i < num_profiles; ++i) {
autofill_profiles.push_back(NextAutofillProfile());
}
SetProfiles(profile, &autofill_profiles);
}
void AutofillSyncPerfTest::UpdateProfiles(int profile) {
const std::vector<AutofillProfile*>& all_profiles =
GetAllProfiles(profile);
std::vector<AutofillProfile> autofill_profiles;
for (size_t i = 0; i < all_profiles.size(); ++i) {
autofill_profiles.push_back(*all_profiles[i]);
autofill_profiles.back().SetInfo(AutofillFieldType(NAME_FIRST),
UTF8ToUTF16(NextName()));
}
SetProfiles(profile, &autofill_profiles);
}
void AutofillSyncPerfTest::RemoveProfiles(int profile) {
std::vector<AutofillProfile> empty;
SetProfiles(profile, &empty);
}
void AutofillSyncPerfTest::AddKeys(int profile, int num_keys) {
std::set<AutofillKey> keys;
for (int i = 0; i < num_keys; ++i) {
keys.insert(NextAutofillKey());
}
autofill_helper::AddKeys(profile, keys);
}
void AutofillSyncPerfTest::RemoveKeys(int profile) {
std::set<AutofillEntry> keys = GetAllKeys(profile);
for (std::set<AutofillEntry>::const_iterator it = keys.begin();
it != keys.end(); ++it) {
RemoveKey(profile, it->key());
}
}
const AutofillProfile AutofillSyncPerfTest::NextAutofillProfile() {
AutofillProfile profile;
autofill_test::SetProfileInfoWithGuid(&profile, NextGUID().c_str(),
NextName().c_str(), "", "", "", "", "",
"", "", "", "", "", "");
return profile;
}
const AutofillKey AutofillSyncPerfTest::NextAutofillKey() {
return AutofillKey(NextName().c_str(), NextName().c_str());
}
const std::string AutofillSyncPerfTest::NextGUID() {
return IntToGUID(guid_number_++);
}
const std::string AutofillSyncPerfTest::IntToGUID(int n) {
return StringPrintf("00000000-0000-0000-0000-%012X", n);
}
const std::string AutofillSyncPerfTest::NextName() {
return IntToName(name_number_++);
}
const std::string AutofillSyncPerfTest::IntToName(int n) {
return StringPrintf("Name%d", n);
}
const std::string AutofillSyncPerfTest::NextValue() {
return IntToValue(value_number_++);
}
const std::string AutofillSyncPerfTest::IntToValue(int n) {
return StringPrintf("Value%d", n);
}
IN_PROC_BROWSER_TEST_F(AutofillSyncPerfTest, AutofillProfiles_P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// TCM ID - 7557873.
AddProfiles(0, kNumProfiles);
base::TimeDelta dt =
SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(kNumProfiles, GetProfileCount(1));
SyncTimingHelper::PrintResult("autofill", "add_autofill_profiles", dt);
// TCM ID - 7549835.
UpdateProfiles(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(kNumProfiles, GetProfileCount(1));
SyncTimingHelper::PrintResult("autofill", "update_autofill_profiles", dt);
// TCM ID - 7553678.
RemoveProfiles(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(0, GetProfileCount(1));
SyncTimingHelper::PrintResult("autofill", "delete_autofill_profiles", dt);
}
IN_PROC_BROWSER_TEST_F(AutofillSyncPerfTest, Autofill_P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
AddKeys(0, kNumKeys);
base::TimeDelta dt =
SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(kNumKeys, GetKeyCount(1));
SyncTimingHelper::PrintResult("autofill", "add_autofill_keys", dt);
RemoveKeys(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(0, GetKeyCount(1));
SyncTimingHelper::PrintResult("autofill", "delete_autofill_keys", dt);
}
<commit_msg>Mark Autofill_P0 flaky on Linux.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/autofill_helper.h"
#include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/webdata/autofill_entry.h"
using autofill_helper::AllProfilesMatch;
using autofill_helper::GetAllKeys;
using autofill_helper::GetAllProfiles;
using autofill_helper::GetKeyCount;
using autofill_helper::GetProfileCount;
using autofill_helper::RemoveKey;
using autofill_helper::SetProfiles;
static const int kNumKeys = 150;
static const int kNumProfiles = 150;
class AutofillSyncPerfTest : public SyncTest {
public:
AutofillSyncPerfTest()
: SyncTest(TWO_CLIENT),
guid_number_(0),
name_number_(0),
value_number_(0) {}
// Adds |num_profiles| new autofill profiles to the sync profile |profile|.
void AddProfiles(int profile, int num_profiles);
// Updates all autofill profiles for the sync profile |profile|.
void UpdateProfiles(int profile);
// Removes all autofill profiles from |profile|.
void RemoveProfiles(int profile);
// Adds |num_keys| new autofill keys to the sync profile |profile|.
void AddKeys(int profile, int num_keys);
// Removes all autofill keys from |profile|.
void RemoveKeys(int profile);
private:
// Returns a new unique autofill profile.
const AutofillProfile NextAutofillProfile();
// Returns a new unique autofill key.
const AutofillKey NextAutofillKey();
// Returns an unused unique guid.
const std::string NextGUID();
// Returns a unique guid based on the input integer |n|.
const std::string IntToGUID(int n);
// Returns a new unused unique name.
const std::string NextName();
// Returns a unique name based on the input integer |n|.
const std::string IntToName(int n);
// Returns a new unused unique value for autofill entries.
const std::string NextValue();
// Returnes a unique value based on the input integer |n|.
const std::string IntToValue(int n);
int guid_number_;
int name_number_;
int value_number_;
DISALLOW_COPY_AND_ASSIGN(AutofillSyncPerfTest);
};
void AutofillSyncPerfTest::AddProfiles(int profile, int num_profiles) {
const std::vector<AutofillProfile*>& all_profiles =
GetAllProfiles(profile);
std::vector<AutofillProfile> autofill_profiles;
for (size_t i = 0; i < all_profiles.size(); ++i) {
autofill_profiles.push_back(*all_profiles[i]);
}
for (int i = 0; i < num_profiles; ++i) {
autofill_profiles.push_back(NextAutofillProfile());
}
SetProfiles(profile, &autofill_profiles);
}
void AutofillSyncPerfTest::UpdateProfiles(int profile) {
const std::vector<AutofillProfile*>& all_profiles =
GetAllProfiles(profile);
std::vector<AutofillProfile> autofill_profiles;
for (size_t i = 0; i < all_profiles.size(); ++i) {
autofill_profiles.push_back(*all_profiles[i]);
autofill_profiles.back().SetInfo(AutofillFieldType(NAME_FIRST),
UTF8ToUTF16(NextName()));
}
SetProfiles(profile, &autofill_profiles);
}
void AutofillSyncPerfTest::RemoveProfiles(int profile) {
std::vector<AutofillProfile> empty;
SetProfiles(profile, &empty);
}
void AutofillSyncPerfTest::AddKeys(int profile, int num_keys) {
std::set<AutofillKey> keys;
for (int i = 0; i < num_keys; ++i) {
keys.insert(NextAutofillKey());
}
autofill_helper::AddKeys(profile, keys);
}
void AutofillSyncPerfTest::RemoveKeys(int profile) {
std::set<AutofillEntry> keys = GetAllKeys(profile);
for (std::set<AutofillEntry>::const_iterator it = keys.begin();
it != keys.end(); ++it) {
RemoveKey(profile, it->key());
}
}
const AutofillProfile AutofillSyncPerfTest::NextAutofillProfile() {
AutofillProfile profile;
autofill_test::SetProfileInfoWithGuid(&profile, NextGUID().c_str(),
NextName().c_str(), "", "", "", "", "",
"", "", "", "", "", "");
return profile;
}
const AutofillKey AutofillSyncPerfTest::NextAutofillKey() {
return AutofillKey(NextName().c_str(), NextName().c_str());
}
const std::string AutofillSyncPerfTest::NextGUID() {
return IntToGUID(guid_number_++);
}
const std::string AutofillSyncPerfTest::IntToGUID(int n) {
return StringPrintf("00000000-0000-0000-0000-%012X", n);
}
const std::string AutofillSyncPerfTest::NextName() {
return IntToName(name_number_++);
}
const std::string AutofillSyncPerfTest::IntToName(int n) {
return StringPrintf("Name%d", n);
}
const std::string AutofillSyncPerfTest::NextValue() {
return IntToValue(value_number_++);
}
const std::string AutofillSyncPerfTest::IntToValue(int n) {
return StringPrintf("Value%d", n);
}
IN_PROC_BROWSER_TEST_F(AutofillSyncPerfTest, AutofillProfiles_P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// TCM ID - 7557873.
AddProfiles(0, kNumProfiles);
base::TimeDelta dt =
SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(kNumProfiles, GetProfileCount(1));
SyncTimingHelper::PrintResult("autofill", "add_autofill_profiles", dt);
// TCM ID - 7549835.
UpdateProfiles(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(kNumProfiles, GetProfileCount(1));
SyncTimingHelper::PrintResult("autofill", "update_autofill_profiles", dt);
// TCM ID - 7553678.
RemoveProfiles(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(0, GetProfileCount(1));
SyncTimingHelper::PrintResult("autofill", "delete_autofill_profiles", dt);
}
// Flaky on Linux, see http://crbug.com/102948
#if defined(OS_LINUX)
#define MAYBE_Autofill_P0 FLAKY_Autofill_P0
#else
#define MAYBE_Autofill_P0 Autofill_P0
#endif
IN_PROC_BROWSER_TEST_F(AutofillSyncPerfTest, MAYBE_Autofill_P0) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
AddKeys(0, kNumKeys);
base::TimeDelta dt =
SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(kNumKeys, GetKeyCount(1));
SyncTimingHelper::PrintResult("autofill", "add_autofill_keys", dt);
RemoveKeys(0);
dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));
ASSERT_EQ(0, GetKeyCount(1));
SyncTimingHelper::PrintResult("autofill", "delete_autofill_keys", dt);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractGrid.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkExtractGrid.h"
#include "vtkBoundingBox.h"
#include "vtkCellData.h"
#include "vtkExtractStructuredGridHelper.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStructuredGrid.h"
vtkStandardNewMacro(vtkExtractGrid);
// Construct object to extract all of the input data.
vtkExtractGrid::vtkExtractGrid()
{
this->VOI[0] = this->VOI[2] = this->VOI[4] = 0;
this->VOI[1] = this->VOI[3] = this->VOI[5] = VTK_INT_MAX;
this->SampleRate[0] = this->SampleRate[1] = this->SampleRate[2] = 1;
this->IncludeBoundary = 0;
this->Internal = vtkExtractStructuredGridHelper::New();
}
vtkExtractGrid::~vtkExtractGrid()
{
if( this->Internal != NULL )
{
this->Internal->Delete();
}
}
int vtkExtractGrid::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
int wholeExtent[6], outWholeExt[6];
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wholeExtent);
this->Internal->Initialize(
this->VOI,wholeExtent,this->SampleRate,(this->IncludeBoundary==1));
this->Internal->GetOutputWholeExtent(outWholeExt);
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
outWholeExt, 6);
return 1;
}
int vtkExtractGrid::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
int i;
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
bool emptyExtent = false;
int uExt[6];
for (i=0; i<3; i++)
{
if (this->Internal->GetSize(i) < 1)
{
uExt[0] = uExt[2] = uExt[4] = 0;
uExt[1] = uExt[3] = uExt[5] = -1;
emptyExtent = true;
break;
}
}
if (!emptyExtent)
{
// Find input update extent based on requested output
// extent
int oUExt[6];
outputVector->GetInformationObject(0)->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), oUExt);
for (i=0; i<3; i++)
{
int idx = oUExt[2*i];
if (idx < 0 || oUExt[2*i] >= (int)this->Internal->GetSize(i))
{
vtkWarningMacro("Requested extent outside whole extent.")
idx = 0;
}
uExt[2*i] = this->Internal->GetMappedExtentValueFromIndex(i, idx);
int jdx = oUExt[2*i+1];
if (jdx < idx || jdx >= (int)this->Internal->GetSize(i))
{
vtkWarningMacro("Requested extent outside whole extent.")
jdx = 0;
}
uExt[2*i + 1] = this->Internal->GetMappedExtentValueFromIndex(i, jdx);
}
}
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), uExt, 6);
// We can handle anything.
inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 0);
return 1;
}
//------------------------------------------------------------------------------
int vtkExtractGrid::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
return this->RequestDataImpl(this->VOI, inputVector, outputVector) ? 0 : 1;
}
//------------------------------------------------------------------------------
bool vtkExtractGrid::RequestDataImpl(int voi[6],
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
if( (this->SampleRate[0] < 1) ||
(this->SampleRate[1] < 1) ||
(this->SampleRate[2] < 1) )
{
vtkErrorMacro("SampleRate must be >= 1 in all 3 dimensions!");
return false;
}
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkStructuredGrid *input = vtkStructuredGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkStructuredGrid *output = vtkStructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPointData *pd=input->GetPointData();
vtkCellData *cd=input->GetCellData();
vtkPointData *outPD=output->GetPointData();
vtkCellData *outCD=output->GetCellData();
int *inExt;
int *outExt;
vtkPoints *newPts, *inPts;
vtkDebugMacro(<< "Extracting Grid");
if (input->GetNumberOfPoints() == 0)
{
return true;
}
inPts = input->GetPoints();
inExt = input->GetExtent();
int begin[3];
int end[3];
this->Internal->ComputeBeginAndEnd(inExt,this->VOI,begin,end);
output->SetExtent(begin[0], end[0], begin[1], end[1], begin[2], end[2]);
newPts = inPts->NewInstance();
outExt = output->GetExtent();
this->Internal->CopyPointsAndPointData(inExt,outExt,pd,inPts,outPD,newPts);
output->SetPoints(newPts);
newPts->Delete();
this->Internal->CopyCellData(inExt,outExt,cd,outCD);
return true;
}
void vtkExtractGrid::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "VOI: \n";
os << indent << " Imin,Imax: (" << this->VOI[0] << ", "
<< this->VOI[1] << ")\n";
os << indent << " Jmin,Jmax: (" << this->VOI[2] << ", "
<< this->VOI[3] << ")\n";
os << indent << " Kmin,Kmax: (" << this->VOI[4] << ", "
<< this->VOI[5] << ")\n";
os << indent << "Sample Rate: (" << this->SampleRate[0] << ", "
<< this->SampleRate[1] << ", "
<< this->SampleRate[2] << ")\n";
os << indent << "Include Boundary: "
<< (this->IncludeBoundary ? "On\n" : "Off\n");
}
<commit_msg>COMP: fix unused warning<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractGrid.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkExtractGrid.h"
#include "vtkBoundingBox.h"
#include "vtkCellData.h"
#include "vtkExtractStructuredGridHelper.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStructuredGrid.h"
vtkStandardNewMacro(vtkExtractGrid);
// Construct object to extract all of the input data.
vtkExtractGrid::vtkExtractGrid()
{
this->VOI[0] = this->VOI[2] = this->VOI[4] = 0;
this->VOI[1] = this->VOI[3] = this->VOI[5] = VTK_INT_MAX;
this->SampleRate[0] = this->SampleRate[1] = this->SampleRate[2] = 1;
this->IncludeBoundary = 0;
this->Internal = vtkExtractStructuredGridHelper::New();
}
vtkExtractGrid::~vtkExtractGrid()
{
if( this->Internal != NULL )
{
this->Internal->Delete();
}
}
int vtkExtractGrid::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
int wholeExtent[6], outWholeExt[6];
inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wholeExtent);
this->Internal->Initialize(
this->VOI,wholeExtent,this->SampleRate,(this->IncludeBoundary==1));
this->Internal->GetOutputWholeExtent(outWholeExt);
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
outWholeExt, 6);
return 1;
}
int vtkExtractGrid::RequestUpdateExtent(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
int i;
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
bool emptyExtent = false;
int uExt[6];
for (i=0; i<3; i++)
{
if (this->Internal->GetSize(i) < 1)
{
uExt[0] = uExt[2] = uExt[4] = 0;
uExt[1] = uExt[3] = uExt[5] = -1;
emptyExtent = true;
break;
}
}
if (!emptyExtent)
{
// Find input update extent based on requested output
// extent
int oUExt[6];
outputVector->GetInformationObject(0)->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), oUExt);
for (i=0; i<3; i++)
{
int idx = oUExt[2*i];
if (idx < 0 || oUExt[2*i] >= (int)this->Internal->GetSize(i))
{
vtkWarningMacro("Requested extent outside whole extent.")
idx = 0;
}
uExt[2*i] = this->Internal->GetMappedExtentValueFromIndex(i, idx);
int jdx = oUExt[2*i+1];
if (jdx < idx || jdx >= (int)this->Internal->GetSize(i))
{
vtkWarningMacro("Requested extent outside whole extent.")
jdx = 0;
}
uExt[2*i + 1] = this->Internal->GetMappedExtentValueFromIndex(i, jdx);
}
}
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), uExt, 6);
// We can handle anything.
inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 0);
return 1;
}
//------------------------------------------------------------------------------
int vtkExtractGrid::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
return this->RequestDataImpl(this->VOI, inputVector, outputVector) ? 0 : 1;
}
//------------------------------------------------------------------------------
bool vtkExtractGrid::RequestDataImpl(int vtkNotUsed(voi)[6],
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
if( (this->SampleRate[0] < 1) ||
(this->SampleRate[1] < 1) ||
(this->SampleRate[2] < 1) )
{
vtkErrorMacro("SampleRate must be >= 1 in all 3 dimensions!");
return false;
}
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkStructuredGrid *input = vtkStructuredGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkStructuredGrid *output = vtkStructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPointData *pd=input->GetPointData();
vtkCellData *cd=input->GetCellData();
vtkPointData *outPD=output->GetPointData();
vtkCellData *outCD=output->GetCellData();
int *inExt;
int *outExt;
vtkPoints *newPts, *inPts;
vtkDebugMacro(<< "Extracting Grid");
if (input->GetNumberOfPoints() == 0)
{
return true;
}
inPts = input->GetPoints();
inExt = input->GetExtent();
int begin[3];
int end[3];
this->Internal->ComputeBeginAndEnd(inExt,this->VOI,begin,end);
output->SetExtent(begin[0], end[0], begin[1], end[1], begin[2], end[2]);
newPts = inPts->NewInstance();
outExt = output->GetExtent();
this->Internal->CopyPointsAndPointData(inExt,outExt,pd,inPts,outPD,newPts);
output->SetPoints(newPts);
newPts->Delete();
this->Internal->CopyCellData(inExt,outExt,cd,outCD);
return true;
}
void vtkExtractGrid::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "VOI: \n";
os << indent << " Imin,Imax: (" << this->VOI[0] << ", "
<< this->VOI[1] << ")\n";
os << indent << " Jmin,Jmax: (" << this->VOI[2] << ", "
<< this->VOI[3] << ")\n";
os << indent << " Kmin,Kmax: (" << this->VOI[4] << ", "
<< this->VOI[5] << ")\n";
os << indent << "Sample Rate: (" << this->SampleRate[0] << ", "
<< this->SampleRate[1] << ", "
<< this->SampleRate[2] << ")\n";
os << indent << "Include Boundary: "
<< (this->IncludeBoundary ? "On\n" : "Off\n");
}
<|endoftext|>
|
<commit_before>// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Dichotomy loop and default search implementation
//
// Author: Skal (pascal.massimino@gmail.com)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "sjpegi.h"
using namespace sjpeg;
////////////////////////////////////////////////////////////////////////////////
// dichotomy
#define DBG_PRINT 0
// convergence is considered reached if |dq| < kdQLimit.
static const float kdQLimit = 0.15;
static float Clamp(float v, float min, float max) {
return (v < min) ? min : (v > max) ? max : v;
}
bool SearchHook::Setup(const SjpegEncodeParam& param) {
for_size = (param.target_mode == SjpegEncodeParam::TARGET_SIZE);
target = param.target_value;
tolerance = param.tolerance / 100.;
qmin = (param.qmin < 0) ? 0 : param.qmin;
qmax = (param.qmax > 100) ? 100 :
(param.qmax < param.qmin) ? param.qmin : param.qmax;
q = Clamp(SjpegEstimateQuality(param.quant_[0], false), qmin, qmax);
value = 0; // undefined for at this point
return true;
}
bool SearchHook::Update(float result) {
value = result;
bool done = (fabs(value - target) < tolerance * target);
if (done) return true;
if (value > target) {
qmax = q;
} else {
qmin = q;
}
const float last_q = q;
q = (qmin + qmax) / 2.;
done = (fabs(q - last_q) < kdQLimit);
if (DBG_PRINT) {
printf("q=%.2f value:%.1f -> next-q=%.2f\n", last_q, value, q);
}
return done;
}
void SearchHook::NextMatrix(int idx, uint8_t dst[64]) {
SetQuantMatrix(kDefaultMatrices[idx], GetQFactor(q), dst);
}
////////////////////////////////////////////////////////////////////////////////
// Helpers for the search
void Encoder::StoreRunLevels(DCTCoeffs* coeffs) {
assert(use_extra_memory_);
assert(reuse_run_levels_);
const QuantizeBlockFunc quantize_block = use_trellis_ ? TrellisQuantizeBlock
: quantize_block_;
if (use_trellis_) InitCodes(true);
ResetDCs();
nb_run_levels_ = 0;
int16_t* in = in_blocks_;
for (int n = 0; n < mb_w_ * mb_h_; ++n) {
CheckBuffers();
for (int c = 0; c < nb_comps_; ++c) {
for (int i = 0; i < nb_blocks_[c]; ++i) {
RunLevel* const run_levels = all_run_levels_ + nb_run_levels_;
const int dc = quantize_block(in, c, &quants_[quant_idx_[c]],
coeffs, run_levels);
coeffs->dc_code_ = GenerateDCDiffCode(dc, &DCs_[c]);
nb_run_levels_ += coeffs->nb_coeffs_;
++coeffs;
in += 64;
}
}
}
}
void Encoder::LoopScan() {
assert(use_extra_memory_);
assert(reuse_run_levels_);
if (use_adaptive_quant_) {
CollectHistograms();
} else {
CollectCoeffs(); // we just need the coeffs
}
const size_t nb_mbs = mb_w_ * mb_h_ * mcu_blocks_;
DCTCoeffs* const base_coeffs = new DCTCoeffs[nb_mbs];
uint8_t opt_quants[2][64];
// Dichotomy passes
float best = 0.; // best distance
float best_q = 0.; // informative value to return to the user
float best_result = 0.;
for (int p = 0; p < passes_; ++p) {
// set new matrices to evaluate
for (int c = 0; c < 2; ++c) {
search_hook_->NextMatrix(c, quants_[c].quant_);
FinalizeQuantMatrix(&quants_[c], q_bias_);
}
if (use_adaptive_quant_) {
AnalyseHisto(); // adjust quant_[] matrices
}
float result;
if (search_hook_->for_size) {
// compute pass to store coeffs / runs / dc_code_
StoreRunLevels(base_coeffs);
if (optimize_size_) {
StoreOptimalHuffmanTables(nb_mbs, base_coeffs);
if (use_trellis_) InitCodes(true);
}
result = ComputeSize(base_coeffs);
} else {
// if we're just targeting PSNR, we don't need to compute the
// run/levels within the loop. We just need to quantize the coeffs
// and measure the distortion.
result = ComputePSNR();
}
if (DBG_PRINT) printf("pass #%d: q=%f value:%.2f\n",
p, search_hook_->q, result);
if (p == 0 || fabs(result - search_hook_->target) < best) {
// save the matrices for later, if they are better
for (int c = 0; c < 2; ++c) {
CopyQuantMatrix(quants_[c].quant_, opt_quants[c]);
}
best = fabs(result - search_hook_->target);
best_q = search_hook_->q;
best_result = result;
}
if (search_hook_->Update(result)) break;
}
// transfer back the final matrices
SetQuantMatrices(opt_quants);
// return informative values to the user
search_hook_->q = best_q;
search_hook_->value = best_result;
// optimize Huffman table now, if we haven't already during the search
if (!search_hook_->for_size) {
StoreRunLevels(base_coeffs);
if (optimize_size_) {
StoreOptimalHuffmanTables(nb_mbs, base_coeffs);
}
}
// finish bitstream
WriteDQT();
WriteSOF();
WriteDHT();
WriteSOS();
FinalPassScan(nb_mbs, base_coeffs);
delete[] base_coeffs;
}
////////////////////////////////////////////////////////////////////////////////
// Size & PSNR computation, mostly for dichotomy
size_t Encoder::HeaderSize() const {
size_t size = 0;
size += 20; // APP0
size += app_markers_.size();
if (exif_.size() > 0) {
size += 8 + exif_.size();
}
if (iccp_.size() > 0) {
const size_t chunk_size_max = 0xffff - 12 - 4;
const size_t num_chunks = (iccp_.size() - 1) / chunk_size_max + 1;
size += num_chunks * (12 + 4 + 2);
size += iccp_.size();
}
if (xmp_.size() > 0) {
size += 2 + 2 + 29 + xmp_.size();
}
size += 2 * 65 + 2 + 2; // DQT
size += 8 + 3 * nb_comps_ + 2; // SOF
size += 6 + 2 * nb_comps_ + 2; // SOS
size += 2; // EOI
// DHT:
for (int c = 0; c < (nb_comps_ == 1 ? 1 : 2); ++c) { // luma, chroma
for (int type = 0; type <= 1; ++type) { // dc, ac
const HuffmanTable* const h = Huffman_tables_[type * 2 + c];
size += 2 + 3 + 16 + h->nb_syms_;
}
}
return size * 8;
}
void Encoder::BlocksSize(int nb_mbs, const DCTCoeffs* coeffs,
const RunLevel* rl,
BitCounter* const bc) const {
for (int n = 0; n < nb_mbs; ++n) {
const DCTCoeffs& c = coeffs[n];
const int idx = c.idx_;
const int q_idx = quant_idx_[idx];
// DC
const int dc_len = c.dc_code_ & 0x0f;
const uint32_t code = dc_codes_[q_idx][dc_len];
bc->AddPackedCode(code);
bc->AddBits(c.dc_code_ >> 4, dc_len);
// AC
const uint32_t* const codes = ac_codes_[q_idx];
for (int i = 0; i < c.nb_coeffs_; ++i) {
int run = rl[i].run_;
while (run & ~15) { // escapes
bc->AddPackedCode(codes[0xf0]);
run -= 16;
}
const uint32_t suffix = rl[i].level_;
const size_t nbits = suffix & 0x0f;
const int sym = (run << 4) | nbits;
bc->AddPackedCode(codes[sym]);
bc->AddBits(suffix >> 4, nbits);
}
if (c.last_ < 63) bc->AddPackedCode(codes[0x00]); // EOB
rl += c.nb_coeffs_;
}
}
float Encoder::ComputeSize(const DCTCoeffs* coeffs) {
InitCodes(false);
size_t size = HeaderSize();
BitCounter bc;
BlocksSize(mb_w_ * mb_h_ * mcu_blocks_, coeffs, all_run_levels_, &bc);
size += bc.Size();
return size / 8.f;
}
////////////////////////////////////////////////////////////////////////////////
static double GetPSNR(uint64_t err, uint64_t size) {
return (err > 0 && size > 0) ? 10. * log10(255. * 255. * size / err) : 99.;
}
float Encoder::ComputePSNR() const {
uint64_t error = 0;
const int16_t* in = in_blocks_;
const size_t nb_mbs = mb_w_ * mb_h_;
for (size_t n = 0; n < nb_mbs; ++n) {
for (int c = 0; c < nb_comps_; ++c) {
const Quantizer* const Q = &quants_[quant_idx_[c]];
for (int i = 0; i < nb_blocks_[c]; ++i) {
error += quantize_error_(in, Q);
in += 64;
}
}
}
return GetPSNR(error, 64ull * nb_mbs * mcu_blocks_);
}
<commit_msg>make GetPSNR() be the same on ARM and x86<commit_after>// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Dichotomy loop and default search implementation
//
// Author: Skal (pascal.massimino@gmail.com)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "sjpegi.h"
using namespace sjpeg;
////////////////////////////////////////////////////////////////////////////////
// dichotomy
#define DBG_PRINT 0
// convergence is considered reached if |dq| < kdQLimit.
static const float kdQLimit = 0.15;
static float Clamp(float v, float min, float max) {
return (v < min) ? min : (v > max) ? max : v;
}
bool SearchHook::Setup(const SjpegEncodeParam& param) {
for_size = (param.target_mode == SjpegEncodeParam::TARGET_SIZE);
target = param.target_value;
tolerance = param.tolerance / 100.;
qmin = (param.qmin < 0) ? 0 : param.qmin;
qmax = (param.qmax > 100) ? 100 :
(param.qmax < param.qmin) ? param.qmin : param.qmax;
q = Clamp(SjpegEstimateQuality(param.quant_[0], false), qmin, qmax);
value = 0; // undefined for at this point
return true;
}
bool SearchHook::Update(float result) {
value = result;
bool done = (fabs(value - target) < tolerance * target);
if (done) return true;
if (value > target) {
qmax = q;
} else {
qmin = q;
}
const float last_q = q;
q = (qmin + qmax) / 2.;
done = (fabs(q - last_q) < kdQLimit);
if (DBG_PRINT) {
printf("q=%.2f value:%.1f -> next-q=%.2f\n", last_q, value, q);
}
return done;
}
void SearchHook::NextMatrix(int idx, uint8_t dst[64]) {
SetQuantMatrix(kDefaultMatrices[idx], GetQFactor(q), dst);
}
////////////////////////////////////////////////////////////////////////////////
// Helpers for the search
void Encoder::StoreRunLevels(DCTCoeffs* coeffs) {
assert(use_extra_memory_);
assert(reuse_run_levels_);
const QuantizeBlockFunc quantize_block = use_trellis_ ? TrellisQuantizeBlock
: quantize_block_;
if (use_trellis_) InitCodes(true);
ResetDCs();
nb_run_levels_ = 0;
int16_t* in = in_blocks_;
for (int n = 0; n < mb_w_ * mb_h_; ++n) {
CheckBuffers();
for (int c = 0; c < nb_comps_; ++c) {
for (int i = 0; i < nb_blocks_[c]; ++i) {
RunLevel* const run_levels = all_run_levels_ + nb_run_levels_;
const int dc = quantize_block(in, c, &quants_[quant_idx_[c]],
coeffs, run_levels);
coeffs->dc_code_ = GenerateDCDiffCode(dc, &DCs_[c]);
nb_run_levels_ += coeffs->nb_coeffs_;
++coeffs;
in += 64;
}
}
}
}
void Encoder::LoopScan() {
assert(use_extra_memory_);
assert(reuse_run_levels_);
if (use_adaptive_quant_) {
CollectHistograms();
} else {
CollectCoeffs(); // we just need the coeffs
}
const size_t nb_mbs = mb_w_ * mb_h_ * mcu_blocks_;
DCTCoeffs* const base_coeffs = new DCTCoeffs[nb_mbs];
uint8_t opt_quants[2][64];
// Dichotomy passes
float best = 0.; // best distance
float best_q = 0.; // informative value to return to the user
float best_result = 0.;
for (int p = 0; p < passes_; ++p) {
// set new matrices to evaluate
for (int c = 0; c < 2; ++c) {
search_hook_->NextMatrix(c, quants_[c].quant_);
FinalizeQuantMatrix(&quants_[c], q_bias_);
}
if (use_adaptive_quant_) {
AnalyseHisto(); // adjust quant_[] matrices
}
float result;
if (search_hook_->for_size) {
// compute pass to store coeffs / runs / dc_code_
StoreRunLevels(base_coeffs);
if (optimize_size_) {
StoreOptimalHuffmanTables(nb_mbs, base_coeffs);
if (use_trellis_) InitCodes(true);
}
result = ComputeSize(base_coeffs);
} else {
// if we're just targeting PSNR, we don't need to compute the
// run/levels within the loop. We just need to quantize the coeffs
// and measure the distortion.
result = ComputePSNR();
}
if (DBG_PRINT) printf("pass #%d: q=%f value:%.2f\n",
p, search_hook_->q, result);
if (p == 0 || fabs(result - search_hook_->target) < best) {
// save the matrices for later, if they are better
for (int c = 0; c < 2; ++c) {
CopyQuantMatrix(quants_[c].quant_, opt_quants[c]);
}
best = fabs(result - search_hook_->target);
best_q = search_hook_->q;
best_result = result;
}
if (search_hook_->Update(result)) break;
}
// transfer back the final matrices
SetQuantMatrices(opt_quants);
// return informative values to the user
search_hook_->q = best_q;
search_hook_->value = best_result;
// optimize Huffman table now, if we haven't already during the search
if (!search_hook_->for_size) {
StoreRunLevels(base_coeffs);
if (optimize_size_) {
StoreOptimalHuffmanTables(nb_mbs, base_coeffs);
}
}
// finish bitstream
WriteDQT();
WriteSOF();
WriteDHT();
WriteSOS();
FinalPassScan(nb_mbs, base_coeffs);
delete[] base_coeffs;
}
////////////////////////////////////////////////////////////////////////////////
// Size & PSNR computation, mostly for dichotomy
size_t Encoder::HeaderSize() const {
size_t size = 0;
size += 20; // APP0
size += app_markers_.size();
if (exif_.size() > 0) {
size += 8 + exif_.size();
}
if (iccp_.size() > 0) {
const size_t chunk_size_max = 0xffff - 12 - 4;
const size_t num_chunks = (iccp_.size() - 1) / chunk_size_max + 1;
size += num_chunks * (12 + 4 + 2);
size += iccp_.size();
}
if (xmp_.size() > 0) {
size += 2 + 2 + 29 + xmp_.size();
}
size += 2 * 65 + 2 + 2; // DQT
size += 8 + 3 * nb_comps_ + 2; // SOF
size += 6 + 2 * nb_comps_ + 2; // SOS
size += 2; // EOI
// DHT:
for (int c = 0; c < (nb_comps_ == 1 ? 1 : 2); ++c) { // luma, chroma
for (int type = 0; type <= 1; ++type) { // dc, ac
const HuffmanTable* const h = Huffman_tables_[type * 2 + c];
size += 2 + 3 + 16 + h->nb_syms_;
}
}
return size * 8;
}
void Encoder::BlocksSize(int nb_mbs, const DCTCoeffs* coeffs,
const RunLevel* rl,
BitCounter* const bc) const {
for (int n = 0; n < nb_mbs; ++n) {
const DCTCoeffs& c = coeffs[n];
const int idx = c.idx_;
const int q_idx = quant_idx_[idx];
// DC
const int dc_len = c.dc_code_ & 0x0f;
const uint32_t code = dc_codes_[q_idx][dc_len];
bc->AddPackedCode(code);
bc->AddBits(c.dc_code_ >> 4, dc_len);
// AC
const uint32_t* const codes = ac_codes_[q_idx];
for (int i = 0; i < c.nb_coeffs_; ++i) {
int run = rl[i].run_;
while (run & ~15) { // escapes
bc->AddPackedCode(codes[0xf0]);
run -= 16;
}
const uint32_t suffix = rl[i].level_;
const size_t nbits = suffix & 0x0f;
const int sym = (run << 4) | nbits;
bc->AddPackedCode(codes[sym]);
bc->AddBits(suffix >> 4, nbits);
}
if (c.last_ < 63) bc->AddPackedCode(codes[0x00]); // EOB
rl += c.nb_coeffs_;
}
}
float Encoder::ComputeSize(const DCTCoeffs* coeffs) {
InitCodes(false);
size_t size = HeaderSize();
BitCounter bc;
BlocksSize(mb_w_ * mb_h_ * mcu_blocks_, coeffs, all_run_levels_, &bc);
size += bc.Size();
return size / 8.f;
}
////////////////////////////////////////////////////////////////////////////////
static float GetPSNR(uint64_t err, uint64_t size) {
// This expression is written such that it gives the same result on ARM
// and x86 (for large values of err/size in particular). Don't change it!
return (err > 0 && size > 0) ? -4.3429448f * log(size / (err / 255. / 255.))
: 99.f;
}
float Encoder::ComputePSNR() const {
uint64_t error = 0;
const int16_t* in = in_blocks_;
const size_t nb_mbs = mb_w_ * mb_h_;
for (size_t n = 0; n < nb_mbs; ++n) {
for (int c = 0; c < nb_comps_; ++c) {
const Quantizer* const Q = &quants_[quant_idx_[c]];
for (int i = 0; i < nb_blocks_[c]; ++i) {
error += quantize_error_(in, Q);
in += 64;
}
}
}
return GetPSNR(error, 64ull * nb_mbs * mcu_blocks_);
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// AGPLab1
//
// Created by Shockk on 27/09/2013.
// Copyright (c) 2013 Shockk. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <SDL.h>
#if defined(_WIN32) || defined(__linux__)
#define GLEW_STATIC
#include <GL/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include <OpenGL/gl3.h>
#include <OpenGL/gl3ext.h>
#endif
#define ATTRIB_VERTEX 0
#define ATTRIB_COLOR 1
#define ATTRIB_NORMAL 2
#define ATTRIB_TEXCOORD 3
#define ATTRIB_INDEX 4
GLfloat vertices[] =
{
-1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f
};
GLfloat colors[] =
{
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
GLfloat vertices2[] =
{
0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f,
1.0f, 0.0f, 0.0f
};
GLuint vao[2];
GLuint vbo[3];
char * load_file(const char *path, long *len)
{
char *buffer = NULL;
long err = 0;
// open binary file for reading
FILE *fh = fopen(path, "rb");
if(!fh)
{
fprintf(stderr, "fopen: error\n");
return NULL;
}
// fseek to end
err = fseek(fh, 0L, SEEK_END);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// get file size
*len = ftell(fh);
if(*len == -1L)
{
fprintf(stderr, "ftell: error\n");
return NULL;
}
// fseek to start
err = fseek(fh, 0L, SEEK_SET);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// allocate buffer
buffer = (char *)malloc(*len);
if(buffer == NULL)
{
fprintf(stderr, "malloc: error\n");
return NULL;
}
// read into buffer
err = fread(buffer, *len, 1, fh);
if(err != 1)
{
fprintf(stderr, "fread: error\n");
return NULL;
}
// close file
err = fclose(fh);
if(err == EOF) fprintf(stderr, "fclose: error\n");
return buffer;
}
SDL_Window * setup_rc(SDL_GLContext *ctx)
{
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "SDL_Init: error\n");
return NULL;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
SDL_Window *wnd = SDL_CreateWindow("AGPLab1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
1280, 800,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
| SDL_WINDOW_FULLSCREEN_DESKTOP);
if(!wnd)
{
fprintf(stderr, "SDL_CreateWindow: error\n");
return NULL;
}
*ctx = SDL_GL_CreateContext(wnd);
if(!*ctx)
{
fprintf(stderr, "SDL_GL_CreateContext: error: %s\n", SDL_GetError());
return NULL;
}
// enable vsync
SDL_GL_SetSwapInterval(1);
return wnd;
}
void printShaderError(const GLint shader) {
int maxLength = 0;
int logLength = 0;
GLchar *logMessage;
// Find out how long the error message is
if (!glIsShader(shader))
glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
else
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
if (maxLength > 0) { // If message has some contents
logMessage = new GLchar[maxLength];
if (!glIsShader(shader))
glGetProgramInfoLog(shader, maxLength, &logLength, logMessage);
else
glGetShaderInfoLog(shader,maxLength, &logLength, logMessage);
fprintf(stderr, "%s\n", logMessage);
delete [] logMessage;
}
// should additionally check for OpenGL errors here
}
GLuint init_shaders(const char *v_path, const char *f_path)
{
GLuint v_id = glCreateShader(GL_VERTEX_SHADER);
GLuint f_id = glCreateShader(GL_FRAGMENT_SHADER);
long v_len, f_len;
const char *v_src = load_file(v_path, &v_len);
const char *f_src = load_file(f_path, &f_len);
glShaderSource(f_id, 1, &f_src, (GLint *)&f_len);
glShaderSource(v_id, 1, &v_src, (GLint *)&v_len);
GLint compile_status;
glCompileShader(v_id);
glGetShaderiv(v_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(v_id): error\n");
printShaderError(v_id);
}
glCompileShader(f_id);
glGetShaderiv(f_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(f_id): error\n");
printShaderError(f_id);
}
GLuint p_id = glCreateProgram();
glAttachShader(p_id, v_id);
glAttachShader(p_id, f_id);
glBindAttribLocation(p_id, ATTRIB_VERTEX, "a_vVertex");
glBindAttribLocation(p_id, ATTRIB_COLOR, "a_vColor");
glBindAttribLocation(p_id, ATTRIB_NORMAL, "a_vNormal");
glBindAttribLocation(p_id, ATTRIB_TEXCOORD, "a_vTexCoord");
glLinkProgram(p_id);
glUseProgram(p_id);
free((void *)v_src);
free((void *)f_src);
return p_id;
}
void init(void)
{
init_shaders("minimal.vsh", "minimal.fsh");
glGenVertexArrays(1, &vao[0]);
glBindVertexArray(vao[0]);
glGenBuffers(1, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glGenBuffers(1, &vbo[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), colors, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_COLOR, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_COLOR);
glGenVertexArrays(1, &vao[1]);
glBindVertexArray(vao[1]);
glGenBuffers(1, &vbo[2]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices2, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glBindVertexArray(vao[0]);
}
void draw(SDL_Window * window) {
// clear the screen - good to use grey as all white or all black triangles will still be visible
glClearColor(0.5f,0.5f,0.5f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao[0]); // Bind mesh VAO
glDrawArrays(GL_TRIANGLES, 0, 3); // draw 3 vertices (one triangle)
glBindVertexArray(vao[1]); // Bind mesh VAO
glDrawArrays(GL_TRIANGLES, 0, 3); // draw 3 vertices (one triangle)
// These are deprecated functions. If a core profile has been correctly
// created, these commands should compile, but wont render anything
glColor3f(0.5,1.0,1.0);
glBegin(GL_TRIANGLES);
glVertex3f(0.5,0.5,0.0);
glVertex3f(0.7,0.5,0.0);
glVertex3f(0.5,0.7,0.0);
glEnd();
SDL_GL_SwapWindow(window); // swap buffers
}
int main(int argc, const char ** argv)
{
SDL_GLContext ctx;
SDL_Window *wnd = setup_rc(&ctx);
if(!wnd)
{
fprintf(stderr, "setup_rc: error\n");
return 1;
}
#if defined(_WIN32) || defined(__linux__)
glewExperimental = true;
GLenum err = glewInit();
if(err != GLEW_OK)
{
fprintf(stderr, "glewInit: error\n");
return 1;
}
#endif
init();
SDL_Event e;
for(unsigned char running=1; running;)
{
SDL_PollEvent(&e);
switch(e.type)
{
case SDL_QUIT:
{
running = 0;
break;
}
case SDL_KEYDOWN:
{
switch(e.key.keysym.sym)
{
case SDLK_ESCAPE:
running = 0;
break;
}
break;
}
}
draw(wnd);
}
SDL_DestroyWindow(wnd);
SDL_Quit();
return 0;
}
<commit_msg>Reformatted indented and some functions.<commit_after>//
// main.cpp
// AGPLab1
//
// Created by Shockk on 27/09/2013.
// Copyright (c) 2013 Shockk. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <SDL.h>
#if defined(_WIN32) || defined(__linux__)
#define GLEW_STATIC
#include <GL/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include <OpenGL/gl3.h>
#include <OpenGL/gl3ext.h>
#endif
#define ATTRIB_VERTEX 0
#define ATTRIB_COLOR 1
#define ATTRIB_NORMAL 2
#define ATTRIB_TEXCOORD 3
#define ATTRIB_INDEX 4
GLfloat vertices[] =
{
-1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f
};
GLfloat colors[] =
{
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
GLfloat vertices2[] =
{
0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f,
1.0f, 0.0f, 0.0f
};
GLuint vao[2];
GLuint vbo[3];
char * load_file(const char *path, long *len)
{
char *buffer = NULL;
long err = 0;
// open binary file for reading
FILE *fh = fopen(path, "rb");
if(!fh)
{
fprintf(stderr, "fopen: error\n");
return NULL;
}
// fseek to end
err = fseek(fh, 0L, SEEK_END);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// get file size
*len = ftell(fh);
if(*len == -1L)
{
fprintf(stderr, "ftell: error\n");
return NULL;
}
// fseek to start
err = fseek(fh, 0L, SEEK_SET);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// allocate buffer
buffer = (char *)malloc(*len);
if(buffer == NULL)
{
fprintf(stderr, "malloc: error\n");
return NULL;
}
// read into buffer
err = fread(buffer, *len, 1, fh);
if(err != 1)
{
fprintf(stderr, "fread: error\n");
return NULL;
}
// close file
err = fclose(fh);
if(err == EOF) fprintf(stderr, "fclose: error\n");
return buffer;
}
SDL_Window * setup_rc(SDL_GLContext *ctx)
{
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "SDL_Init: error\n");
return NULL;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
SDL_Window *wnd = SDL_CreateWindow("AGPLab1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
1280, 800,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
| SDL_WINDOW_FULLSCREEN_DESKTOP);
if(!wnd)
{
fprintf(stderr, "SDL_CreateWindow: error\n");
return NULL;
}
*ctx = SDL_GL_CreateContext(wnd);
if(!*ctx)
{
fprintf(stderr, "SDL_GL_CreateContext: error: %s\n", SDL_GetError());
return NULL;
}
// enable vsync
SDL_GL_SetSwapInterval(1);
return wnd;
}
void print_shader_error(GLint shader)
{
GLint max_len = 0;
GLint log_len = 0;
unsigned char is_shader = glIsShader(shader);
if(is_shader) glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_len);
else glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &max_len);
if(max_len > 0)
{
GLchar *message = (GLchar *)malloc(sizeof(GLchar) * max_len);
if(is_shader) glGetShaderInfoLog(shader, max_len, &log_len, message);
else glGetProgramInfoLog(shader, max_len, &log_len, message);
fprintf(stderr, "%s\n", message);
free(message);
}
}
GLuint init_shaders(const char *v_path, const char *f_path)
{
GLuint v_id = glCreateShader(GL_VERTEX_SHADER);
GLuint f_id = glCreateShader(GL_FRAGMENT_SHADER);
long v_len, f_len;
const char *v_src = load_file(v_path, &v_len);
const char *f_src = load_file(f_path, &f_len);
glShaderSource(f_id, 1, &f_src, (GLint *)&f_len);
glShaderSource(v_id, 1, &v_src, (GLint *)&v_len);
GLint compile_status;
glCompileShader(v_id);
glGetShaderiv(v_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(v_id): error\n");
print_shader_error(v_id);
}
glCompileShader(f_id);
glGetShaderiv(f_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(f_id): error\n");
print_shader_error(f_id);
}
GLuint p_id = glCreateProgram();
glAttachShader(p_id, v_id);
glAttachShader(p_id, f_id);
glBindAttribLocation(p_id, ATTRIB_VERTEX, "a_vVertex");
glBindAttribLocation(p_id, ATTRIB_COLOR, "a_vColor");
glBindAttribLocation(p_id, ATTRIB_NORMAL, "a_vNormal");
glBindAttribLocation(p_id, ATTRIB_TEXCOORD, "a_vTexCoord");
glLinkProgram(p_id);
glUseProgram(p_id);
free((void *)v_src);
free((void *)f_src);
return p_id;
}
void init(void)
{
init_shaders("minimal.vsh", "minimal.fsh");
glGenVertexArrays(1, &vao[0]);
glBindVertexArray(vao[0]);
glGenBuffers(1, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glGenBuffers(1, &vbo[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), colors, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_COLOR, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_COLOR);
glGenVertexArrays(1, &vao[1]);
glBindVertexArray(vao[1]);
glGenBuffers(1, &vbo[2]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices2, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glBindVertexArray(vao[0]);
}
void draw(SDL_Window *wnd)
{
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(vao[1]);
glDrawArrays(GL_TRIANGLES, 0, 3);
// if core profile is active, should not render anything
glColor3f(0.5f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(0.7f, 0.5f, 0.0f);
glVertex3f(0.5f, 0.7f, 0.0f);
SDL_GL_SwapWindow(wnd);
}
int main(int argc, const char ** argv)
{
SDL_GLContext ctx;
SDL_Window *wnd = setup_rc(&ctx);
if(!wnd)
{
fprintf(stderr, "setup_rc: error\n");
return 1;
}
#if defined(_WIN32) || defined(__linux__)
glewExperimental = true;
GLenum err = glewInit();
if(err != GLEW_OK)
{
fprintf(stderr, "glewInit: error\n");
return 1;
}
#endif
init();
SDL_Event e;
for(unsigned char running=1; running;)
{
SDL_PollEvent(&e);
switch(e.type)
{
case SDL_QUIT:
{
running = 0;
break;
}
case SDL_KEYDOWN:
{
switch(e.key.keysym.sym)
{
case SDLK_ESCAPE:
running = 0;
break;
}
break;
}
}
draw(wnd);
}
SDL_DestroyWindow(wnd);
SDL_Quit();
return 0;
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// AGPLab1
//
// Created by Shockk on 27/09/2013.
// Copyright (c) 2013 Shockk. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <SDL.h>
#if defined(_WIN32) || defined(__linux__)
#define GLEW_STATIC
#include <GL/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include <OpenGL/gl3.h>
#include <OpenGL/gl3ext.h>
#endif
#define ATTRIB_VERTEX 0
#define ATTRIB_COLOR 1
#define ATTRIB_NORMAL 2
#define ATTRIB_TEXCOORD 3
#define ATTRIB_INDEX 4
GLfloat vertices[] =
{
-1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f
};
GLfloat colors[] =
{
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
GLfloat vertices2[] =
{
0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f,
1.0f, 0.0f, 0.0f
};
GLuint vao[2];
GLuint vbo[3];
char * load_file(const char *path, long *len)
{
char *buffer = NULL;
long err = 0;
// open binary file for reading
FILE *fh = fopen(path, "rb");
if(!fh)
{
fprintf(stderr, "fopen: error\n");
return NULL;
}
// fseek to end
err = fseek(fh, 0L, SEEK_END);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// get file size
*len = ftell(fh);
if(*len == -1L)
{
fprintf(stderr, "ftell: error\n");
return NULL;
}
// fseek to start
err = fseek(fh, 0L, SEEK_SET);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// allocate buffer
buffer = (char *)malloc(*len);
if(buffer == NULL)
{
fprintf(stderr, "malloc: error\n");
return NULL;
}
// read into buffer
err = fread(buffer, *len, 1, fh);
if(err != 1)
{
fprintf(stderr, "fread: error\n");
return NULL;
}
// close file
err = fclose(fh);
if(err == EOF) fprintf(stderr, "fclose: error\n");
return buffer;
}
SDL_Window * setup_rc(SDL_GLContext *ctx)
{
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "SDL_Init: error: %s\n", SDL_GetError());
return NULL;
}
// create dummy window and context to test default options
SDL_Window *wnd = SDL_CreateWindow("", 0, 0, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
if(!wnd)
{
fprintf(stderr, "SDL_CreateWindow: dummy error: %s\n", SDL_GetError());
return NULL;
}
*ctx = SDL_GL_CreateContext(wnd);
if(!*ctx)
{
fprintf(stderr, "SDL_GL_CreateContext: dummy error: %s\n", SDL_GetError());
return NULL;
}
// debug info
fprintf(stderr, "[DUMMY] OpenGL version: %s\n", glGetString(GL_VERSION));
fprintf(stderr, "[DUMMY] GLSL version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
SDL_GL_DeleteContext(*ctx);
SDL_DestroyWindow(wnd);
// set attributes and create window and context
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
wnd = SDL_CreateWindow("AGPLab1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
1280, 720,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
| SDL_WINDOW_BORDERLESS);
if(!wnd)
{
fprintf(stderr, "SDL_CreateWindow: error: %s\n", SDL_GetError());
return NULL;
}
*ctx = SDL_GL_CreateContext(wnd);
if(!*ctx)
{
fprintf(stderr, "SDL_GL_CreateContext: error: %s\n", SDL_GetError());
return NULL;
}
// debug info
fprintf(stderr, "OpenGL version: %s\n", glGetString(GL_VERSION));
fprintf(stderr, "GLSL version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
// enable vsync
//SDL_GL_SetSwapInterval(1);
return wnd;
}
void print_shader_error(GLint shader)
{
GLint max_len = 0;
GLint log_len = 0;
unsigned char is_shader = glIsShader(shader);
if(is_shader) glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_len);
else glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &max_len);
if(max_len > 0)
{
GLchar *message = (GLchar *)malloc(sizeof(GLchar) * max_len);
if(is_shader) glGetShaderInfoLog(shader, max_len, &log_len, message);
else glGetProgramInfoLog(shader, max_len, &log_len, message);
fprintf(stderr, "%s\n", message);
free(message);
}
}
GLuint init_shaders(const char *v_path, const char *f_path)
{
GLuint v_id = glCreateShader(GL_VERTEX_SHADER);
GLuint f_id = glCreateShader(GL_FRAGMENT_SHADER);
long v_len, f_len;
const char *v_src = load_file(v_path, &v_len);
const char *f_src = load_file(f_path, &f_len);
glShaderSource(f_id, 1, &f_src, (GLint *)&f_len);
glShaderSource(v_id, 1, &v_src, (GLint *)&v_len);
GLint compile_status;
glCompileShader(v_id);
glGetShaderiv(v_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(v_id): error\n");
print_shader_error(v_id);
}
glCompileShader(f_id);
glGetShaderiv(f_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(f_id): error\n");
print_shader_error(f_id);
}
GLuint p_id = glCreateProgram();
glAttachShader(p_id, v_id);
glAttachShader(p_id, f_id);
glBindAttribLocation(p_id, ATTRIB_VERTEX, "a_vVertex");
glBindAttribLocation(p_id, ATTRIB_COLOR, "a_vColor");
glBindAttribLocation(p_id, ATTRIB_NORMAL, "a_vNormal");
glBindAttribLocation(p_id, ATTRIB_TEXCOORD, "a_vTexCoord");
glLinkProgram(p_id);
glUseProgram(p_id);
free((void *)v_src);
free((void *)f_src);
return p_id;
}
void init(void)
{
init_shaders("minimal.vsh", "minimal.fsh");
glGenVertexArrays(1, &vao[0]);
glBindVertexArray(vao[0]);
glGenBuffers(1, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glGenBuffers(1, &vbo[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), colors, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_COLOR, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_COLOR);
glGenVertexArrays(1, &vao[1]);
glBindVertexArray(vao[1]);
glGenBuffers(1, &vbo[2]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices2, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glBindVertexArray(vao[0]);
}
void draw(SDL_Window *wnd)
{
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(vao[1]);
glDrawArrays(GL_TRIANGLES, 0, 3);
// if core profile is active, should not render anything
glColor3f(0.5f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(0.7f, 0.5f, 0.0f);
glVertex3f(0.5f, 0.7f, 0.0f);
SDL_GL_SwapWindow(wnd);
}
int main(int argc, const char ** argv)
{
SDL_GLContext ctx;
SDL_Window *wnd = setup_rc(&ctx);
if(!wnd)
{
fprintf(stderr, "setup_rc: error\n");
return 1;
}
#if defined(_WIN32) || defined(__linux__)
glewExperimental = true;
GLenum err = glewInit();
if(err != GLEW_OK)
{
fprintf(stderr, "glewInit: error\n");
return 1;
}
#endif
init();
SDL_Event e;
for(unsigned char running=1; running;)
{
SDL_PollEvent(&e);
switch(e.type)
{
case SDL_QUIT:
{
running = 0;
break;
}
case SDL_KEYDOWN:
{
switch(e.key.keysym.sym)
{
case SDLK_ESCAPE:
running = 0;
break;
}
break;
}
}
draw(wnd);
}
SDL_DestroyWindow(wnd);
SDL_Quit();
return 0;
}
<commit_msg>Fixed vsync issue on linux and potentially other platforms by processing all new events before drawing, rather than only one per iteration.<commit_after>//
// main.cpp
// AGPLab1
//
// Created by Shockk on 27/09/2013.
// Copyright (c) 2013 Shockk. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <SDL.h>
#if defined(_WIN32) || defined(__linux__)
#define GLEW_STATIC
#include <GL/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include <OpenGL/gl3.h>
#include <OpenGL/gl3ext.h>
#endif
#define ATTRIB_VERTEX 0
#define ATTRIB_COLOR 1
#define ATTRIB_NORMAL 2
#define ATTRIB_TEXCOORD 3
#define ATTRIB_INDEX 4
GLfloat vertices[] =
{
-1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f
};
GLfloat colors[] =
{
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f
};
GLfloat vertices2[] =
{
0.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f,
1.0f, 0.0f, 0.0f
};
GLuint vao[2];
GLuint vbo[3];
char * load_file(const char *path, long *len)
{
char *buffer = NULL;
long err = 0;
// open binary file for reading
FILE *fh = fopen(path, "rb");
if(!fh)
{
fprintf(stderr, "fopen: error\n");
return NULL;
}
// fseek to end
err = fseek(fh, 0L, SEEK_END);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// get file size
*len = ftell(fh);
if(*len == -1L)
{
fprintf(stderr, "ftell: error\n");
return NULL;
}
// fseek to start
err = fseek(fh, 0L, SEEK_SET);
if(err != 0)
{
fprintf(stderr, "fseek: error\n");
return NULL;
}
// allocate buffer
buffer = (char *)malloc(*len);
if(buffer == NULL)
{
fprintf(stderr, "malloc: error\n");
return NULL;
}
// read into buffer
err = fread(buffer, *len, 1, fh);
if(err != 1)
{
fprintf(stderr, "fread: error\n");
return NULL;
}
// close file
err = fclose(fh);
if(err == EOF) fprintf(stderr, "fclose: error\n");
return buffer;
}
SDL_Window * setup_rc(SDL_GLContext *ctx)
{
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "SDL_Init: error: %s\n", SDL_GetError());
return NULL;
}
// create dummy window and context to test default options
SDL_Window *wnd = SDL_CreateWindow("", 0, 0, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
if(!wnd)
{
fprintf(stderr, "SDL_CreateWindow: dummy error: %s\n", SDL_GetError());
return NULL;
}
*ctx = SDL_GL_CreateContext(wnd);
if(!*ctx)
{
fprintf(stderr, "SDL_GL_CreateContext: dummy error: %s\n", SDL_GetError());
return NULL;
}
// debug info
fprintf(stderr, "[DUMMY] OpenGL version: %s\n", glGetString(GL_VERSION));
fprintf(stderr, "[DUMMY] GLSL version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
SDL_GL_DeleteContext(*ctx);
SDL_DestroyWindow(wnd);
// set attributes and create window and context
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
wnd = SDL_CreateWindow("AGPLab1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
1280, 720,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
| SDL_WINDOW_BORDERLESS);
if(!wnd)
{
fprintf(stderr, "SDL_CreateWindow: error: %s\n", SDL_GetError());
return NULL;
}
*ctx = SDL_GL_CreateContext(wnd);
if(!*ctx)
{
fprintf(stderr, "SDL_GL_CreateContext: error: %s\n", SDL_GetError());
return NULL;
}
// debug info
fprintf(stderr, "OpenGL version: %s\n", glGetString(GL_VERSION));
fprintf(stderr, "GLSL version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
// enable vsync
SDL_GL_SetSwapInterval(1);
return wnd;
}
void print_shader_error(GLint shader)
{
GLint max_len = 0;
GLint log_len = 0;
unsigned char is_shader = glIsShader(shader);
if(is_shader) glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_len);
else glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &max_len);
if(max_len > 0)
{
GLchar *message = (GLchar *)malloc(sizeof(GLchar) * max_len);
if(is_shader) glGetShaderInfoLog(shader, max_len, &log_len, message);
else glGetProgramInfoLog(shader, max_len, &log_len, message);
fprintf(stderr, "%s\n", message);
free(message);
}
}
GLuint init_shaders(const char *v_path, const char *f_path)
{
GLuint v_id = glCreateShader(GL_VERTEX_SHADER);
GLuint f_id = glCreateShader(GL_FRAGMENT_SHADER);
long v_len, f_len;
const char *v_src = load_file(v_path, &v_len);
const char *f_src = load_file(f_path, &f_len);
glShaderSource(f_id, 1, &f_src, (GLint *)&f_len);
glShaderSource(v_id, 1, &v_src, (GLint *)&v_len);
GLint compile_status;
glCompileShader(v_id);
glGetShaderiv(v_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(v_id): error\n");
print_shader_error(v_id);
}
glCompileShader(f_id);
glGetShaderiv(f_id, GL_COMPILE_STATUS, &compile_status);
if(!compile_status)
{
fprintf(stderr, "glCompileShader(f_id): error\n");
print_shader_error(f_id);
}
GLuint p_id = glCreateProgram();
glAttachShader(p_id, v_id);
glAttachShader(p_id, f_id);
glBindAttribLocation(p_id, ATTRIB_VERTEX, "a_vVertex");
glBindAttribLocation(p_id, ATTRIB_COLOR, "a_vColor");
glBindAttribLocation(p_id, ATTRIB_NORMAL, "a_vNormal");
glBindAttribLocation(p_id, ATTRIB_TEXCOORD, "a_vTexCoord");
glLinkProgram(p_id);
glUseProgram(p_id);
free((void *)v_src);
free((void *)f_src);
return p_id;
}
void init(void)
{
init_shaders("minimal.vsh", "minimal.fsh");
glGenVertexArrays(1, &vao[0]);
glBindVertexArray(vao[0]);
glGenBuffers(1, &vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glGenBuffers(1, &vbo[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), colors, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_COLOR, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_COLOR);
glGenVertexArrays(1, &vao[1]);
glBindVertexArray(vao[1]);
glGenBuffers(1, &vbo[2]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
glBufferData(GL_ARRAY_BUFFER, 3 * 3 * sizeof(float), vertices2, GL_STATIC_DRAW);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glBindVertexArray(vao[0]);
}
void draw(SDL_Window *wnd)
{
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(vao[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(vao[1]);
glDrawArrays(GL_TRIANGLES, 0, 3);
// if core profile is active, should not render anything
glColor3f(0.5f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(0.7f, 0.5f, 0.0f);
glVertex3f(0.5f, 0.7f, 0.0f);
SDL_GL_SwapWindow(wnd);
}
int main(int argc, const char ** argv)
{
SDL_GLContext ctx;
SDL_Window *wnd = setup_rc(&ctx);
if(!wnd)
{
fprintf(stderr, "setup_rc: error\n");
return 1;
}
#if defined(_WIN32) || defined(__linux__)
glewExperimental = true;
GLenum err = glewInit();
if(err != GLEW_OK)
{
fprintf(stderr, "glewInit: error\n");
return 1;
}
#endif
init();
SDL_Event e;
for(unsigned char running=1; running;)
{
unsigned char event_avail = 1;
for(;;)
{
event_avail = SDL_PollEvent(&e);
if(!event_avail) break;
switch(e.type)
{
case SDL_QUIT:
{
running = 0;
break;
}
case SDL_KEYDOWN:
{
switch(e.key.keysym.sym)
{
case SDLK_ESCAPE:
running = 0;
break;
}
break;
}
}
}
draw(wnd);
}
SDL_DestroyWindow(wnd);
SDL_Quit();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, The Cinder Project: http://libcinder.org All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Portions of this code (C) Paul Houx
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.
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 "cinder/CameraUi.h"
namespace cinder {
CameraUi::CameraUi()
: mCamera( nullptr ), mWindowSize( 640, 480 ), mMouseWheelMultiplier( 1.2f ), mMinimumPivotDistance( 1.0f ),
mEnabled( true ), mLastAction( ACTION_NONE )
{}
CameraUi::CameraUi( CameraPersp *camera, const app::WindowRef &window, int signalPriority )
: mCamera( camera ), mWindowSize( 640, 480 ), mMouseWheelMultiplier( 1.2f ), mMinimumPivotDistance( 1.0f ),
mEnabled( true )
{
connect( window, signalPriority );
}
CameraUi::CameraUi( const CameraUi &rhs )
: mCamera( rhs.mCamera ), mWindowSize( rhs.mWindowSize ),
mWindow( rhs.mWindow ), mSignalPriority( rhs.mSignalPriority ),
mMouseWheelMultiplier( rhs.mMouseWheelMultiplier ), mMinimumPivotDistance( rhs.mMinimumPivotDistance ),
mEnabled( rhs.mEnabled )
{
connect( mWindow, mSignalPriority );
}
CameraUi::~CameraUi()
{
disconnect();
}
CameraUi& CameraUi::operator=( const CameraUi &rhs )
{
mCamera = rhs.mCamera;
mWindowSize = rhs.mWindowSize;
mMouseWheelMultiplier = rhs.mMouseWheelMultiplier;
mMinimumPivotDistance = rhs.mMinimumPivotDistance;
mWindow = rhs.mWindow;
mSignalPriority = rhs.mSignalPriority;
mEnabled = rhs.mEnabled;
connect( mWindow, mSignalPriority );
return *this;
}
//! Connects to mouseDown, mouseDrag, mouseWheel and resize signals of \a window, with optional priority \a signalPriority
void CameraUi::connect( const app::WindowRef &window, int signalPriority )
{
mWindow = window;
mSignalPriority = signalPriority;
if( window ) {
mMouseDownConnection = window->getSignalMouseDown().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseDown( event ); } );
mMouseUpConnection = window->getSignalMouseUp().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseUp( event ); } );
mMouseDragConnection = window->getSignalMouseDrag().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseDrag( event ); } );
mMouseWheelConnection = window->getSignalMouseWheel().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseWheel( event ); } );
mWindowResizeConnection = window->getSignalResize().connect( signalPriority,
[this]() {
setWindowSize( mWindow->getSize() );
if( mCamera )
mCamera->setAspectRatio( mWindow->getAspectRatio() );
}
);
}
else
disconnect();
mLastAction = ACTION_NONE;
}
//! Disconnects all signal handlers
void CameraUi::disconnect()
{
mMouseDownConnection.disconnect();
mMouseUpConnection.disconnect();
mMouseDragConnection.disconnect();
mMouseWheelConnection.disconnect();
mWindowResizeConnection.disconnect();
mWindow.reset();
}
signals::Signal<void()>& CameraUi::getSignalCameraChange()
{
return mSignalCameraChange;
}
void CameraUi::mouseDown( app::MouseEvent &event )
{
mouseDown( event.getPos() );
event.setHandled();
}
void CameraUi::mouseUp( app::MouseEvent &event )
{
mouseUp( event.getPos() );
event.setHandled();
}
void CameraUi::mouseWheel( app::MouseEvent &event )
{
mouseWheel( event.getWheelIncrement() );
event.setHandled();
}
void CameraUi::mouseUp( const ivec2 &mousePos )
{
mLastAction = ACTION_NONE;
}
void CameraUi::mouseDown( const ivec2 &mousePos )
{
if( ! mCamera || ! mEnabled )
return;
mInitialMousePos = mousePos;
mInitialCam = *mCamera;
mInitialPivotDistance = mCamera->getPivotDistance();
mLastAction = ACTION_NONE;
}
void CameraUi::mouseDrag( app::MouseEvent &event )
{
bool isLeftDown = event.isLeftDown();
bool isMiddleDown = event.isMiddleDown() || event.isAltDown();
bool isRightDown = event.isRightDown() || event.isControlDown();
if( isMiddleDown )
isLeftDown = false;
mouseDrag( event.getPos(), isLeftDown, isMiddleDown, isRightDown );
event.setHandled();
}
void CameraUi::mouseDrag( const ivec2 &mousePos, bool leftDown, bool middleDown, bool rightDown )
{
if( ! mCamera || ! mEnabled )
return;
int action;
if( rightDown || ( leftDown && middleDown ) )
action = ACTION_ZOOM;
else if( middleDown )
action = ACTION_PAN;
else if( leftDown )
action = ACTION_TUMBLE;
else
return;
if( action != mLastAction ) {
mInitialCam = *mCamera;
mInitialPivotDistance = mCamera->getPivotDistance();
mInitialMousePos = mousePos;
}
mLastAction = action;
if( action == ACTION_ZOOM ) { // zooming
int mouseDelta = ( mousePos.x - mInitialMousePos.x ) + ( mousePos.y - mInitialMousePos.y );
float newPivotDistance = powf( 2.71828183f, 2 * -mouseDelta / length( vec2( getWindowSize() ) ) ) * mInitialPivotDistance;
vec3 oldTarget = mInitialCam.getEyePoint() + mInitialCam.getViewDirection() * mInitialPivotDistance;
vec3 newEye = oldTarget - mInitialCam.getViewDirection() * newPivotDistance;
mCamera->setEyePoint( newEye );
mCamera->setPivotDistance( std::max<float>( newPivotDistance, mMinimumPivotDistance ) );
}
else if( action == ACTION_PAN ) { // panning
float deltaX = ( mousePos.x - mInitialMousePos.x ) / (float)getWindowSize().x * mInitialPivotDistance;
float deltaY = ( mousePos.y - mInitialMousePos.y ) / (float)getWindowSize().y * mInitialPivotDistance;
vec3 right, up;
mInitialCam.getBillboardVectors( &right, &up );
mCamera->setEyePoint( mInitialCam.getEyePoint() - right * deltaX + up * deltaY );
}
else { // tumbling
float deltaX = ( mousePos.x - mInitialMousePos.x ) / -100.0f;
float deltaY = ( mousePos.y - mInitialMousePos.y ) / 100.0f;
vec3 mW = normalize( mInitialCam.getViewDirection() );
bool invertMotion = ( mInitialCam.getOrientation() * glm::vec3( 0, 1, 0 ) ).y < 0.0f;
vec3 mU = normalize( cross( vec3( 0, 1, 0 ), mW ) );
if( invertMotion ) {
deltaX = -deltaX;
deltaY = -deltaY;
}
glm::vec3 rotatedVec = glm::angleAxis( deltaY, mU ) * ( -mInitialCam.getViewDirection() * mInitialPivotDistance );
rotatedVec = glm::angleAxis( deltaX, glm::vec3( 0, 1, 0 ) ) * rotatedVec;
mCamera->setEyePoint( mInitialCam.getEyePoint() + mInitialCam.getViewDirection() * mInitialPivotDistance + rotatedVec );
mCamera->setOrientation( glm::angleAxis( deltaX, glm::vec3( 0, 1, 0 ) ) * glm::angleAxis( deltaY, mU ) * mInitialCam.getOrientation() );
}
mSignalCameraChange.emit();
}
void CameraUi::mouseWheel( float increment )
{
if( ! mCamera || ! mEnabled )
return;
// some mice issue mouseWheel events during middle-clicks; filter that out
if( mLastAction != ACTION_NONE )
return;
float multiplier;
if( mMouseWheelMultiplier > 0 )
multiplier = powf( mMouseWheelMultiplier, increment );
else
multiplier = powf( -mMouseWheelMultiplier, -increment );
vec3 newEye = mCamera->getEyePoint() + mCamera->getViewDirection() * ( mCamera->getPivotDistance() * ( 1 - multiplier ) );
mCamera->setEyePoint( newEye );
mCamera->setPivotDistance( std::max<float>( mCamera->getPivotDistance() * multiplier, mMinimumPivotDistance ) );
mSignalCameraChange.emit();
}
ivec2 CameraUi::getWindowSize() const
{
if( mWindow )
return mWindow->getSize();
else
return mWindowSize;
}
}; // namespace cinder
<commit_msg>CameraUi Tumble Orientation<commit_after>/*
Copyright (c) 2015, The Cinder Project: http://libcinder.org All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Portions of this code (C) Paul Houx
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.
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 "cinder/CameraUi.h"
namespace cinder {
CameraUi::CameraUi()
: mCamera( nullptr ), mWindowSize( 640, 480 ), mMouseWheelMultiplier( 1.2f ), mMinimumPivotDistance( 1.0f ),
mEnabled( true ), mLastAction( ACTION_NONE )
{}
CameraUi::CameraUi( CameraPersp *camera, const app::WindowRef &window, int signalPriority )
: mCamera( camera ), mWindowSize( 640, 480 ), mMouseWheelMultiplier( 1.2f ), mMinimumPivotDistance( 1.0f ),
mEnabled( true )
{
connect( window, signalPriority );
}
CameraUi::CameraUi( const CameraUi &rhs )
: mCamera( rhs.mCamera ), mWindowSize( rhs.mWindowSize ),
mWindow( rhs.mWindow ), mSignalPriority( rhs.mSignalPriority ),
mMouseWheelMultiplier( rhs.mMouseWheelMultiplier ), mMinimumPivotDistance( rhs.mMinimumPivotDistance ),
mEnabled( rhs.mEnabled )
{
connect( mWindow, mSignalPriority );
}
CameraUi::~CameraUi()
{
disconnect();
}
CameraUi& CameraUi::operator=( const CameraUi &rhs )
{
mCamera = rhs.mCamera;
mWindowSize = rhs.mWindowSize;
mMouseWheelMultiplier = rhs.mMouseWheelMultiplier;
mMinimumPivotDistance = rhs.mMinimumPivotDistance;
mWindow = rhs.mWindow;
mSignalPriority = rhs.mSignalPriority;
mEnabled = rhs.mEnabled;
connect( mWindow, mSignalPriority );
return *this;
}
//! Connects to mouseDown, mouseDrag, mouseWheel and resize signals of \a window, with optional priority \a signalPriority
void CameraUi::connect( const app::WindowRef &window, int signalPriority )
{
mWindow = window;
mSignalPriority = signalPriority;
if( window ) {
mMouseDownConnection = window->getSignalMouseDown().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseDown( event ); } );
mMouseUpConnection = window->getSignalMouseUp().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseUp( event ); } );
mMouseDragConnection = window->getSignalMouseDrag().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseDrag( event ); } );
mMouseWheelConnection = window->getSignalMouseWheel().connect( signalPriority,
[this]( app::MouseEvent &event ) { mouseWheel( event ); } );
mWindowResizeConnection = window->getSignalResize().connect( signalPriority,
[this]() {
setWindowSize( mWindow->getSize() );
if( mCamera )
mCamera->setAspectRatio( mWindow->getAspectRatio() );
}
);
}
else
disconnect();
mLastAction = ACTION_NONE;
}
//! Disconnects all signal handlers
void CameraUi::disconnect()
{
mMouseDownConnection.disconnect();
mMouseUpConnection.disconnect();
mMouseDragConnection.disconnect();
mMouseWheelConnection.disconnect();
mWindowResizeConnection.disconnect();
mWindow.reset();
}
signals::Signal<void()>& CameraUi::getSignalCameraChange()
{
return mSignalCameraChange;
}
void CameraUi::mouseDown( app::MouseEvent &event )
{
mouseDown( event.getPos() );
event.setHandled();
}
void CameraUi::mouseUp( app::MouseEvent &event )
{
mouseUp( event.getPos() );
event.setHandled();
}
void CameraUi::mouseWheel( app::MouseEvent &event )
{
mouseWheel( event.getWheelIncrement() );
event.setHandled();
}
void CameraUi::mouseUp( const ivec2 &mousePos )
{
mLastAction = ACTION_NONE;
}
void CameraUi::mouseDown( const ivec2 &mousePos )
{
if( ! mCamera || ! mEnabled )
return;
mInitialMousePos = mousePos;
mInitialCam = *mCamera;
mInitialPivotDistance = mCamera->getPivotDistance();
mLastAction = ACTION_NONE;
}
void CameraUi::mouseDrag( app::MouseEvent &event )
{
bool isLeftDown = event.isLeftDown();
bool isMiddleDown = event.isMiddleDown() || event.isAltDown();
bool isRightDown = event.isRightDown() || event.isControlDown();
if( isMiddleDown )
isLeftDown = false;
mouseDrag( event.getPos(), isLeftDown, isMiddleDown, isRightDown );
event.setHandled();
}
void CameraUi::mouseDrag( const ivec2 &mousePos, bool leftDown, bool middleDown, bool rightDown )
{
if( ! mCamera || ! mEnabled )
return;
int action;
if( rightDown || ( leftDown && middleDown ) )
action = ACTION_ZOOM;
else if( middleDown )
action = ACTION_PAN;
else if( leftDown )
action = ACTION_TUMBLE;
else
return;
if( action != mLastAction ) {
mInitialCam = *mCamera;
mInitialPivotDistance = mCamera->getPivotDistance();
mInitialMousePos = mousePos;
}
mLastAction = action;
if( action == ACTION_ZOOM ) { // zooming
int mouseDelta = ( mousePos.x - mInitialMousePos.x ) + ( mousePos.y - mInitialMousePos.y );
float newPivotDistance = powf( 2.71828183f, 2 * -mouseDelta / length( vec2( getWindowSize() ) ) ) * mInitialPivotDistance;
vec3 oldTarget = mInitialCam.getEyePoint() + mInitialCam.getViewDirection() * mInitialPivotDistance;
vec3 newEye = oldTarget - mInitialCam.getViewDirection() * newPivotDistance;
mCamera->setEyePoint( newEye );
mCamera->setPivotDistance( std::max<float>( newPivotDistance, mMinimumPivotDistance ) );
}
else if( action == ACTION_PAN ) { // panning
float deltaX = ( mousePos.x - mInitialMousePos.x ) / (float)getWindowSize().x * mInitialPivotDistance;
float deltaY = ( mousePos.y - mInitialMousePos.y ) / (float)getWindowSize().y * mInitialPivotDistance;
vec3 right, up;
mInitialCam.getBillboardVectors( &right, &up );
mCamera->setEyePoint( mInitialCam.getEyePoint() - right * deltaX + up * deltaY );
}
else { // tumbling
float deltaX = ( mousePos.x - mInitialMousePos.x ) / -100.0f;
float deltaY = ( mousePos.y - mInitialMousePos.y ) / 100.0f;
vec3 mW = normalize( mInitialCam.getViewDirection() );
bool invertMotion = glm::length(mInitialCam.getOrientation() * mInitialCam.getWorldUp()) < 0.0f;
vec3 mU = normalize(cross(mInitialCam.getWorldUp(), mW));
if( invertMotion ) {
deltaX = -deltaX;
deltaY = -deltaY;
}
glm::vec3 rotatedVec = glm::angleAxis( deltaY, mU ) * ( -mInitialCam.getViewDirection() * mInitialPivotDistance );
rotatedVec = glm::angleAxis(deltaX, mInitialCam.getWorldUp()) * rotatedVec;
mCamera->setEyePoint( mInitialCam.getEyePoint() + mInitialCam.getViewDirection() * mInitialPivotDistance + rotatedVec );
mCamera->setOrientation(glm::angleAxis(deltaX, mInitialCam.getWorldUp()) * glm::angleAxis(deltaY, mU) * mInitialCam.getOrientation());
}
mSignalCameraChange.emit();
}
void CameraUi::mouseWheel( float increment )
{
if( ! mCamera || ! mEnabled )
return;
// some mice issue mouseWheel events during middle-clicks; filter that out
if( mLastAction != ACTION_NONE )
return;
float multiplier;
if( mMouseWheelMultiplier > 0 )
multiplier = powf( mMouseWheelMultiplier, increment );
else
multiplier = powf( -mMouseWheelMultiplier, -increment );
vec3 newEye = mCamera->getEyePoint() + mCamera->getViewDirection() * ( mCamera->getPivotDistance() * ( 1 - multiplier ) );
mCamera->setEyePoint( newEye );
mCamera->setPivotDistance( std::max<float>( mCamera->getPivotDistance() * multiplier, mMinimumPivotDistance ) );
mSignalCameraChange.emit();
}
ivec2 CameraUi::getWindowSize() const
{
if( mWindow )
return mWindow->getSize();
else
return mWindowSize;
}
}; // namespace cinder
<|endoftext|>
|
<commit_before>#ifndef ITERATOR_ITERATOR_HPP_
#define ITERATOR_ITERATOR_HPP_
#include <iterator>
#include <type_traits>
#include <utility>
#include "iterbase.hpp"
// IterIterWrapper and IteratorIterator provide a means to have a container
// of iterators act like a container of the pointed to objects. This is useful
// for combinatorics and similar itertools which need to keep track of
// more than one element at a time.
// an IterIterWrapper<some_collection_type<collection<T>::iterator>>
// behave like some_collection<T> when iterated over or indexed
namespace iter {
namespace impl {
template <typename T, typename = void>
struct HasConstDeref : std::false_type {};
template <typename T>
struct HasConstDeref<T, void_t<decltype(*std::declval<const T&>())>>
: std::true_type {};
template <typename TopIter>
class IteratorIterator
: public std::iterator<std::random_access_iterator_tag,
typename std::remove_reference<decltype(
**std::declval<TopIter>())>::type> {
using Diff = std::ptrdiff_t;
static_assert(
std::is_same<
typename std::iterator_traits<TopIter>::iterator_category,
std::random_access_iterator_tag>::value,
"IteratorIterator only works with random access iterators");
private:
TopIter sub_iter;
public:
IteratorIterator() = default;
IteratorIterator(const TopIter& it) : sub_iter{it} {}
bool operator==(const IteratorIterator& other) const {
return !(*this != other);
}
bool operator!=(const IteratorIterator& other) const {
return this->sub_iter != other.sub_iter;
}
IteratorIterator& operator++() {
++this->sub_iter;
return *this;
}
IteratorIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
IteratorIterator& operator--() {
--this->sub_iter;
return *this;
}
IteratorIterator operator--(int) {
auto ret = *this;
--*this;
return ret;
}
auto operator*() -> decltype(**sub_iter) {
return **this->sub_iter;
}
auto operator-> () -> decltype(*sub_iter) {
return *this->sub_iter;
}
IteratorIterator& operator+=(Diff n) {
this->sub_iter += n;
return *this;
}
IteratorIterator operator+(Diff n) const {
auto it = *this;
it += n;
return it;
}
friend IteratorIterator operator+(Diff n, IteratorIterator it) {
it += n;
return it;
}
IteratorIterator& operator-=(Diff n) {
this->sub_iter -= n;
return *this;
}
IteratorIterator operator-(Diff n) const {
auto it = *this;
it -= n;
return it;
}
friend IteratorIterator operator-(Diff n, IteratorIterator it) {
it -= n;
return it;
}
Diff operator-(const IteratorIterator& rhs) const {
return this->sub_iter - rhs.sub_iter;
}
auto operator[](Diff idx) -> decltype(*sub_iter[idx]) {
return *sub_iter[idx];
}
bool operator<(const IteratorIterator& rhs) const {
return this->sub_iter < rhs.sub_iter;
}
bool operator>(const IteratorIterator& rhs) const {
return this->sub_iter > rhs.sub_iter;
}
bool operator<=(const IteratorIterator& rhs) const {
return this->sub_iter <= rhs.sub_iter;
}
bool operator>=(const IteratorIterator& rhs) const {
return this->sub_iter >= rhs.sub_iter;
}
};
template <typename Container>
class IterIterWrapper {
private:
Container container;
using contained_iter = typename Container::value_type;
using size_type = typename Container::size_type;
using iterator = IteratorIterator<typename Container::iterator>;
using const_iterator =
IteratorIterator<typename Container::const_iterator>;
using reverse_iterator =
IteratorIterator<typename Container::reverse_iterator>;
using const_reverse_iterator =
IteratorIterator<typename Container::const_reverse_iterator>;
template <typename U = Container, typename = void>
struct ConstAtTypeOrVoid : type_is<void> {};
template <typename U>
struct ConstAtTypeOrVoid<U,
void_t<decltype(*std::declval<const U&>().at(0))>>
: type_is<decltype(*std::declval<const U&>().at(0))> {};
using const_at_type_or_void_t = typename ConstAtTypeOrVoid<>::type;
template <typename U = Container, typename = void>
struct ConstIndexTypeOrVoid : type_is<void> {};
template <typename U>
struct ConstIndexTypeOrVoid<U,
void_t<decltype(*std::declval<const U&>()[0])>>
: type_is<decltype(*std::declval<const U&>()[0])> {};
using const_index_type_or_void_t = typename ConstIndexTypeOrVoid<>::type;
public:
IterIterWrapper() = default;
explicit IterIterWrapper(size_type sz) : container(sz) {}
IterIterWrapper(size_type sz, const contained_iter& val)
: container(sz, val) {}
auto at(size_type pos) -> decltype(*container.at(pos)) {
return *container.at(pos);
}
auto at(size_type pos) const -> const_at_type_or_void_t {
return *container.at(pos);
}
auto operator[](size_type pos) noexcept(noexcept(*container[pos]))
-> decltype(*container[pos]) {
return *container[pos];
}
auto operator[](size_type pos) const noexcept(noexcept(*container[pos]))
-> const_index_type_or_void_t {
return *container[pos];
}
bool empty() const noexcept {
return container.empty();
}
size_type size() const noexcept {
return container.size();
}
iterator begin() noexcept {
return {container.begin()};
}
iterator end() noexcept {
return {container.end()};
}
const_iterator begin() const noexcept {
return {container.begin()};
}
const_iterator end() const noexcept {
return {container.end()};
}
const_iterator cbegin() const noexcept {
return {container.cbegin()};
}
const_iterator cend() const noexcept {
return {container.cend()};
}
reverse_iterator rbegin() noexcept {
return {container.rbegin()};
}
reverse_iterator rend() noexcept {
return {container.rend()};
}
const_reverse_iterator rbegin() const noexcept {
return {container.rbegin()};
}
const_reverse_iterator rend() const noexcept {
return {container.rend()};
}
const_reverse_iterator crbegin() const noexcept {
return {container.rbegin()};
}
const_reverse_iterator crend() const noexcept {
return {container.rend()};
}
// get() exposes the underlying container. this allows the
// itertools to manipulate the iterators in the container
// and should not be depended on anywhere else.
Container& get() noexcept {
return container;
}
const Container& get() const noexcept {
return container;
}
};
}
}
#endif
<commit_msg>Makes IteratorIterators comparable to each other<commit_after>#ifndef ITERATOR_ITERATOR_HPP_
#define ITERATOR_ITERATOR_HPP_
#include <iterator>
#include <type_traits>
#include <utility>
#include "iterbase.hpp"
// IterIterWrapper and IteratorIterator provide a means to have a container
// of iterators act like a container of the pointed to objects. This is useful
// for combinatorics and similar itertools which need to keep track of
// more than one element at a time.
// an IterIterWrapper<some_collection_type<collection<T>::iterator>>
// behave like some_collection<T> when iterated over or indexed
namespace iter {
namespace impl {
template <typename T, typename = void>
struct HasConstDeref : std::false_type {};
template <typename T>
struct HasConstDeref<T, void_t<decltype(*std::declval<const T&>())>>
: std::true_type {};
template <typename TopIter>
class IteratorIterator
: public std::iterator<std::random_access_iterator_tag,
typename std::remove_reference<decltype(
**std::declval<TopIter>())>::type> {
template <typename> friend class IteratorIterator;
using Diff = std::ptrdiff_t;
static_assert(
std::is_same<
typename std::iterator_traits<TopIter>::iterator_category,
std::random_access_iterator_tag>::value,
"IteratorIterator only works with random access iterators");
private:
TopIter sub_iter;
public:
IteratorIterator() = default;
IteratorIterator(const TopIter& it) : sub_iter{it} {}
const TopIter& get() const {
return sub_iter;
}
template <typename T>
bool operator==(const IteratorIterator<T>& other) const {
return !(*this != other);
}
template <typename T>
bool operator!=(const IteratorIterator<T>& other) const {
return this->sub_iter != other.sub_iter;
}
IteratorIterator& operator++() {
++this->sub_iter;
return *this;
}
IteratorIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
IteratorIterator& operator--() {
--this->sub_iter;
return *this;
}
IteratorIterator operator--(int) {
auto ret = *this;
--*this;
return ret;
}
auto operator*() -> decltype(**sub_iter) {
return **this->sub_iter;
}
auto operator-> () -> decltype(*sub_iter) {
return *this->sub_iter;
}
IteratorIterator& operator+=(Diff n) {
this->sub_iter += n;
return *this;
}
IteratorIterator operator+(Diff n) const {
auto it = *this;
it += n;
return it;
}
friend IteratorIterator operator+(Diff n, IteratorIterator it) {
it += n;
return it;
}
IteratorIterator& operator-=(Diff n) {
this->sub_iter -= n;
return *this;
}
IteratorIterator operator-(Diff n) const {
auto it = *this;
it -= n;
return it;
}
friend IteratorIterator operator-(Diff n, IteratorIterator it) {
it -= n;
return it;
}
Diff operator-(const IteratorIterator& rhs) const {
return this->sub_iter - rhs.sub_iter;
}
auto operator[](Diff idx) -> decltype(*sub_iter[idx]) {
return *sub_iter[idx];
}
bool operator<(const IteratorIterator& rhs) const {
return this->sub_iter < rhs.sub_iter;
}
bool operator>(const IteratorIterator& rhs) const {
return this->sub_iter > rhs.sub_iter;
}
bool operator<=(const IteratorIterator& rhs) const {
return this->sub_iter <= rhs.sub_iter;
}
bool operator>=(const IteratorIterator& rhs) const {
return this->sub_iter >= rhs.sub_iter;
}
};
template <typename Container>
class IterIterWrapper {
private:
Container container;
using contained_iter = typename Container::value_type;
using size_type = typename Container::size_type;
using iterator = IteratorIterator<typename Container::iterator>;
using const_iterator =
IteratorIterator<typename Container::const_iterator>;
using reverse_iterator =
IteratorIterator<typename Container::reverse_iterator>;
using const_reverse_iterator =
IteratorIterator<typename Container::const_reverse_iterator>;
template <typename U = Container, typename = void>
struct ConstAtTypeOrVoid : type_is<void> {};
template <typename U>
struct ConstAtTypeOrVoid<U,
void_t<decltype(*std::declval<const U&>().at(0))>>
: type_is<decltype(*std::declval<const U&>().at(0))> {};
using const_at_type_or_void_t = typename ConstAtTypeOrVoid<>::type;
template <typename U = Container, typename = void>
struct ConstIndexTypeOrVoid : type_is<void> {};
template <typename U>
struct ConstIndexTypeOrVoid<U,
void_t<decltype(*std::declval<const U&>()[0])>>
: type_is<decltype(*std::declval<const U&>()[0])> {};
using const_index_type_or_void_t = typename ConstIndexTypeOrVoid<>::type;
public:
IterIterWrapper() = default;
explicit IterIterWrapper(size_type sz) : container(sz) {}
IterIterWrapper(size_type sz, const contained_iter& val)
: container(sz, val) {}
auto at(size_type pos) -> decltype(*container.at(pos)) {
return *container.at(pos);
}
auto at(size_type pos) const -> const_at_type_or_void_t {
return *container.at(pos);
}
auto operator[](size_type pos) noexcept(noexcept(*container[pos]))
-> decltype(*container[pos]) {
return *container[pos];
}
auto operator[](size_type pos) const noexcept(noexcept(*container[pos]))
-> const_index_type_or_void_t {
return *container[pos];
}
bool empty() const noexcept {
return container.empty();
}
size_type size() const noexcept {
return container.size();
}
iterator begin() noexcept {
return {container.begin()};
}
iterator end() noexcept {
return {container.end()};
}
const_iterator begin() const noexcept {
return {container.begin()};
}
const_iterator end() const noexcept {
return {container.end()};
}
const_iterator cbegin() const noexcept {
return {container.cbegin()};
}
const_iterator cend() const noexcept {
return {container.cend()};
}
reverse_iterator rbegin() noexcept {
return {container.rbegin()};
}
reverse_iterator rend() noexcept {
return {container.rend()};
}
const_reverse_iterator rbegin() const noexcept {
return {container.rbegin()};
}
const_reverse_iterator rend() const noexcept {
return {container.rend()};
}
const_reverse_iterator crbegin() const noexcept {
return {container.rbegin()};
}
const_reverse_iterator crend() const noexcept {
return {container.rend()};
}
// get() exposes the underlying container. this allows the
// itertools to manipulate the iterators in the container
// and should not be depended on anywhere else.
Container& get() noexcept {
return container;
}
const Container& get() const noexcept {
return container;
}
};
}
}
#endif
<|endoftext|>
|
<commit_before>// @(#) $Id: AliHLTTPCCATracker.cxx 34611 2009-09-04 00:22:05Z sgorbuno $
// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: Sergey Gorbunov <sergey.gorbunov@kip.uni-heidelberg.de> *
// Ivan Kisel <kisel@kip.uni-heidelberg.de> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
#include "AliHLTTPCCADef.h"
#include "AliHLTTPCCAGPUConfig.h"
#include "AliHLTTPCCATrackerFramework.h"
#include "AliHLTTPCCAGPUTracker.h"
#include "AliHLTTPCCATracker.h"
#include "AliHLTTPCCAMath.h"
#include "AliHLTTPCCAClusterData.h"
#include <windows.h>
#include <winbase.h>
#ifdef HLTCA_STANDALONE
#include <omp.h>
#endif
int AliHLTTPCCATrackerFramework::InitGPU(int sliceCount, int forceDeviceID)
{
//Initialize GPU Tracker and determine if GPU available
int retVal;
if (!fGPULibAvailable)
{
printf("GPU Library not loaded\n");
return(1);
}
if (fGPUTrackerAvailable && (retVal = ExitGPU())) return(retVal);
retVal = fGPUTracker->InitGPU(sliceCount, forceDeviceID);
fUseGPUTracker = fGPUTrackerAvailable = retVal == 0;
fGPUSliceCount = sliceCount;
return(retVal);
}
int AliHLTTPCCATrackerFramework::ExitGPU()
{
//Uninitialize GPU Tracker
if (!fGPUTrackerAvailable) return(0);
fUseGPUTracker = false;
fGPUTrackerAvailable = false;
return(fGPUTracker->ExitGPU());
}
void AliHLTTPCCATrackerFramework::SetGPUDebugLevel(int Level, std::ostream *OutFile, std::ostream *GPUOutFile)
{
//Set Debug Level for GPU Tracker and also for CPU Tracker for comparison reasons
fGPUTracker->SetDebugLevel(Level, GPUOutFile);
fGPUDebugLevel = Level;
for (int i = 0;i < fgkNSlices;i++)
{
fCPUTrackers[i].SetGPUDebugLevel(Level, OutFile);
}
}
int AliHLTTPCCATrackerFramework::SetGPUTracker(bool enable)
{
//Enable / disable GPU Tracker
if (enable && !fGPUTrackerAvailable)
{
fUseGPUTracker = false;
return(1);
}
fUseGPUTracker = enable;
return(0);
}
GPUhd() void AliHLTTPCCATrackerFramework::SetOutputControl( AliHLTTPCCASliceOutput::outputControlStruct* val)
{
//Set Output Control Pointers
fOutputControl = val;
fGPUTracker->SetOutputControl(val);
for (int i = 0;i < fgkNSlices;i++)
{
fCPUTrackers[i].SetOutputControl(val);
}
}
int AliHLTTPCCATrackerFramework::ProcessSlices(int firstSlice, int sliceCount, AliHLTTPCCAClusterData* pClusterData, AliHLTTPCCASliceOutput** pOutput)
{
//Process sliceCount slices starting from firstslice, in is pClusterData array, out pOutput array
if (fUseGPUTracker)
{
if (fGPUTracker->Reconstruct(pOutput, pClusterData, firstSlice, CAMath::Min(sliceCount, fgkNSlices - firstSlice))) return(1);
}
else
{
#ifdef HLTCA_STANDALONE
if (fOutputControl->fOutputPtr && omp_get_max_threads() > 1)
{
printf("fOutputPtr must not be used with OpenMP\n");
return(1);
}
#pragma omp parallel for
#endif
for (int iSlice = 0;iSlice < CAMath::Min(sliceCount, fgkNSlices - firstSlice);iSlice++)
{
fCPUTrackers[firstSlice + iSlice].ReadEvent(&pClusterData[iSlice]);
fCPUTrackers[firstSlice + iSlice].SetOutput(&pOutput[iSlice]);
fCPUTrackers[firstSlice + iSlice].Reconstruct();
fCPUTrackers[firstSlice + iSlice].SetupCommonMemory();
}
}
if (fGPUDebugLevel >= 6 && fUseGPUTracker)
{
fUseGPUTracker = 0;
ProcessSlices(firstSlice, sliceCount, pClusterData, pOutput);
fUseGPUTracker = 1;
}
//printf("Slice Tracks Output: %d\n", pOutput[0].NTracks());
return(0);
}
unsigned long long int* AliHLTTPCCATrackerFramework::PerfTimer(int GPU, int iSlice, int iTimer)
{
//Performance information for slice trackers
return(GPU ? fGPUTracker->PerfTimer(iSlice, iTimer) : fCPUTrackers[iSlice].PerfTimer(iTimer));
}
int AliHLTTPCCATrackerFramework::InitializeSliceParam(int iSlice, AliHLTTPCCAParam ¶m)
{
//Initialize Tracker Parameters for a slice
if (fGPUTrackerAvailable && fGPUTracker->InitializeSliceParam(iSlice, param)) return(1);
fCPUTrackers[iSlice].Initialize(param);
return(0);
}
AliHLTTPCCATrackerFramework::AliHLTTPCCATrackerFramework(int allowGPU) : fGPULibAvailable(false), fGPUTrackerAvailable(false), fUseGPUTracker(false), fGPUDebugLevel(0), fGPUSliceCount(0), fGPUTracker(NULL), fGPULib(NULL), fOutputControl( NULL ), fCPUSliceCount(fgkNSlices)
{
//Constructor
HMODULE hGPULib = LoadLibraryEx("cagpu.dll", NULL, NULL);
if (hGPULib == NULL)
{
printf("Error Opening cagpu library\n");
fGPUTracker = new AliHLTTPCCAGPUTracker;
}
else
{
FARPROC createFunc = GetProcAddress(hGPULib, "AliHLTTPCCAGPUTrackerNVCCCreate");
if (createFunc == NULL)
{
printf("Error Creating GPU Tracker\n");
FreeLibrary(hGPULib);
fGPUTracker = new AliHLTTPCCAGPUTracker;
}
else
{
AliHLTTPCCAGPUTracker* (*tmp)() = (AliHLTTPCCAGPUTracker* (*)()) createFunc;
fGPUTracker = tmp();
fGPULibAvailable = true;
fGPULib = (void*) (size_t) hGPULib;
}
}
if (allowGPU && fGPULibAvailable)
{
fUseGPUTracker = (fGPUTrackerAvailable= (fGPUTracker->InitGPU() == 0));
fGPUSliceCount = fGPUTrackerAvailable ? fGPUTracker->GetSliceCount() : 0;
}
}
AliHLTTPCCATrackerFramework::~AliHLTTPCCATrackerFramework()
{
HMODULE hGPULib = (HMODULE) (size_t) fGPULib;
if (fGPULib)
{
if (fGPUTracker)
{
FARPROC destroyFunc = GetProcAddress(hGPULib, "AliHLTTPCCAGPUTrackerNVCCDestroy");
if (destroyFunc == NULL) printf("Error Freeing GPU Tracker\n");
else
{
void (*tmp)(AliHLTTPCCAGPUTracker*) = (void (*)(AliHLTTPCCAGPUTracker*)) destroyFunc;
tmp(fGPUTracker);
}
}
FreeLibrary(hGPULib);
}
else if (fGPUTracker)
{
delete fGPUTracker;
}
fGPULib = NULL;
fGPUTracker = NULL;
}
<commit_msg>added linux support for lib<commit_after>// @(#) $Id: AliHLTTPCCATracker.cxx 34611 2009-09-04 00:22:05Z sgorbuno $
// **************************************************************************
// This file is property of and copyright by the ALICE HLT Project *
// ALICE Experiment at CERN, All rights reserved. *
// *
// Primary Authors: Sergey Gorbunov <sergey.gorbunov@kip.uni-heidelberg.de> *
// Ivan Kisel <kisel@kip.uni-heidelberg.de> *
// for The ALICE HLT Project. *
// *
// Permission to use, copy, modify and distribute this software and its *
// documentation strictly for non-commercial purposes is hereby granted *
// without fee, provided that the above copyright notice appears in all *
// copies and that both the copyright notice and this permission notice *
// appear in the supporting documentation. The authors make no claims *
// about the suitability of this software for any purpose. It is *
// provided "as is" without express or implied warranty. *
// *
//***************************************************************************
#include "AliHLTTPCCADef.h"
#include "AliHLTTPCCAGPUConfig.h"
#include "AliHLTTPCCATrackerFramework.h"
#include "AliHLTTPCCAGPUTracker.h"
#include "AliHLTTPCCATracker.h"
#include "AliHLTTPCCAMath.h"
#include "AliHLTTPCCAClusterData.h"
#ifdef R__WIN32
#include <windows.h>
#include <winbase.h>
#else
#include <dlfcn.h>
#endif
#ifdef HLTCA_STANDALONE
#include <omp.h>
#endif
int AliHLTTPCCATrackerFramework::InitGPU(int sliceCount, int forceDeviceID)
{
//Initialize GPU Tracker and determine if GPU available
int retVal;
if (!fGPULibAvailable)
{
printf("GPU Library not loaded\n");
return(1);
}
if (fGPUTrackerAvailable && (retVal = ExitGPU())) return(retVal);
retVal = fGPUTracker->InitGPU(sliceCount, forceDeviceID);
fUseGPUTracker = fGPUTrackerAvailable = retVal == 0;
fGPUSliceCount = sliceCount;
return(retVal);
}
int AliHLTTPCCATrackerFramework::ExitGPU()
{
//Uninitialize GPU Tracker
if (!fGPUTrackerAvailable) return(0);
fUseGPUTracker = false;
fGPUTrackerAvailable = false;
return(fGPUTracker->ExitGPU());
}
void AliHLTTPCCATrackerFramework::SetGPUDebugLevel(int Level, std::ostream *OutFile, std::ostream *GPUOutFile)
{
//Set Debug Level for GPU Tracker and also for CPU Tracker for comparison reasons
fGPUTracker->SetDebugLevel(Level, GPUOutFile);
fGPUDebugLevel = Level;
for (int i = 0;i < fgkNSlices;i++)
{
fCPUTrackers[i].SetGPUDebugLevel(Level, OutFile);
}
}
int AliHLTTPCCATrackerFramework::SetGPUTracker(bool enable)
{
//Enable / disable GPU Tracker
if (enable && !fGPUTrackerAvailable)
{
fUseGPUTracker = false;
return(1);
}
fUseGPUTracker = enable;
return(0);
}
GPUhd() void AliHLTTPCCATrackerFramework::SetOutputControl( AliHLTTPCCASliceOutput::outputControlStruct* val)
{
//Set Output Control Pointers
fOutputControl = val;
fGPUTracker->SetOutputControl(val);
for (int i = 0;i < fgkNSlices;i++)
{
fCPUTrackers[i].SetOutputControl(val);
}
}
int AliHLTTPCCATrackerFramework::ProcessSlices(int firstSlice, int sliceCount, AliHLTTPCCAClusterData* pClusterData, AliHLTTPCCASliceOutput** pOutput)
{
//Process sliceCount slices starting from firstslice, in is pClusterData array, out pOutput array
if (fUseGPUTracker)
{
if (fGPUTracker->Reconstruct(pOutput, pClusterData, firstSlice, CAMath::Min(sliceCount, fgkNSlices - firstSlice))) return(1);
}
else
{
#ifdef HLTCA_STANDALONE
if (fOutputControl->fOutputPtr && omp_get_max_threads() > 1)
{
printf("fOutputPtr must not be used with OpenMP\n");
return(1);
}
#pragma omp parallel for
#endif
for (int iSlice = 0;iSlice < CAMath::Min(sliceCount, fgkNSlices - firstSlice);iSlice++)
{
fCPUTrackers[firstSlice + iSlice].ReadEvent(&pClusterData[iSlice]);
fCPUTrackers[firstSlice + iSlice].SetOutput(&pOutput[iSlice]);
fCPUTrackers[firstSlice + iSlice].Reconstruct();
fCPUTrackers[firstSlice + iSlice].SetupCommonMemory();
}
}
if (fGPUDebugLevel >= 6 && fUseGPUTracker)
{
fUseGPUTracker = 0;
ProcessSlices(firstSlice, sliceCount, pClusterData, pOutput);
fUseGPUTracker = 1;
}
//printf("Slice Tracks Output: %d\n", pOutput[0].NTracks());
return(0);
}
unsigned long long int* AliHLTTPCCATrackerFramework::PerfTimer(int GPU, int iSlice, int iTimer)
{
//Performance information for slice trackers
return(GPU ? fGPUTracker->PerfTimer(iSlice, iTimer) : fCPUTrackers[iSlice].PerfTimer(iTimer));
}
int AliHLTTPCCATrackerFramework::InitializeSliceParam(int iSlice, AliHLTTPCCAParam ¶m)
{
//Initialize Tracker Parameters for a slice
if (fGPUTrackerAvailable && fGPUTracker->InitializeSliceParam(iSlice, param)) return(1);
fCPUTrackers[iSlice].Initialize(param);
return(0);
}
AliHLTTPCCATrackerFramework::AliHLTTPCCATrackerFramework(int allowGPU) : fGPULibAvailable(false), fGPUTrackerAvailable(false), fUseGPUTracker(false), fGPUDebugLevel(0), fGPUSliceCount(0), fGPUTracker(NULL), fGPULib(NULL), fOutputControl( NULL ), fCPUSliceCount(fgkNSlices)
{
//Constructor
#ifdef R__WIN32
HMODULE hGPULib = LoadLibraryEx("cagpu.dll", NULL, NULL);
#else
void* hGPULib = dlopen("cagpu.so", RTLD_NOW);
#endif
if (hGPULib == NULL)
{
printf("Error Opening cagpu library\n");
fGPUTracker = new AliHLTTPCCAGPUTracker;
}
else
{
#ifdef R__WIN32
FARPROC createFunc = GetProcAddress(hGPULib, "AliHLTTPCCAGPUTrackerNVCCCreate");
#else
void* createFunc = (void*) dlsym(hGPULib, "AliHLTTPCCAGPUTrackerNVCCCreate");
#endif
if (createFunc == NULL)
{
printf("Error Creating GPU Tracker\n");
#ifdef R__WIN32
FreeLibrary(hGPULib);
#else
dlclose(hGPULib);
#endif
fGPUTracker = new AliHLTTPCCAGPUTracker;
}
else
{
AliHLTTPCCAGPUTracker* (*tmp)() = (AliHLTTPCCAGPUTracker* (*)()) createFunc;
fGPUTracker = tmp();
fGPULibAvailable = true;
fGPULib = (void*) (size_t) hGPULib;
}
}
if (allowGPU && fGPULibAvailable)
{
fUseGPUTracker = (fGPUTrackerAvailable= (fGPUTracker->InitGPU() == 0));
fGPUSliceCount = fGPUTrackerAvailable ? fGPUTracker->GetSliceCount() : 0;
}
}
AliHLTTPCCATrackerFramework::~AliHLTTPCCATrackerFramework()
{
#ifdef R__WIN32
HMODULE hGPULib = (HMODULE) (size_t) fGPULib;
#else
void* hGPULib = fGPULib;
#endif
if (fGPULib)
{
if (fGPUTracker)
{
#ifdef R__WIN32
FARPROC destroyFunc = GetProcAddress(hGPULib, "AliHLTTPCCAGPUTrackerNVCCDestroy");
#else
void* destroyFunc = (void*) dlsym(hGPULib, "AliHLTTPCCAGPUTrackerNVCCDestroy");
#endif
if (destroyFunc == NULL) printf("Error Freeing GPU Tracker\n");
else
{
void (*tmp)(AliHLTTPCCAGPUTracker*) = (void (*)(AliHLTTPCCAGPUTracker*)) destroyFunc;
tmp(fGPUTracker);
}
}
#ifdef R__WIN32
FreeLibrary(hGPULib);
#else
dlclose(hGPULib);
#endif
}
else if (fGPUTracker)
{
delete fGPUTracker;
}
fGPULib = NULL;
fGPUTracker = NULL;
}
<|endoftext|>
|
<commit_before>#include <boost/locale.hpp>
#include <locale>
#include <iostream>
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
int main(int argc, char *argv[])
{
// Create string with one weird (ñ) char
char iso[] = {'L', 'a', ' ', 'P', 'e', 0xF1, 'a', 0};
// Use latin1 to convert string to UTF8
std::string utf8 = boost::locale::conv::to_utf<char>(iso, "Latin1");
std::cout << "The UTF8 string is: " << utf8 << std::endl;
std::cout << "The Latin1 string is: " << iso << std::endl;
return 0;
}
<commit_msg>Example: fix c++11 error<commit_after>#include <boost/locale.hpp>
#include <locale>
#include <iostream>
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
int main(int argc, char *argv[])
{
// Create string with one weird (ñ) char
char iso[] = "La Pe\361a";
// Use latin1 to convert string to UTF8
std::string utf8 = boost::locale::conv::to_utf<char>(iso, "Latin1");
std::cout << "The UTF8 string is: " << utf8 << std::endl;
std::cout << "The Latin1 string is: " << iso << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: */
// Macro to generate ad hoc GMS alignment matrices in the agreed format:
// TClonesArray saved in the Root file with a key "GMSarray"
// containing TGeoHMatrix with TObject::fUniqueID equal to the geometry
// module Id
//
// By I. Hrivnacova, IPN Orsay
#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliMpConstants.h"
#endif
MUONGenerateTestGMS()
{
TFile f("data/GMS.root", "RECREATE");
TClonesArray* array = new TClonesArray("TGeoHMatrix",100);
for (Int_t i=0; i<AliMpConstants::NofGeomModules(); i++) {
TGeoHMatrix* m = new((*array)[i]) TGeoHMatrix();
m->SetUniqueID(i);
/// rotate by small angle
m->RotateX(i*0.01);
}
gFile->WriteObject(array,"GMSarray");
f.Close();
}
<commit_msg>Replaced use of global gFile with the local file.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: */
// Macro to generate ad hoc GMS alignment matrices in the agreed format:
// TClonesArray saved in the Root file with a key "GMSarray"
// containing TGeoHMatrix with TObject::fUniqueID equal to the geometry
// module Id
//
// By I. Hrivnacova, IPN Orsay
#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliMpConstants.h"
#endif
MUONGenerateTestGMS()
{
TFile f("data/GMS.root", "RECREATE");
TClonesArray* array = new TClonesArray("TGeoHMatrix",100);
for (Int_t i=0; i<AliMpConstants::NofGeomModules(); i++) {
TGeoHMatrix* m = new((*array)[i]) TGeoHMatrix();
m->SetUniqueID(i);
/// rotate by small angle
m->RotateX(i*0.01);
}
f.WriteObject(array,"GMSarray");
f.Close();
}
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/benchmark/benchmark_performance_options.h"
#include <algorithm>
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include "tensorflow/core/util/stats_calculator.h"
#include "tensorflow/lite/c/c_api_internal.h"
#if defined(__ANDROID__)
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/nnapi/nnapi_util.h"
#endif
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/benchmark/benchmark_params.h"
#include "tensorflow/lite/tools/benchmark/benchmark_utils.h"
#include "tensorflow/lite/tools/benchmark/logging.h"
#include "tensorflow/lite/tools/command_line_flags.h"
namespace tflite {
namespace benchmark {
void MultiRunStatsRecorder::OnBenchmarkStart(const BenchmarkParams& params) {
current_run_name_.clear();
#if defined(__ANDROID__)
if (params.Get<bool>("use_nnapi")) {
current_run_name_ = "nnapi";
const std::string accelerator =
params.Get<std::string>("nnapi_accelerator_name");
if (!accelerator.empty()) {
current_run_name_ = "nnapi(" + accelerator + ")";
}
return;
}
#endif
if (params.Get<bool>("use_gpu")) {
#if defined(__ANDROID__)
const bool allow_precision_loss =
params.Get<bool>("gpu_precision_loss_allowed");
const std::string precision_tag = allow_precision_loss ? "fp16" : "fp32";
current_run_name_ = "gpu(" + precision_tag + ")";
const auto default_opts = TfLiteGpuDelegateOptionsV2Default();
if (default_opts.is_precision_loss_allowed == allow_precision_loss) {
current_run_name_ += "-default";
}
#else
current_run_name_ = "gpu-default";
#endif
return;
}
// Handle cases run on CPU
// Note: could use std::to_string to convert an integer to string but it
// requires C++11.
std::stringstream sstm;
sstm << "cpu w/ " << params.Get<int32_t>("num_threads") << " threads";
current_run_name_ = sstm.str();
}
void MultiRunStatsRecorder::OnBenchmarkEnd(const BenchmarkResults& results) {
each_run_stats_.emplace_back(std::make_pair(current_run_name_, results));
}
void MultiRunStatsRecorder::OutputStats() {
// Make a 80-character-long header.
TFLITE_LOG(INFO) << "\n==============Summary of All Runs w/ Different "
"Performance Options==============";
std::sort(each_run_stats_.begin(), each_run_stats_.end(),
EachRunStatsEntryComparator());
for (const auto& run_stats : each_run_stats_) {
std::stringstream stream;
// Output the name of this run first.
stream << std::setw(26) << run_stats.first << ": ";
run_stats.second.inference_time_us().OutputToStream(&stream);
TFLITE_LOG(INFO) << stream.str();
}
}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkModel* single_option_run)
: BenchmarkPerformanceOptions(DefaultParams(), single_option_run,
DefaultRunStatsRecorder()) {}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkParams params, BenchmarkModel* single_option_run,
std::unique_ptr<MultiRunStatsRecorder> all_run_stats)
: params_(std::move(params)),
single_option_run_(single_option_run),
single_option_run_params_(single_option_run->mutable_params()),
all_run_stats_(std::move(all_run_stats)) {
single_option_run_->AddListener(all_run_stats_.get());
}
BenchmarkParams BenchmarkPerformanceOptions::DefaultParams() {
BenchmarkParams params;
params.AddParam("perf_options_list",
BenchmarkParam::Create<std::string>("all"));
params.AddParam("option_benchmark_run_delay",
BenchmarkParam::Create<float>(-1.0f));
params.AddParam("random_shuffle_benchmark_runs",
BenchmarkParam::Create<bool>(true));
return params;
}
std::unique_ptr<MultiRunStatsRecorder>
BenchmarkPerformanceOptions::DefaultRunStatsRecorder() {
return std::unique_ptr<MultiRunStatsRecorder>(new MultiRunStatsRecorder());
}
std::vector<Flag> BenchmarkPerformanceOptions::GetFlags() {
return {
CreateFlag<std::string>(
"perf_options_list", ¶ms_,
"A comma-separated list of TFLite performance options to benchmark. "
"By default, all performance options are benchmarked."),
CreateFlag<float>("option_benchmark_run_delay", ¶ms_,
"The delay between two consecutive runs of "
"benchmarking performance options in seconds."),
CreateFlag<bool>(
"random_shuffle_benchmark_runs", ¶ms_,
"Whether to perform all benchmark runs, each of which has different "
"performance options, in a random order. It is enabled by default."),
};
}
bool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) {
auto flag_list = GetFlags();
const bool parse_result =
Flags::Parse(argc, const_cast<const char**>(argv), flag_list);
if (!parse_result) {
std::string usage = Flags::Usage(argv[0], flag_list);
TFLITE_LOG(ERROR) << usage;
return false;
}
// Parse the value of --perf_options_list to find performance options to be
// benchmarked.
return ParsePerfOptions();
}
bool BenchmarkPerformanceOptions::ParsePerfOptions() {
const auto& perf_options_list = params_.Get<std::string>("perf_options_list");
if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) {
TFLITE_LOG(ERROR) << "Cannot parse --perf_options_list: '"
<< perf_options_list
<< "'. Please double-check its value.";
perf_options_.clear();
return false;
}
const auto valid_options = GetValidPerfOptions();
bool is_valid = true;
for (const auto& option : perf_options_) {
if (std::find(valid_options.begin(), valid_options.end(), option) ==
valid_options.end()) {
is_valid = false;
break;
}
}
if (!is_valid) {
std::string valid_options_str;
for (int i = 0; i < valid_options.size() - 1; ++i) {
valid_options_str += (valid_options[i] + ", ");
}
valid_options_str += valid_options.back();
TFLITE_LOG(ERROR)
<< "There are invalid perf options in --perf_options_list: '"
<< perf_options_list << "'. Valid perf options are: ["
<< valid_options_str << "]";
perf_options_.clear();
return false;
}
return true;
}
std::vector<std::string> BenchmarkPerformanceOptions::GetValidPerfOptions()
const {
return {"all", "cpu", "gpu", "nnapi"};
}
bool BenchmarkPerformanceOptions::HasOption(const std::string& option) const {
return std::find(perf_options_.begin(), perf_options_.end(), option) !=
perf_options_.end();
}
void BenchmarkPerformanceOptions::ResetPerformanceOptions() {
single_option_run_params_->Set<int32_t>("num_threads", 1);
single_option_run_params_->Set<bool>("use_gpu", false);
#if defined(__ANDROID__)
single_option_run_params_->Set<bool>("gpu_precision_loss_allowed", true);
single_option_run_params_->Set<bool>("use_nnapi", false);
single_option_run_params_->Set<std::string>("nnapi_accelerator_name", "");
#endif
}
void BenchmarkPerformanceOptions::CreatePerformanceOptions() {
TFLITE_LOG(INFO) << "The list of TFLite runtime options to be benchmarked: ["
<< params_.Get<std::string>("perf_options_list") << "]";
const bool benchmark_all = HasOption("all");
if (benchmark_all || HasOption("cpu")) {
const std::vector<int> num_threads = {1, 2, 4};
for (const int count : num_threads) {
BenchmarkParams params;
params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(count));
all_run_params_.emplace_back(std::move(params));
}
}
if (benchmark_all || HasOption("gpu")) {
#if defined(__ANDROID__)
const std::vector<bool> allow_precision_loss = {true, false};
for (const auto precision_loss : allow_precision_loss) {
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
params.AddParam("gpu_precision_loss_allowed",
BenchmarkParam::Create<bool>(precision_loss));
all_run_params_.emplace_back(std::move(params));
}
#else
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
#endif
}
#if defined(__ANDROID__)
if (benchmark_all || HasOption("nnapi")) {
std::string nnapi_accelerators = nnapi::GetStringDeviceNamesList();
if (!nnapi_accelerators.empty()) {
std::vector<std::string> device_names;
util::SplitAndParse(nnapi_accelerators, ',', &device_names);
for (const auto name : device_names) {
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
params.AddParam("nnapi_accelerator_name",
BenchmarkParam::Create<std::string>(name));
all_run_params_.emplace_back(std::move(params));
}
} else {
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
}
}
#endif
}
void BenchmarkPerformanceOptions::Run(int argc, char** argv) {
// We first parse flags for single-option runs to get information like
// parameters of the input model etc.
if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return;
// Now, we parse flags that are specified for this particular binary.
if (!ParseFlags(&argc, argv)) return;
// Now, the remaining are unrecognized flags and we simply print them out.
for (int i = 1; i < argc; ++i) {
TFLITE_LOG(WARN) << "WARNING: unrecognized commandline flag: " << argv[i];
}
CreatePerformanceOptions();
if (params_.Get<bool>("random_shuffle_benchmark_runs")) {
std::random_shuffle(all_run_params_.begin(), all_run_params_.end());
}
// Now perform all runs, each with different performance-affecting parameters.
for (const auto& run_params : all_run_params_) {
// Reset all performance-related options before any runs.
ResetPerformanceOptions();
single_option_run_params_->Set(run_params);
util::SleepForSeconds(params_.Get<float>("option_benchmark_run_delay"));
single_option_run_->Run();
}
all_run_stats_->OutputStats();
}
} // namespace benchmark
} // namespace tflite
<commit_msg>Also benchmark nnapi execution when no explicit accelerator name is specified as the nnapi execution path is different.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/benchmark/benchmark_performance_options.h"
#include <algorithm>
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include "tensorflow/core/util/stats_calculator.h"
#include "tensorflow/lite/c/c_api_internal.h"
#if defined(__ANDROID__)
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/nnapi/nnapi_util.h"
#endif
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/benchmark/benchmark_params.h"
#include "tensorflow/lite/tools/benchmark/benchmark_utils.h"
#include "tensorflow/lite/tools/benchmark/logging.h"
#include "tensorflow/lite/tools/command_line_flags.h"
namespace tflite {
namespace benchmark {
void MultiRunStatsRecorder::OnBenchmarkStart(const BenchmarkParams& params) {
current_run_name_.clear();
#if defined(__ANDROID__)
if (params.Get<bool>("use_nnapi")) {
const std::string accelerator =
params.Get<std::string>("nnapi_accelerator_name");
current_run_name_ = accelerator.empty() ? "nnapi(w/o accel name)"
: "nnapi(" + accelerator + ")";
return;
}
#endif
if (params.Get<bool>("use_gpu")) {
#if defined(__ANDROID__)
const bool allow_precision_loss =
params.Get<bool>("gpu_precision_loss_allowed");
const std::string precision_tag = allow_precision_loss ? "fp16" : "fp32";
current_run_name_ = "gpu(" + precision_tag + ")";
const auto default_opts = TfLiteGpuDelegateOptionsV2Default();
if (default_opts.is_precision_loss_allowed == allow_precision_loss) {
current_run_name_ += "-default";
}
#else
current_run_name_ = "gpu-default";
#endif
return;
}
// Handle cases run on CPU
// Note: could use std::to_string to convert an integer to string but it
// requires C++11.
std::stringstream sstm;
sstm << "cpu w/ " << params.Get<int32_t>("num_threads") << " threads";
current_run_name_ = sstm.str();
}
void MultiRunStatsRecorder::OnBenchmarkEnd(const BenchmarkResults& results) {
each_run_stats_.emplace_back(std::make_pair(current_run_name_, results));
}
void MultiRunStatsRecorder::OutputStats() {
// Make a 80-character-long header.
TFLITE_LOG(INFO) << "\n==============Summary of All Runs w/ Different "
"Performance Options==============";
std::sort(each_run_stats_.begin(), each_run_stats_.end(),
EachRunStatsEntryComparator());
for (const auto& run_stats : each_run_stats_) {
std::stringstream stream;
// Output the name of this run first.
stream << std::setw(26) << run_stats.first << ": ";
run_stats.second.inference_time_us().OutputToStream(&stream);
TFLITE_LOG(INFO) << stream.str();
}
}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkModel* single_option_run)
: BenchmarkPerformanceOptions(DefaultParams(), single_option_run,
DefaultRunStatsRecorder()) {}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkParams params, BenchmarkModel* single_option_run,
std::unique_ptr<MultiRunStatsRecorder> all_run_stats)
: params_(std::move(params)),
single_option_run_(single_option_run),
single_option_run_params_(single_option_run->mutable_params()),
all_run_stats_(std::move(all_run_stats)) {
single_option_run_->AddListener(all_run_stats_.get());
}
BenchmarkParams BenchmarkPerformanceOptions::DefaultParams() {
BenchmarkParams params;
params.AddParam("perf_options_list",
BenchmarkParam::Create<std::string>("all"));
params.AddParam("option_benchmark_run_delay",
BenchmarkParam::Create<float>(-1.0f));
params.AddParam("random_shuffle_benchmark_runs",
BenchmarkParam::Create<bool>(true));
return params;
}
std::unique_ptr<MultiRunStatsRecorder>
BenchmarkPerformanceOptions::DefaultRunStatsRecorder() {
return std::unique_ptr<MultiRunStatsRecorder>(new MultiRunStatsRecorder());
}
std::vector<Flag> BenchmarkPerformanceOptions::GetFlags() {
return {
CreateFlag<std::string>(
"perf_options_list", ¶ms_,
"A comma-separated list of TFLite performance options to benchmark. "
"By default, all performance options are benchmarked."),
CreateFlag<float>("option_benchmark_run_delay", ¶ms_,
"The delay between two consecutive runs of "
"benchmarking performance options in seconds."),
CreateFlag<bool>(
"random_shuffle_benchmark_runs", ¶ms_,
"Whether to perform all benchmark runs, each of which has different "
"performance options, in a random order. It is enabled by default."),
};
}
bool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) {
auto flag_list = GetFlags();
const bool parse_result =
Flags::Parse(argc, const_cast<const char**>(argv), flag_list);
if (!parse_result) {
std::string usage = Flags::Usage(argv[0], flag_list);
TFLITE_LOG(ERROR) << usage;
return false;
}
// Parse the value of --perf_options_list to find performance options to be
// benchmarked.
return ParsePerfOptions();
}
bool BenchmarkPerformanceOptions::ParsePerfOptions() {
const auto& perf_options_list = params_.Get<std::string>("perf_options_list");
if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) {
TFLITE_LOG(ERROR) << "Cannot parse --perf_options_list: '"
<< perf_options_list
<< "'. Please double-check its value.";
perf_options_.clear();
return false;
}
const auto valid_options = GetValidPerfOptions();
bool is_valid = true;
for (const auto& option : perf_options_) {
if (std::find(valid_options.begin(), valid_options.end(), option) ==
valid_options.end()) {
is_valid = false;
break;
}
}
if (!is_valid) {
std::string valid_options_str;
for (int i = 0; i < valid_options.size() - 1; ++i) {
valid_options_str += (valid_options[i] + ", ");
}
valid_options_str += valid_options.back();
TFLITE_LOG(ERROR)
<< "There are invalid perf options in --perf_options_list: '"
<< perf_options_list << "'. Valid perf options are: ["
<< valid_options_str << "]";
perf_options_.clear();
return false;
}
return true;
}
std::vector<std::string> BenchmarkPerformanceOptions::GetValidPerfOptions()
const {
return {"all", "cpu", "gpu", "nnapi"};
}
bool BenchmarkPerformanceOptions::HasOption(const std::string& option) const {
return std::find(perf_options_.begin(), perf_options_.end(), option) !=
perf_options_.end();
}
void BenchmarkPerformanceOptions::ResetPerformanceOptions() {
single_option_run_params_->Set<int32_t>("num_threads", 1);
single_option_run_params_->Set<bool>("use_gpu", false);
#if defined(__ANDROID__)
single_option_run_params_->Set<bool>("gpu_precision_loss_allowed", true);
single_option_run_params_->Set<bool>("use_nnapi", false);
single_option_run_params_->Set<std::string>("nnapi_accelerator_name", "");
#endif
}
void BenchmarkPerformanceOptions::CreatePerformanceOptions() {
TFLITE_LOG(INFO) << "The list of TFLite runtime options to be benchmarked: ["
<< params_.Get<std::string>("perf_options_list") << "]";
const bool benchmark_all = HasOption("all");
if (benchmark_all || HasOption("cpu")) {
const std::vector<int> num_threads = {1, 2, 4};
for (const int count : num_threads) {
BenchmarkParams params;
params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(count));
all_run_params_.emplace_back(std::move(params));
}
}
if (benchmark_all || HasOption("gpu")) {
#if defined(__ANDROID__)
const std::vector<bool> allow_precision_loss = {true, false};
for (const auto precision_loss : allow_precision_loss) {
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
params.AddParam("gpu_precision_loss_allowed",
BenchmarkParam::Create<bool>(precision_loss));
all_run_params_.emplace_back(std::move(params));
}
#else
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
#endif
}
#if defined(__ANDROID__)
if (benchmark_all || HasOption("nnapi")) {
std::string nnapi_accelerators = nnapi::GetStringDeviceNamesList();
if (!nnapi_accelerators.empty()) {
std::vector<std::string> device_names;
util::SplitAndParse(nnapi_accelerators, ',', &device_names);
for (const auto name : device_names) {
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
params.AddParam("nnapi_accelerator_name",
BenchmarkParam::Create<std::string>(name));
all_run_params_.emplace_back(std::move(params));
}
}
// Explicitly test the case when there's no "nnapi_accelerator_name"
// parameter as the nnpai execution is different from the case when
// an accelerator name is explicitly specified.
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
}
#endif
}
void BenchmarkPerformanceOptions::Run(int argc, char** argv) {
// We first parse flags for single-option runs to get information like
// parameters of the input model etc.
if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return;
// Now, we parse flags that are specified for this particular binary.
if (!ParseFlags(&argc, argv)) return;
// Now, the remaining are unrecognized flags and we simply print them out.
for (int i = 1; i < argc; ++i) {
TFLITE_LOG(WARN) << "WARNING: unrecognized commandline flag: " << argv[i];
}
CreatePerformanceOptions();
if (params_.Get<bool>("random_shuffle_benchmark_runs")) {
std::random_shuffle(all_run_params_.begin(), all_run_params_.end());
}
// Now perform all runs, each with different performance-affecting parameters.
for (const auto& run_params : all_run_params_) {
// Reset all performance-related options before any runs.
ResetPerformanceOptions();
single_option_run_params_->Set(run_params);
util::SleepForSeconds(params_.Get<float>("option_benchmark_run_delay"));
single_option_run_->Run();
}
all_run_stats_->OutputStats();
}
} // namespace benchmark
} // namespace tflite
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "murmur3_partitioner.hh"
#include "utils/murmur_hash.hh"
#include "sstables/key.hh"
#include "utils/class_registrator.hh"
#include <boost/lexical_cast.hpp>
namespace dht {
inline
int64_t
murmur3_partitioner::normalize(int64_t in) {
return in == std::numeric_limits<int64_t>::lowest()
? std::numeric_limits<int64_t>::max()
: in;
}
token
murmur3_partitioner::get_token(bytes_view key) {
if (key.empty()) {
return minimum_token();
}
std::array<uint64_t, 2> hash;
utils::murmur_hash::hash3_x64_128(key, 0, hash);
return get_token(hash[0]);
}
token
murmur3_partitioner::get_token(uint64_t value) const {
// We don't normalize() the value, since token includes an is-before-everything
// indicator.
// FIXME: will this require a repair when importing a database?
auto t = net::hton(normalize(value));
bytes b(bytes::initialized_later(), 8);
std::copy_n(reinterpret_cast<int8_t*>(&t), 8, b.begin());
return token{token::kind::key, std::move(b)};
}
token
murmur3_partitioner::get_token(const sstables::key_view& key) {
return get_token(bytes_view(key));
}
token
murmur3_partitioner::get_token(const schema& s, partition_key_view key) {
std::array<uint64_t, 2> hash;
auto&& legacy = key.legacy_form(s);
utils::murmur_hash::hash3_x64_128(legacy.begin(), legacy.size(), 0, hash);
return get_token(hash[0]);
}
token murmur3_partitioner::get_random_token() {
auto rand = dht::get_random_number<uint64_t>();
return get_token(rand);
}
inline int64_t long_token(const token& t) {
if (t.is_minimum()) {
return std::numeric_limits<long>::min();
}
if (t._data.size() != sizeof(int64_t)) {
throw runtime_exception(sprint("Invalid token. Should have size %ld, has size %ld\n", sizeof(int64_t), t._data.size()));
}
auto ptr = t._data.begin();
auto lp = unaligned_cast<const int64_t *>(ptr);
return net::ntoh(*lp);
}
sstring murmur3_partitioner::to_sstring(const token& t) const {
return ::to_sstring(long_token(t));
}
dht::token murmur3_partitioner::from_sstring(const sstring& t) const {
auto lp = boost::lexical_cast<long>(t);
if (lp == std::numeric_limits<long>::min()) {
return minimum_token();
} else {
return get_token(uint64_t(lp));
}
}
dht::token murmur3_partitioner::from_bytes(bytes_view bytes) const {
if (bytes.size() != sizeof(int64_t)) {
throw runtime_exception(sprint("Invalid token. Should have size %ld, has size %ld\n", sizeof(int64_t), bytes.size()));
}
int64_t v;
std::copy_n(bytes.begin(), sizeof(v), reinterpret_cast<int8_t *>(&v));
auto tok = net::ntoh(v);
if (tok == std::numeric_limits<int64_t>::min()) {
return minimum_token();
} else {
return dht::token(dht::token::kind::key, bytes);
}
}
int murmur3_partitioner::tri_compare(const token& t1, const token& t2) const {
auto l1 = long_token(t1);
auto l2 = long_token(t2);
if (l1 == l2) {
return 0;
} else {
return l1 < l2 ? -1 : 1;
}
}
// Assuming that x>=y, return the positive difference x-y.
// The return type is an unsigned type, as the difference may overflow
// a signed type (e.g., consider very positive x and very negative y).
template <typename T>
static std::make_unsigned_t<T> positive_subtract(T x, T y) {
return std::make_unsigned_t<T>(x) - std::make_unsigned_t<T>(y);
}
token murmur3_partitioner::midpoint(const token& t1, const token& t2) const {
auto l1 = long_token(t1);
auto l2 = long_token(t2);
int64_t mid;
if (l1 <= l2) {
// To find the midpoint, we cannot use the trivial formula (l1+l2)/2
// because the addition can overflow the integer. To avoid this
// overflow, we first notice that the above formula is equivalent to
// l1 + (l2-l1)/2. Now, "l2-l1" can still overflow a signed integer
// (e.g., think of a very positive l2 and very negative l1), but
// because l1 <= l2 in this branch, we note that l2-l1 is positive
// and fits an *unsigned* int's range. So,
mid = l1 + positive_subtract(l2, l1)/2;
} else {
// When l2 < l1, we need to switch l1 and and l2 in the above
// formula, because now l1 - l2 is positive.
// Additionally, we consider this case is a "wrap around", so we need
// to behave as if l2 + 2^64 was meant instead of l2, i.e., add 2^63
// to the average.
mid = l2 + positive_subtract(l1, l2)/2 + 0x8000'0000'0000'0000;
}
return get_token(mid);
}
static float ratio_helper(int64_t a, int64_t b) {
uint64_t val = (a > b)? static_cast<uint64_t>(a) - static_cast<uint64_t>(b) : (static_cast<uint64_t>(a) - static_cast<uint64_t>(b) - 1);
return val/(float)std::numeric_limits<uint64_t>::max();
}
std::map<token, float>
murmur3_partitioner::describe_ownership(const std::vector<token>& sorted_tokens) {
std::map<token, float> ownerships;
auto i = sorted_tokens.begin();
// 0-case
if (i == sorted_tokens.end()) {
throw runtime_exception("No nodes present in the cluster. Has this node finished starting up?");
}
// 1-case
if (sorted_tokens.size() == 1) {
ownerships[sorted_tokens[0]] = 1.0;
// n-case
} else {
const token& start = sorted_tokens[0];
int64_t ti = long_token(start); // The first token and its value
int64_t start_long = ti;
int64_t tim1 = ti; // The last token and its value (after loop)
for (i++; i != sorted_tokens.end(); i++) {
ti = long_token(*i); // The next token and its value
ownerships[*i]= ratio_helper(ti, tim1); // save (T(i) -> %age)
tim1 = ti;
}
// The start token's range extends backward to the last token, which is why both were saved above.
ownerships[start] = ratio_helper(start_long, ti);
}
return ownerships;
}
data_type
murmur3_partitioner::get_token_validator() {
return long_type;
}
unsigned
murmur3_partitioner::shard_of(const token& t) const {
switch (t._kind) {
case token::kind::before_all_keys:
return 0;
case token::kind::after_all_keys:
return _shard_count - 1;
case token::kind::key:
int64_t l = long_token(t);
// treat l as a fraction between 0 and 1 and use 128-bit arithmetic to
// divide that range evenly among shards:
uint64_t adjusted = uint64_t(l) + uint64_t(std::numeric_limits<int64_t>::min());
return (__int128(adjusted) * _shard_count) >> 64;
}
assert(0);
}
token
murmur3_partitioner::token_for_next_shard(const token& t) const {
switch (t._kind) {
case token::kind::before_all_keys:
return token_for_next_shard(get_token(std::numeric_limits<int64_t>::min() + 1));
case token::kind::after_all_keys:
return maximum_token();
case token::kind::key:
if (long_token(t) == std::numeric_limits<int64_t>::min()) {
return token_for_next_shard(get_token(std::numeric_limits<int64_t>::min() + 1));
}
using uint128 = unsigned __int128;
auto s = shard_of(t) + 1;
if (s == _shard_count) {
return maximum_token();
}
uint64_t e = (uint128(s) << 64) / _shard_count;
while (((uint128(e) * _shard_count) >> 64) != s) {
// division will round down, so correct for it
++e;
}
return get_token(e + uint64_t(std::numeric_limits<int64_t>::min()));
}
assert(0);
}
using registry = class_registrator<i_partitioner, murmur3_partitioner>;
static registry registrator("org.apache.cassandra.dht.Murmur3Partitioner");
static registry registrator_short_name("Murmur3Partitioner");
}
<commit_msg>murmur3_partitioner: Convert maximum_token to sstring<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "murmur3_partitioner.hh"
#include "utils/murmur_hash.hh"
#include "sstables/key.hh"
#include "utils/class_registrator.hh"
#include <boost/lexical_cast.hpp>
namespace dht {
inline
int64_t
murmur3_partitioner::normalize(int64_t in) {
return in == std::numeric_limits<int64_t>::lowest()
? std::numeric_limits<int64_t>::max()
: in;
}
token
murmur3_partitioner::get_token(bytes_view key) {
if (key.empty()) {
return minimum_token();
}
std::array<uint64_t, 2> hash;
utils::murmur_hash::hash3_x64_128(key, 0, hash);
return get_token(hash[0]);
}
token
murmur3_partitioner::get_token(uint64_t value) const {
// We don't normalize() the value, since token includes an is-before-everything
// indicator.
// FIXME: will this require a repair when importing a database?
auto t = net::hton(normalize(value));
bytes b(bytes::initialized_later(), 8);
std::copy_n(reinterpret_cast<int8_t*>(&t), 8, b.begin());
return token{token::kind::key, std::move(b)};
}
token
murmur3_partitioner::get_token(const sstables::key_view& key) {
return get_token(bytes_view(key));
}
token
murmur3_partitioner::get_token(const schema& s, partition_key_view key) {
std::array<uint64_t, 2> hash;
auto&& legacy = key.legacy_form(s);
utils::murmur_hash::hash3_x64_128(legacy.begin(), legacy.size(), 0, hash);
return get_token(hash[0]);
}
token murmur3_partitioner::get_random_token() {
auto rand = dht::get_random_number<uint64_t>();
return get_token(rand);
}
inline int64_t long_token(const token& t) {
if (t.is_minimum() || t.is_maximum()) {
return std::numeric_limits<long>::min();
}
if (t._data.size() != sizeof(int64_t)) {
throw runtime_exception(sprint("Invalid token. Should have size %ld, has size %ld\n", sizeof(int64_t), t._data.size()));
}
auto ptr = t._data.begin();
auto lp = unaligned_cast<const int64_t *>(ptr);
return net::ntoh(*lp);
}
sstring murmur3_partitioner::to_sstring(const token& t) const {
return ::to_sstring(long_token(t));
}
dht::token murmur3_partitioner::from_sstring(const sstring& t) const {
auto lp = boost::lexical_cast<long>(t);
if (lp == std::numeric_limits<long>::min()) {
return minimum_token();
} else {
return get_token(uint64_t(lp));
}
}
dht::token murmur3_partitioner::from_bytes(bytes_view bytes) const {
if (bytes.size() != sizeof(int64_t)) {
throw runtime_exception(sprint("Invalid token. Should have size %ld, has size %ld\n", sizeof(int64_t), bytes.size()));
}
int64_t v;
std::copy_n(bytes.begin(), sizeof(v), reinterpret_cast<int8_t *>(&v));
auto tok = net::ntoh(v);
if (tok == std::numeric_limits<int64_t>::min()) {
return minimum_token();
} else {
return dht::token(dht::token::kind::key, bytes);
}
}
int murmur3_partitioner::tri_compare(const token& t1, const token& t2) const {
auto l1 = long_token(t1);
auto l2 = long_token(t2);
if (l1 == l2) {
return 0;
} else {
return l1 < l2 ? -1 : 1;
}
}
// Assuming that x>=y, return the positive difference x-y.
// The return type is an unsigned type, as the difference may overflow
// a signed type (e.g., consider very positive x and very negative y).
template <typename T>
static std::make_unsigned_t<T> positive_subtract(T x, T y) {
return std::make_unsigned_t<T>(x) - std::make_unsigned_t<T>(y);
}
token murmur3_partitioner::midpoint(const token& t1, const token& t2) const {
auto l1 = long_token(t1);
auto l2 = long_token(t2);
int64_t mid;
if (l1 <= l2) {
// To find the midpoint, we cannot use the trivial formula (l1+l2)/2
// because the addition can overflow the integer. To avoid this
// overflow, we first notice that the above formula is equivalent to
// l1 + (l2-l1)/2. Now, "l2-l1" can still overflow a signed integer
// (e.g., think of a very positive l2 and very negative l1), but
// because l1 <= l2 in this branch, we note that l2-l1 is positive
// and fits an *unsigned* int's range. So,
mid = l1 + positive_subtract(l2, l1)/2;
} else {
// When l2 < l1, we need to switch l1 and and l2 in the above
// formula, because now l1 - l2 is positive.
// Additionally, we consider this case is a "wrap around", so we need
// to behave as if l2 + 2^64 was meant instead of l2, i.e., add 2^63
// to the average.
mid = l2 + positive_subtract(l1, l2)/2 + 0x8000'0000'0000'0000;
}
return get_token(mid);
}
static float ratio_helper(int64_t a, int64_t b) {
uint64_t val = (a > b)? static_cast<uint64_t>(a) - static_cast<uint64_t>(b) : (static_cast<uint64_t>(a) - static_cast<uint64_t>(b) - 1);
return val/(float)std::numeric_limits<uint64_t>::max();
}
std::map<token, float>
murmur3_partitioner::describe_ownership(const std::vector<token>& sorted_tokens) {
std::map<token, float> ownerships;
auto i = sorted_tokens.begin();
// 0-case
if (i == sorted_tokens.end()) {
throw runtime_exception("No nodes present in the cluster. Has this node finished starting up?");
}
// 1-case
if (sorted_tokens.size() == 1) {
ownerships[sorted_tokens[0]] = 1.0;
// n-case
} else {
const token& start = sorted_tokens[0];
int64_t ti = long_token(start); // The first token and its value
int64_t start_long = ti;
int64_t tim1 = ti; // The last token and its value (after loop)
for (i++; i != sorted_tokens.end(); i++) {
ti = long_token(*i); // The next token and its value
ownerships[*i]= ratio_helper(ti, tim1); // save (T(i) -> %age)
tim1 = ti;
}
// The start token's range extends backward to the last token, which is why both were saved above.
ownerships[start] = ratio_helper(start_long, ti);
}
return ownerships;
}
data_type
murmur3_partitioner::get_token_validator() {
return long_type;
}
unsigned
murmur3_partitioner::shard_of(const token& t) const {
switch (t._kind) {
case token::kind::before_all_keys:
return 0;
case token::kind::after_all_keys:
return _shard_count - 1;
case token::kind::key:
int64_t l = long_token(t);
// treat l as a fraction between 0 and 1 and use 128-bit arithmetic to
// divide that range evenly among shards:
uint64_t adjusted = uint64_t(l) + uint64_t(std::numeric_limits<int64_t>::min());
return (__int128(adjusted) * _shard_count) >> 64;
}
assert(0);
}
token
murmur3_partitioner::token_for_next_shard(const token& t) const {
switch (t._kind) {
case token::kind::before_all_keys:
return token_for_next_shard(get_token(std::numeric_limits<int64_t>::min() + 1));
case token::kind::after_all_keys:
return maximum_token();
case token::kind::key:
if (long_token(t) == std::numeric_limits<int64_t>::min()) {
return token_for_next_shard(get_token(std::numeric_limits<int64_t>::min() + 1));
}
using uint128 = unsigned __int128;
auto s = shard_of(t) + 1;
if (s == _shard_count) {
return maximum_token();
}
uint64_t e = (uint128(s) << 64) / _shard_count;
while (((uint128(e) * _shard_count) >> 64) != s) {
// division will round down, so correct for it
++e;
}
return get_token(e + uint64_t(std::numeric_limits<int64_t>::min()));
}
assert(0);
}
using registry = class_registrator<i_partitioner, murmur3_partitioner>;
static registry registrator("org.apache.cassandra.dht.Murmur3Partitioner");
static registry registrator_short_name("Murmur3Partitioner");
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/dot_as_convolution_util.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
#include "tensorflow/compiler/xla/status_macros.h"
namespace xla {
namespace dot_as_convolution_util {
bool ConvSpatialDimensionIsParallel(const WindowDimension& wd, int64 lhs_size) {
// A parallel batch dimension in DotGeneral is represented as a
// spatial dimension with window size B (batch dimension size),
// stride B - 1, and base dilation B.
if (lhs_size == wd.size() && lhs_size == wd.base_dilation() &&
((std::max<int64>(1, lhs_size - 1) == wd.stride() &&
wd.window_dilation() == 1) ||
(std::max<int64>(1, lhs_size - 1) == wd.window_dilation() &&
wd.stride() == 1)) &&
wd.padding_high() == 0 && wd.padding_low() == 0 &&
!wd.window_reversal()) {
return true;
}
// Aternative representation of a batch dimension.
if (wd.size() == lhs_size && wd.padding_high() == lhs_size - 1 &&
wd.padding_low() == lhs_size - 1 && wd.window_reversal() &&
wd.window_dilation() == 1 && wd.stride() == lhs_size &&
wd.base_dilation() == lhs_size - 1) {
return true;
}
return false;
}
/* static */ DotConvolutionDimsInfo ParseConvolutionDimsInfo(
const HloInstruction* conv) {
CHECK_EQ(conv->opcode(), HloOpcode::kConvolution);
const auto& conv_dims = conv->convolution_dimension_numbers();
DotConvolutionDimsInfo dims;
dims.lhs_non_contracting_dims.push_back(
{conv_dims.input_batch_dimension(), -1,
conv_dims.output_batch_dimension(), -1});
dims.rhs_non_contracting_dims.push_back(
{-1, conv_dims.kernel_output_feature_dimension(),
conv_dims.output_feature_dimension(), -1});
dims.contracting_dims.push_back({conv_dims.input_feature_dimension(),
conv_dims.kernel_input_feature_dimension(),
-1, -1});
for (int64 i = 0; i < conv_dims.input_spatial_dimensions_size(); ++i) {
int64 lhs = conv_dims.input_spatial_dimensions(i);
int64 lhs_size = conv->operand(0)->shape().dimensions(lhs);
int64 rhs = conv_dims.kernel_spatial_dimensions(i);
int64 rhs_size = conv->operand(1)->shape().dimensions(rhs);
int64 output = conv_dims.output_spatial_dimensions(i);
const auto& wd = conv->window().dimensions(i);
if (ConvSpatialDimensionIsParallel(wd, lhs_size)) {
dims.batch_dims.push_back({lhs, rhs, output, i});
} else if (lhs_size == wd.size() && wd.base_dilation() == 1 &&
wd.window_dilation() == 1 && wd.padding_high() == 0 &&
wd.padding_low() == 0 && !wd.window_reversal()) {
// A contracting dimension be represented as a spatial dimension with
// window size C (contracting dimension size). Stride can be any size
// since there is only one window.
dims.contracting_dims.push_back({lhs, rhs, output, i});
} else if (wd.stride() == 1 && wd.window_dilation() == 1 &&
wd.base_dilation() == 1) {
if (rhs_size == 1 && wd.size() == 1 && wd.padding_high() == 0 &&
wd.padding_low() == 0 && !wd.window_reversal()) {
// A LHS non-contracting dimension can be represented as a spatial
// dimension with window size 1.
dims.lhs_non_contracting_dims.push_back({lhs, rhs, output, i});
} else if (lhs_size == 1 && wd.size() == rhs_size &&
wd.padding_high() == rhs_size - 1 &&
wd.padding_low() == rhs_size - 1 && wd.window_reversal()) {
// A RHS non-contracting dimension can be represented as a spatial
// dimension with window size N (non-contracting dimension size), low
// padding N - 1, high padding N - 1 and window reversal.
dims.rhs_non_contracting_dims.push_back({lhs, rhs, output, i});
} else {
dims.conv_spatial_dims.push_back({lhs, rhs, output, i});
}
} else {
dims.conv_spatial_dims.push_back({lhs, rhs, output, i});
}
}
return dims;
}
StatusOr<std::unique_ptr<HloInstruction>>
CreateShardedConvForDotGeneralConvolution(
const HloInstruction& conv, const DotConvolutionDimsInfo& dot_dnums,
HloInstruction* sharded_lhs_hlo, HloInstruction* sharded_rhs_hlo) {
CHECK_EQ(conv.opcode(), HloOpcode::kConvolution);
const auto& conv_dnums = conv.convolution_dimension_numbers();
auto window = conv.window();
for (const auto& dim : dot_dnums.batch_dims) {
auto wd = window.mutable_dimensions(dim.spatial_dim);
wd->set_size(sharded_lhs_hlo->shape().dimensions(
conv_dnums.input_spatial_dimensions(dim.spatial_dim)));
wd->set_stride(std::max<int64>(1, wd->size() - 1));
wd->set_base_dilation(wd->size());
}
for (const auto& dim : dot_dnums.contracting_dims) {
if (dim.spatial_dim < 0) {
continue;
}
auto wd = window.mutable_dimensions(dim.spatial_dim);
wd->set_size(sharded_lhs_hlo->shape().dimensions(
conv_dnums.input_spatial_dimensions(dim.spatial_dim)));
}
for (const auto& dim : dot_dnums.rhs_non_contracting_dims) {
if (dim.spatial_dim < 0) {
continue;
}
auto wd = window.mutable_dimensions(dim.spatial_dim);
wd->set_size(sharded_rhs_hlo->shape().dimensions(
conv_dnums.kernel_spatial_dimensions(dim.spatial_dim)));
wd->set_padding_high(wd->size() - 1);
wd->set_padding_low(wd->size() - 1);
}
TF_ASSIGN_OR_RETURN(Shape sharded_conv_shape,
ShapeInference::InferConvolveShape(
sharded_lhs_hlo->shape(), sharded_rhs_hlo->shape(),
/*feature_group_count=*/1,
/*batch_group_count=*/1, window, conv_dnums));
*sharded_conv_shape.mutable_layout() = conv.shape().layout();
return HloInstruction::CreateConvolve(
sharded_conv_shape, sharded_lhs_hlo, sharded_rhs_hlo,
/*feature_group_count=*/1,
/*batch_group_count=*/1, window, conv_dnums, conv.precision_config());
}
DotConvolutionDimsInfo ParseDotGeneralFromDot(const HloInstruction* dot) {
const auto& dot_dim_numbs = dot->dot_dimension_numbers();
dot_as_convolution_util::DotConvolutionDimsInfo dnums;
for (int64 i = 0; i < dot_dim_numbs.lhs_batch_dimensions().size(); ++i) {
dnums.batch_dims.emplace_back();
dnums.batch_dims.back().lhs = dot_dim_numbs.lhs_batch_dimensions(i);
dnums.batch_dims.back().rhs = dot_dim_numbs.rhs_batch_dimensions(i);
dnums.batch_dims.back().output = i;
dnums.batch_dims.back().spatial_dim = -1;
}
for (int64 i = 0; i < dot_dim_numbs.lhs_contracting_dimensions().size();
++i) {
dnums.contracting_dims.emplace_back();
dnums.contracting_dims.back().lhs =
dot_dim_numbs.lhs_contracting_dimensions(i);
dnums.contracting_dims.back().rhs =
dot_dim_numbs.rhs_contracting_dimensions(i);
dnums.contracting_dims.back().output = -1;
dnums.contracting_dims.back().spatial_dim = -1;
}
for (int64 i = 0; i < dot->operand(0)->shape().rank(); ++i) {
if (!absl::c_linear_search(dot_dim_numbs.lhs_batch_dimensions(), i) &&
!absl::c_linear_search(dot_dim_numbs.lhs_contracting_dimensions(), i)) {
dnums.lhs_non_contracting_dims.emplace_back();
dnums.lhs_non_contracting_dims.back().lhs = i;
dnums.lhs_non_contracting_dims.back().rhs = -1;
dnums.lhs_non_contracting_dims.back().output =
dot_dim_numbs.lhs_batch_dimensions_size() +
dnums.lhs_non_contracting_dims.size() - 1;
dnums.lhs_non_contracting_dims.back().spatial_dim = -1;
}
}
for (int64 i = 0; i < dot->operand(1)->shape().rank(); ++i) {
if (!absl::c_linear_search(dot_dim_numbs.rhs_batch_dimensions(), i) &&
!absl::c_linear_search(dot_dim_numbs.rhs_contracting_dimensions(), i)) {
dnums.rhs_non_contracting_dims.emplace_back();
dnums.rhs_non_contracting_dims.back().lhs = -1;
dnums.rhs_non_contracting_dims.back().rhs = i;
dnums.rhs_non_contracting_dims.back().output =
dot_dim_numbs.lhs_batch_dimensions_size() +
dnums.lhs_non_contracting_dims.size() +
dnums.rhs_non_contracting_dims.size() - 1;
dnums.rhs_non_contracting_dims.back().spatial_dim = -1;
}
}
return dnums;
}
} // namespace dot_as_convolution_util
} // namespace xla
<commit_msg>[XLA:SPMD] Fix SPMD issue with replicated depthwise convolution.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/dot_as_convolution_util.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
#include "tensorflow/compiler/xla/status_macros.h"
namespace xla {
namespace dot_as_convolution_util {
bool ConvSpatialDimensionIsParallel(const WindowDimension& wd, int64 lhs_size) {
// A parallel batch dimension in DotGeneral is represented as a
// spatial dimension with window size B (batch dimension size),
// stride B - 1, and base dilation B.
if (lhs_size == wd.size() && lhs_size == wd.base_dilation() &&
((std::max<int64>(1, lhs_size - 1) == wd.stride() &&
wd.window_dilation() == 1) ||
(std::max<int64>(1, lhs_size - 1) == wd.window_dilation() &&
wd.stride() == 1)) &&
wd.padding_high() == 0 && wd.padding_low() == 0 &&
!wd.window_reversal()) {
return true;
}
// Aternative representation of a batch dimension.
if (wd.size() == lhs_size && wd.padding_high() == lhs_size - 1 &&
wd.padding_low() == lhs_size - 1 && wd.window_reversal() &&
wd.window_dilation() == 1 && wd.stride() == lhs_size &&
wd.base_dilation() == lhs_size - 1) {
return true;
}
return false;
}
/* static */ DotConvolutionDimsInfo ParseConvolutionDimsInfo(
const HloInstruction* conv) {
CHECK_EQ(conv->opcode(), HloOpcode::kConvolution);
const auto& conv_dims = conv->convolution_dimension_numbers();
DotConvolutionDimsInfo dims;
dims.lhs_non_contracting_dims.push_back(
{conv_dims.input_batch_dimension(), -1,
conv_dims.output_batch_dimension(), -1});
dims.rhs_non_contracting_dims.push_back(
{-1, conv_dims.kernel_output_feature_dimension(),
conv_dims.output_feature_dimension(), -1});
dims.contracting_dims.push_back({conv_dims.input_feature_dimension(),
conv_dims.kernel_input_feature_dimension(),
-1, -1});
for (int64 i = 0; i < conv_dims.input_spatial_dimensions_size(); ++i) {
int64 lhs = conv_dims.input_spatial_dimensions(i);
int64 lhs_size = conv->operand(0)->shape().dimensions(lhs);
int64 rhs = conv_dims.kernel_spatial_dimensions(i);
int64 rhs_size = conv->operand(1)->shape().dimensions(rhs);
int64 output = conv_dims.output_spatial_dimensions(i);
const auto& wd = conv->window().dimensions(i);
if (ConvSpatialDimensionIsParallel(wd, lhs_size)) {
dims.batch_dims.push_back({lhs, rhs, output, i});
} else if (lhs_size == wd.size() && wd.base_dilation() == 1 &&
wd.window_dilation() == 1 && wd.padding_high() == 0 &&
wd.padding_low() == 0 && !wd.window_reversal()) {
// A contracting dimension be represented as a spatial dimension with
// window size C (contracting dimension size). Stride can be any size
// since there is only one window.
dims.contracting_dims.push_back({lhs, rhs, output, i});
} else if (wd.stride() == 1 && wd.window_dilation() == 1 &&
wd.base_dilation() == 1) {
if (rhs_size == 1 && wd.size() == 1 && wd.padding_high() == 0 &&
wd.padding_low() == 0 && !wd.window_reversal()) {
// A LHS non-contracting dimension can be represented as a spatial
// dimension with window size 1.
dims.lhs_non_contracting_dims.push_back({lhs, rhs, output, i});
} else if (lhs_size == 1 && wd.size() == rhs_size &&
wd.padding_high() == rhs_size - 1 &&
wd.padding_low() == rhs_size - 1 && wd.window_reversal()) {
// A RHS non-contracting dimension can be represented as a spatial
// dimension with window size N (non-contracting dimension size), low
// padding N - 1, high padding N - 1 and window reversal.
dims.rhs_non_contracting_dims.push_back({lhs, rhs, output, i});
} else {
dims.conv_spatial_dims.push_back({lhs, rhs, output, i});
}
} else {
dims.conv_spatial_dims.push_back({lhs, rhs, output, i});
}
}
return dims;
}
StatusOr<std::unique_ptr<HloInstruction>>
CreateShardedConvForDotGeneralConvolution(
const HloInstruction& conv, const DotConvolutionDimsInfo& dot_dnums,
HloInstruction* sharded_lhs_hlo, HloInstruction* sharded_rhs_hlo) {
CHECK_EQ(conv.opcode(), HloOpcode::kConvolution);
const auto& conv_dnums = conv.convolution_dimension_numbers();
auto window = conv.window();
for (const auto& dim : dot_dnums.batch_dims) {
auto wd = window.mutable_dimensions(dim.spatial_dim);
wd->set_size(sharded_lhs_hlo->shape().dimensions(
conv_dnums.input_spatial_dimensions(dim.spatial_dim)));
wd->set_stride(std::max<int64>(1, wd->size() - 1));
wd->set_base_dilation(wd->size());
}
for (const auto& dim : dot_dnums.contracting_dims) {
if (dim.spatial_dim < 0) {
continue;
}
auto wd = window.mutable_dimensions(dim.spatial_dim);
wd->set_size(sharded_lhs_hlo->shape().dimensions(
conv_dnums.input_spatial_dimensions(dim.spatial_dim)));
}
for (const auto& dim : dot_dnums.rhs_non_contracting_dims) {
if (dim.spatial_dim < 0) {
continue;
}
auto wd = window.mutable_dimensions(dim.spatial_dim);
wd->set_size(sharded_rhs_hlo->shape().dimensions(
conv_dnums.kernel_spatial_dimensions(dim.spatial_dim)));
wd->set_padding_high(wd->size() - 1);
wd->set_padding_low(wd->size() - 1);
}
TF_ASSIGN_OR_RETURN(
Shape sharded_conv_shape,
ShapeInference::InferConvolveShape(
sharded_lhs_hlo->shape(), sharded_rhs_hlo->shape(),
/*feature_group_count=*/conv.feature_group_count(),
/*batch_group_count=*/conv.batch_group_count(), window, conv_dnums));
*sharded_conv_shape.mutable_layout() = conv.shape().layout();
return HloInstruction::CreateConvolve(
sharded_conv_shape, sharded_lhs_hlo, sharded_rhs_hlo,
/*feature_group_count=*/conv.feature_group_count(),
/*batch_group_count=*/conv.batch_group_count(), window, conv_dnums,
conv.precision_config());
}
DotConvolutionDimsInfo ParseDotGeneralFromDot(const HloInstruction* dot) {
const auto& dot_dim_numbs = dot->dot_dimension_numbers();
dot_as_convolution_util::DotConvolutionDimsInfo dnums;
for (int64 i = 0; i < dot_dim_numbs.lhs_batch_dimensions().size(); ++i) {
dnums.batch_dims.emplace_back();
dnums.batch_dims.back().lhs = dot_dim_numbs.lhs_batch_dimensions(i);
dnums.batch_dims.back().rhs = dot_dim_numbs.rhs_batch_dimensions(i);
dnums.batch_dims.back().output = i;
dnums.batch_dims.back().spatial_dim = -1;
}
for (int64 i = 0; i < dot_dim_numbs.lhs_contracting_dimensions().size();
++i) {
dnums.contracting_dims.emplace_back();
dnums.contracting_dims.back().lhs =
dot_dim_numbs.lhs_contracting_dimensions(i);
dnums.contracting_dims.back().rhs =
dot_dim_numbs.rhs_contracting_dimensions(i);
dnums.contracting_dims.back().output = -1;
dnums.contracting_dims.back().spatial_dim = -1;
}
for (int64 i = 0; i < dot->operand(0)->shape().rank(); ++i) {
if (!absl::c_linear_search(dot_dim_numbs.lhs_batch_dimensions(), i) &&
!absl::c_linear_search(dot_dim_numbs.lhs_contracting_dimensions(), i)) {
dnums.lhs_non_contracting_dims.emplace_back();
dnums.lhs_non_contracting_dims.back().lhs = i;
dnums.lhs_non_contracting_dims.back().rhs = -1;
dnums.lhs_non_contracting_dims.back().output =
dot_dim_numbs.lhs_batch_dimensions_size() +
dnums.lhs_non_contracting_dims.size() - 1;
dnums.lhs_non_contracting_dims.back().spatial_dim = -1;
}
}
for (int64 i = 0; i < dot->operand(1)->shape().rank(); ++i) {
if (!absl::c_linear_search(dot_dim_numbs.rhs_batch_dimensions(), i) &&
!absl::c_linear_search(dot_dim_numbs.rhs_contracting_dimensions(), i)) {
dnums.rhs_non_contracting_dims.emplace_back();
dnums.rhs_non_contracting_dims.back().lhs = -1;
dnums.rhs_non_contracting_dims.back().rhs = i;
dnums.rhs_non_contracting_dims.back().output =
dot_dim_numbs.lhs_batch_dimensions_size() +
dnums.lhs_non_contracting_dims.size() +
dnums.rhs_non_contracting_dims.size() - 1;
dnums.rhs_non_contracting_dims.back().spatial_dim = -1;
}
}
return dnums;
}
} // namespace dot_as_convolution_util
} // namespace xla
<|endoftext|>
|
<commit_before>#include <string>
#include <iostream>
#include "dirent.h"
using namespace std;
int main()
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("\\lists\\")) != NULL) {
while ((ent = readdir (dir)) != NULL) {
cout << ent->d_name << endl;
}
closedir(dir);
}
else
{
perror ("");
return EXIT_FAILURE;
}
return (0);
}
<commit_msg>Delete directoryIteratorTest2.cpp<commit_after><|endoftext|>
|
<commit_before>#include "Header.h"
#include "Common/StringUtils.h"
#include "Common/TimeUtils.h"
using namespace HTTP;
/**Parses a string containing key=value pairs in HTTP header format. Supports value quoting, without quote escape.
Sample input stuff; key1=value1; key2="value2"
@param ParamConsumerType A functor with the following signature:
Func(const CharType *KeyBegin, const CharType *KeyEnd, const CharType *ValueBegin, const CharType *ValueEnd)
Note that ValueBegin and ValueEnd can be nullptr, if the given key
*/
template<class ParamConsumerType, class CharType, CharType Separator>
void ParseDelimitedKeyValue(const CharType *Source, ParamConsumerType Consumer)
{
const CharType *CurrPos=Source;
const CharType *KeyBegin=NULL, *KeyEnd=NULL;
const CharType *ValueBegin=NULL;
enum PARSE_STATE
{
PS_ZERO, //Searching for key.
PS_KEY, //Searching for key end.
PS_SEPSEARCH, //Searching for Separator.
PS_VALSEARCH, //Searching for value.
PS_VAL, //Searching for value end.
PS_QUOTEDVAL, //Searching for value end in quoted value.
} CurrState=PS_ZERO;
CharType CurrVal;
while (true)
{
CurrVal=*CurrPos;
if (!CurrVal)
break;
switch (CurrState)
{
case PS_ZERO:
if ((!UD::StringUtils::IsWS(CurrVal)) && (CurrVal!=';'))
{
KeyBegin=CurrPos;
CurrState=PS_KEY;
}
break;
case PS_KEY:
if (UD::StringUtils::IsWS(CurrVal))
{
KeyEnd=CurrPos;
CurrState=PS_SEPSEARCH;
}
else if (CurrVal==Separator)
{
KeyEnd=CurrPos;
CurrState=PS_VALSEARCH;
}
else if (CurrVal==';')
{
Consumer(KeyBegin,CurrPos,nullptr,nullptr);
CurrState=PS_ZERO;
}
break;
case PS_SEPSEARCH:
if (CurrVal==Separator)
CurrState=PS_VALSEARCH;
else if (CurrVal==';')
{
Consumer(KeyBegin,KeyEnd,nullptr,nullptr);
CurrState=PS_ZERO;
}
else if (!UD::StringUtils::IsWS(CurrVal))
{
//This is something weird, like: "Key1 Key2...". Let's skip Key1, and start again from Key2.
KeyBegin=CurrPos;
CurrState=PS_KEY;
}
break;
case PS_VALSEARCH:
if (!UD::StringUtils::IsWS(CurrVal))
{
ValueBegin=CurrPos;
if (CurrVal=='"')
CurrState=PS_QUOTEDVAL;
else
CurrState=PS_VAL;
}
else if (UD::StringUtils::IsNewLine(CurrVal))
{
//Empty value.
Consumer(KeyBegin,KeyEnd,CurrPos,CurrPos);
CurrState=PS_ZERO;
}
break;
case PS_VAL:
if ((UD::StringUtils::IsWS(CurrVal)) || (CurrVal==';'))
{
//End of value.
Consumer(KeyBegin,KeyEnd,ValueBegin,CurrPos);
CurrState=PS_ZERO;
}
break;
case PS_QUOTEDVAL:
if (CurrVal=='"')
{
//End of quoted value (ValueBegin points to the '"').
Consumer(KeyBegin,KeyEnd,ValueBegin+1,CurrPos);
CurrState=PS_ZERO;
}
break;
default:
break;
}
CurrPos++;
}
//We might have some work left.
switch (CurrState)
{
case PS_VAL:
//Output the last value.
Consumer(KeyBegin,KeyEnd,ValueBegin,CurrPos);
break;
case PS_QUOTEDVAL:
//Output the last value (quoted, but quote not closed).
Consumer(KeyBegin,KeyEnd,ValueBegin+1,CurrPos);
break;
default:
break;
}
}
template<class ParamConsumerType>
inline void ParseDelimitedKeyValue(const char *Source, ParamConsumerType Consumer) { ParseDelimitedKeyValue<ParamConsumerType,char,'='>(Source,Consumer); }
struct SingleKeyExtractor
{
SingleKeyExtractor(const std::string &KeyName, std::string &ValTargetStr) : Key(KeyName), Target(ValTargetStr)
{ }
void operator()(const char *KeyBegin, const char *KeyEnd, const char *ValueBegin, const char *ValueEnd)
{
if ((ValueBegin) && (UD::StringUtils::IsEqual(Key,KeyBegin,KeyEnd)))
Target.assign(ValueBegin,ValueEnd);
}
private:
const std::string &Key;
std::string &Target;
};
struct ContentDisposExtractor
{
ContentDisposExtractor(std::string &NameStr, std::string &FNStr) : NameTarget(NameStr), FNTarget(FNStr)
{ }
void operator()(const char *KeyBegin, const char *KeyEnd, const char *ValueBegin, const char *ValueEnd)
{
if (ValueBegin)
{
if (UD::StringUtils::IsEqual(NameKey,KeyBegin,KeyEnd))
NameTarget.assign(ValueBegin,ValueEnd);
else if (UD::StringUtils::IsEqual(FNKey,KeyBegin,KeyEnd))
FNTarget.assign(ValueBegin,ValueEnd);
}
}
private:
static const std::string NameKey, FNKey;
std::string &NameTarget, &FNTarget;
};
const std::string ContentDisposExtractor::NameKey="name", ContentDisposExtractor::FNKey="filename";
const std::string Header::BoundaryParamName("boundary");
boost::unordered_map<std::string,HEADERNAME> Header::HeaderNameMap;
bool Header::IsHeaderNameInit=Header::InitHeaderNameMap();
Header::Header(char *LineBegin, char *LineEnd)
{
if (ExtractHeader(LineBegin,LineEnd,(char **)&Name,(char **)&Value))
IntName=ParseHeader(Name);
else
IntName=HN_UNKNOWN;
}
Header::Header(char *LineBegin, char *LineEnd, SkipParseOption) : IntName(HN_UNKNOWN)
{
ExtractHeader(LineBegin,LineEnd,(char **)&Name,(char **)&Value);
}
CONTENTTYPE Header::GetContentType(std::string &OutBoundary) const
{
if (IntName!=HN_CONTENT_TYPE)
return CT_UNKNOWN;
if (const char *SCPos=strchr(Value,';'))
{
if (UD::StringUtils::CmpI("multipart/form-data",Value,SCPos)==0)
{
OutBoundary.clear();
ParseDelimitedKeyValue(SCPos,SingleKeyExtractor(BoundaryParamName,OutBoundary));
return !OutBoundary.empty() ? CT_FORM_MULTIPART : CT_UNKNOWN;
}
}
else
{
if (UD::StringUtils::CmpI(Value,"application/x-www-form-urlencoded")==0)
return CT_URL_ENCODED;
}
return CT_UNKNOWN;
}
void Header::ParseContentDisposition(std::string &OutName, std::string &OutFileName) const
{
if (IntName==HN_CONTENT_DISPOSITION)
ParseDelimitedKeyValue(Value,ContentDisposExtractor(OutName,OutFileName));
else
{
OutName.clear();
OutFileName.clear();
}
}
bool Header::IsConnectionClose() const
{
return strcmp(Value,"close")==0;
}
time_t Header::GetDateTime() const
{
// 0 1 2
// 01234567890123456789012345678
//Sample RFC 1123 date: "Sun, 06 Nov 1994 08:49:37 GMT", strlen: 29
//WDay values: "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun"
//Month values: "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
if (strlen(Value)!=DateStringLength)
throw FormatException("DateTime has invalid length");
tm TM;
TM.tm_isdst=0; TM.tm_wday=0; TM.tm_yday=0;
TM.tm_mday=atoi(Value + 5);
TM.tm_year=atoi(Value + 12) - 1900;
TM.tm_hour=atoi(Value + 17);
TM.tm_min=atoi(Value + 20);
TM.tm_sec=atoi(Value + 23);
TM.tm_mon=-1;
switch (*(Value + 8))
{
case 'A': //Apr, Aug
if (*(Value + 9)=='p')
TM.tm_mon=3; //Apr
else if (*(Value + 9)=='u')
TM.tm_mon=7; //Aug
break;
case 'D': //Dec
TM.tm_mon=11;
break;
case 'F': //Feb
TM.tm_mon=2;
break;
case 'J': //Jan, Jun, Jul
if (*(Value + 9)=='a')
TM.tm_mon=0; //Jan
else if (*(Value + 10)=='l')
TM.tm_mon=6; //Jul
else if (*(Value + 10)=='n')
TM.tm_mon=5; //Jun
break;
case 'M': //Mar, May
if (*(Value + 10)=='r')
TM.tm_mon=2; //Mar
else if (*(Value + 10)=='y')
TM.tm_mon=4; //May
break;
case 'N': //Nov
TM.tm_mon=10;
break;
case 'O': //Oct
TM.tm_mon=9;
break;
case 'S': //Sep
TM.tm_mon=8;
break;
}
if ((TM.tm_year==0) || (TM.tm_mon==1))
throw FormatException("DateTime is invalid");
time_t RetTime=UD::TimeUtils::TimeGM(&TM);
if (RetTime!=-1)
return RetTime;
else
throw FormatException("DateTime is invalid");
}
long long Header::GetLongLong() const
{
char *EndPtr;
#ifdef _MSC_VER
long long RetVal=_strtoi64(Value,&EndPtr,10);
#else
long long RetVal=strtoll(Value,&EndPtr,10);
#endif
if (EndPtr!=Value)
return RetVal;
else
throw FormatException("Cannot parse LongLong value");
}
unsigned long long Header::GetULongLong() const
{
char *EndPtr;
#ifdef _MSC_VER
unsigned long long RetVal=_strtoui64(Value,&EndPtr,10);
#else
unsigned long long RetVal=strtoull(Value,&EndPtr,10);
#endif
if (EndPtr!=Value)
return RetVal;
else
throw FormatException("Cannot parse ULongLong value");
}
HEADERNAME Header::ParseHeader(const char *Name)
{
boost::unordered_map<std::string,HEADERNAME>::const_iterator FindI=HeaderNameMap.find(Name);
if (FindI!=HeaderNameMap.end())
return FindI->second;
else
return HN_UNKNOWN;
}
const std::string &Header::GetHeaderName(HEADERNAME Name)
{
switch (Name)
{
case HN_HOST: { static const std::string HeaderStr("host"); return HeaderStr; }
case HN_CONNECTION: { static const std::string HeaderStr("connection"); return HeaderStr; }
case HN_CONTENT_DISPOSITION: { static const std::string HeaderStr("content-disposition"); return HeaderStr; }
case HN_CONTENT_TYPE: { static const std::string HeaderStr("content-type"); return HeaderStr; }
case HN_CONTENT_LENGTH: { static const std::string HeaderStr("content-length"); return HeaderStr; }
case HN_CONTENT_ENCODING: { static const std::string HeaderStr("content-encoding"); return HeaderStr; }
case HN_USER_AGENT: { static const std::string HeaderStr("user-agent"); return HeaderStr; }
case HN_IF_MOD_SINCE: { static const std::string HeaderStr("if-modified-since"); return HeaderStr; }
case HH_ORIGIN: { static const std::string HeaderStr("origin"); return HeaderStr; }
case HH_UPGRADE: { static const std::string HeaderStr("upgrade"); return HeaderStr; }
case HH_SEC_WEBSOCKET_KEY: { static const std::string HeaderStr("sec-websocket-key"); return HeaderStr; }
case HH_SEC_WEBSCOKET_VERSION: { static const std::string HeaderStr("sec-websocket-version"); return HeaderStr; }
case HH_SEC_WEBSOCKET_PROTOCOL: { static const std::string HeaderStr("sec-websocket-protocol"); return HeaderStr; }
case HN_LAST_MODIFIED: { static const std::string HeaderStr("last-modified"); return HeaderStr; }
case HN_LOCATION: { static const std::string HeaderStr("location"); return HeaderStr; }
case HH_SEC_WEBSOCKET_ACCEPT: { static const std::string HeaderStr("sec-websocket-accept"); return HeaderStr; }
default: { static const std::string HeaderStr(""); return HeaderStr; }
}
}
char *Header::ExtractHeader(char *LineBegin, char *LineEnd, char **OutName, char **OutValue)
{
*OutName=LineBegin;
*OutValue=nullptr;
while (LineBegin!=LineEnd)
{
char CurrVal=*LineBegin;
if ((CurrVal>='A') && (CurrVal<='Z'))
*LineBegin=CurrVal-'A'+'a';
else if (CurrVal==':')
{
*LineBegin='\0';
LineBegin++;
break;
}
LineBegin++;
}
while (LineBegin!=LineEnd)
{
if (*LineBegin!=' ')
{
*OutValue=LineBegin;
break;
}
else
LineBegin++;
}
while (LineBegin!=LineEnd)
{
if (*LineBegin=='\r')
{
*LineBegin++='\0';
return LineBegin;
}
else
LineBegin++;
}
return nullptr;
}
void Header::FormatDateTime(time_t Timestamp, char *TargetBuff)
{
tm TM;
if (!UD::TimeUtils::GMTime(&Timestamp,&TM))
strftime(TargetBuff,30,"%a, %d %b %Y %H:%M:%S GMT",&TM);
else
*TargetBuff='\0';
}
bool Header::InitHeaderNameMap()
{
for (unsigned int x=HN_UNKNOWN + 1; x!=HN_NOTUSED; ++x)
AddToHeaderMap((HEADERNAME)x);
return true;
}
<commit_msg>Header::GetContentType: application/x-www-form-urlencoded parse fix<commit_after>#include "Header.h"
#include "Common/StringUtils.h"
#include "Common/TimeUtils.h"
using namespace HTTP;
/**Parses a string containing key=value pairs in HTTP header format. Supports value quoting, without quote escape.
Sample input stuff; key1=value1; key2="value2"
@param ParamConsumerType A functor with the following signature:
Func(const CharType *KeyBegin, const CharType *KeyEnd, const CharType *ValueBegin, const CharType *ValueEnd)
Note that ValueBegin and ValueEnd can be nullptr, if the given key
*/
template<class ParamConsumerType, class CharType, CharType Separator>
void ParseDelimitedKeyValue(const CharType *Source, ParamConsumerType Consumer)
{
const CharType *CurrPos=Source;
const CharType *KeyBegin=NULL, *KeyEnd=NULL;
const CharType *ValueBegin=NULL;
enum PARSE_STATE
{
PS_ZERO, //Searching for key.
PS_KEY, //Searching for key end.
PS_SEPSEARCH, //Searching for Separator.
PS_VALSEARCH, //Searching for value.
PS_VAL, //Searching for value end.
PS_QUOTEDVAL, //Searching for value end in quoted value.
} CurrState=PS_ZERO;
CharType CurrVal;
while (true)
{
CurrVal=*CurrPos;
if (!CurrVal)
break;
switch (CurrState)
{
case PS_ZERO:
if ((!UD::StringUtils::IsWS(CurrVal)) && (CurrVal!=';'))
{
KeyBegin=CurrPos;
CurrState=PS_KEY;
}
break;
case PS_KEY:
if (UD::StringUtils::IsWS(CurrVal))
{
KeyEnd=CurrPos;
CurrState=PS_SEPSEARCH;
}
else if (CurrVal==Separator)
{
KeyEnd=CurrPos;
CurrState=PS_VALSEARCH;
}
else if (CurrVal==';')
{
Consumer(KeyBegin,CurrPos,nullptr,nullptr);
CurrState=PS_ZERO;
}
break;
case PS_SEPSEARCH:
if (CurrVal==Separator)
CurrState=PS_VALSEARCH;
else if (CurrVal==';')
{
Consumer(KeyBegin,KeyEnd,nullptr,nullptr);
CurrState=PS_ZERO;
}
else if (!UD::StringUtils::IsWS(CurrVal))
{
//This is something weird, like: "Key1 Key2...". Let's skip Key1, and start again from Key2.
KeyBegin=CurrPos;
CurrState=PS_KEY;
}
break;
case PS_VALSEARCH:
if (!UD::StringUtils::IsWS(CurrVal))
{
ValueBegin=CurrPos;
if (CurrVal=='"')
CurrState=PS_QUOTEDVAL;
else
CurrState=PS_VAL;
}
else if (UD::StringUtils::IsNewLine(CurrVal))
{
//Empty value.
Consumer(KeyBegin,KeyEnd,CurrPos,CurrPos);
CurrState=PS_ZERO;
}
break;
case PS_VAL:
if ((UD::StringUtils::IsWS(CurrVal)) || (CurrVal==';'))
{
//End of value.
Consumer(KeyBegin,KeyEnd,ValueBegin,CurrPos);
CurrState=PS_ZERO;
}
break;
case PS_QUOTEDVAL:
if (CurrVal=='"')
{
//End of quoted value (ValueBegin points to the '"').
Consumer(KeyBegin,KeyEnd,ValueBegin+1,CurrPos);
CurrState=PS_ZERO;
}
break;
default:
break;
}
CurrPos++;
}
//We might have some work left.
switch (CurrState)
{
case PS_VAL:
//Output the last value.
Consumer(KeyBegin,KeyEnd,ValueBegin,CurrPos);
break;
case PS_QUOTEDVAL:
//Output the last value (quoted, but quote not closed).
Consumer(KeyBegin,KeyEnd,ValueBegin+1,CurrPos);
break;
default:
break;
}
}
template<class ParamConsumerType>
inline void ParseDelimitedKeyValue(const char *Source, ParamConsumerType Consumer) { ParseDelimitedKeyValue<ParamConsumerType,char,'='>(Source,Consumer); }
struct SingleKeyExtractor
{
SingleKeyExtractor(const std::string &KeyName, std::string &ValTargetStr) : Key(KeyName), Target(ValTargetStr)
{ }
void operator()(const char *KeyBegin, const char *KeyEnd, const char *ValueBegin, const char *ValueEnd)
{
if ((ValueBegin) && (UD::StringUtils::IsEqual(Key,KeyBegin,KeyEnd)))
Target.assign(ValueBegin,ValueEnd);
}
private:
const std::string &Key;
std::string &Target;
};
struct ContentDisposExtractor
{
ContentDisposExtractor(std::string &NameStr, std::string &FNStr) : NameTarget(NameStr), FNTarget(FNStr)
{ }
void operator()(const char *KeyBegin, const char *KeyEnd, const char *ValueBegin, const char *ValueEnd)
{
if (ValueBegin)
{
if (UD::StringUtils::IsEqual(NameKey,KeyBegin,KeyEnd))
NameTarget.assign(ValueBegin,ValueEnd);
else if (UD::StringUtils::IsEqual(FNKey,KeyBegin,KeyEnd))
FNTarget.assign(ValueBegin,ValueEnd);
}
}
private:
static const std::string NameKey, FNKey;
std::string &NameTarget, &FNTarget;
};
const std::string ContentDisposExtractor::NameKey="name", ContentDisposExtractor::FNKey="filename";
const std::string Header::BoundaryParamName("boundary");
boost::unordered_map<std::string,HEADERNAME> Header::HeaderNameMap;
bool Header::IsHeaderNameInit=Header::InitHeaderNameMap();
Header::Header(char *LineBegin, char *LineEnd)
{
if (ExtractHeader(LineBegin,LineEnd,(char **)&Name,(char **)&Value))
IntName=ParseHeader(Name);
else
IntName=HN_UNKNOWN;
}
Header::Header(char *LineBegin, char *LineEnd, SkipParseOption) : IntName(HN_UNKNOWN)
{
ExtractHeader(LineBegin,LineEnd,(char **)&Name,(char **)&Value);
}
CONTENTTYPE Header::GetContentType(std::string &OutBoundary) const
{
if (IntName!=HN_CONTENT_TYPE)
return CT_UNKNOWN;
if (const char *SCPos=strchr(Value,';'))
{
if (UD::StringUtils::CmpI("multipart/form-data",Value,SCPos)==0)
{
OutBoundary.clear();
ParseDelimitedKeyValue(SCPos,SingleKeyExtractor(BoundaryParamName,OutBoundary));
return !OutBoundary.empty() ? CT_FORM_MULTIPART : CT_UNKNOWN;
}
else if (UD::StringUtils::CmpI("application/x-www-form-urlencoded",Value,SCPos)==0)
return CT_URL_ENCODED;
}
else
{
if (UD::StringUtils::CmpI(Value,"application/x-www-form-urlencoded")==0)
return CT_URL_ENCODED;
}
return CT_UNKNOWN;
}
void Header::ParseContentDisposition(std::string &OutName, std::string &OutFileName) const
{
if (IntName==HN_CONTENT_DISPOSITION)
ParseDelimitedKeyValue(Value,ContentDisposExtractor(OutName,OutFileName));
else
{
OutName.clear();
OutFileName.clear();
}
}
bool Header::IsConnectionClose() const
{
return strcmp(Value,"close")==0;
}
time_t Header::GetDateTime() const
{
// 0 1 2
// 01234567890123456789012345678
//Sample RFC 1123 date: "Sun, 06 Nov 1994 08:49:37 GMT", strlen: 29
//WDay values: "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun"
//Month values: "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
if (strlen(Value)!=DateStringLength)
throw FormatException("DateTime has invalid length");
tm TM;
TM.tm_isdst=0; TM.tm_wday=0; TM.tm_yday=0;
TM.tm_mday=atoi(Value + 5);
TM.tm_year=atoi(Value + 12) - 1900;
TM.tm_hour=atoi(Value + 17);
TM.tm_min=atoi(Value + 20);
TM.tm_sec=atoi(Value + 23);
TM.tm_mon=-1;
switch (*(Value + 8))
{
case 'A': //Apr, Aug
if (*(Value + 9)=='p')
TM.tm_mon=3; //Apr
else if (*(Value + 9)=='u')
TM.tm_mon=7; //Aug
break;
case 'D': //Dec
TM.tm_mon=11;
break;
case 'F': //Feb
TM.tm_mon=2;
break;
case 'J': //Jan, Jun, Jul
if (*(Value + 9)=='a')
TM.tm_mon=0; //Jan
else if (*(Value + 10)=='l')
TM.tm_mon=6; //Jul
else if (*(Value + 10)=='n')
TM.tm_mon=5; //Jun
break;
case 'M': //Mar, May
if (*(Value + 10)=='r')
TM.tm_mon=2; //Mar
else if (*(Value + 10)=='y')
TM.tm_mon=4; //May
break;
case 'N': //Nov
TM.tm_mon=10;
break;
case 'O': //Oct
TM.tm_mon=9;
break;
case 'S': //Sep
TM.tm_mon=8;
break;
}
if ((TM.tm_year==0) || (TM.tm_mon==1))
throw FormatException("DateTime is invalid");
time_t RetTime=UD::TimeUtils::TimeGM(&TM);
if (RetTime!=-1)
return RetTime;
else
throw FormatException("DateTime is invalid");
}
long long Header::GetLongLong() const
{
char *EndPtr;
#ifdef _MSC_VER
long long RetVal=_strtoi64(Value,&EndPtr,10);
#else
long long RetVal=strtoll(Value,&EndPtr,10);
#endif
if (EndPtr!=Value)
return RetVal;
else
throw FormatException("Cannot parse LongLong value");
}
unsigned long long Header::GetULongLong() const
{
char *EndPtr;
#ifdef _MSC_VER
unsigned long long RetVal=_strtoui64(Value,&EndPtr,10);
#else
unsigned long long RetVal=strtoull(Value,&EndPtr,10);
#endif
if (EndPtr!=Value)
return RetVal;
else
throw FormatException("Cannot parse ULongLong value");
}
HEADERNAME Header::ParseHeader(const char *Name)
{
boost::unordered_map<std::string,HEADERNAME>::const_iterator FindI=HeaderNameMap.find(Name);
if (FindI!=HeaderNameMap.end())
return FindI->second;
else
return HN_UNKNOWN;
}
const std::string &Header::GetHeaderName(HEADERNAME Name)
{
switch (Name)
{
case HN_HOST: { static const std::string HeaderStr("host"); return HeaderStr; }
case HN_CONNECTION: { static const std::string HeaderStr("connection"); return HeaderStr; }
case HN_CONTENT_DISPOSITION: { static const std::string HeaderStr("content-disposition"); return HeaderStr; }
case HN_CONTENT_TYPE: { static const std::string HeaderStr("content-type"); return HeaderStr; }
case HN_CONTENT_LENGTH: { static const std::string HeaderStr("content-length"); return HeaderStr; }
case HN_CONTENT_ENCODING: { static const std::string HeaderStr("content-encoding"); return HeaderStr; }
case HN_USER_AGENT: { static const std::string HeaderStr("user-agent"); return HeaderStr; }
case HN_IF_MOD_SINCE: { static const std::string HeaderStr("if-modified-since"); return HeaderStr; }
case HH_ORIGIN: { static const std::string HeaderStr("origin"); return HeaderStr; }
case HH_UPGRADE: { static const std::string HeaderStr("upgrade"); return HeaderStr; }
case HH_SEC_WEBSOCKET_KEY: { static const std::string HeaderStr("sec-websocket-key"); return HeaderStr; }
case HH_SEC_WEBSCOKET_VERSION: { static const std::string HeaderStr("sec-websocket-version"); return HeaderStr; }
case HH_SEC_WEBSOCKET_PROTOCOL: { static const std::string HeaderStr("sec-websocket-protocol"); return HeaderStr; }
case HN_LAST_MODIFIED: { static const std::string HeaderStr("last-modified"); return HeaderStr; }
case HN_LOCATION: { static const std::string HeaderStr("location"); return HeaderStr; }
case HH_SEC_WEBSOCKET_ACCEPT: { static const std::string HeaderStr("sec-websocket-accept"); return HeaderStr; }
default: { static const std::string HeaderStr(""); return HeaderStr; }
}
}
char *Header::ExtractHeader(char *LineBegin, char *LineEnd, char **OutName, char **OutValue)
{
*OutName=LineBegin;
*OutValue=nullptr;
while (LineBegin!=LineEnd)
{
char CurrVal=*LineBegin;
if ((CurrVal>='A') && (CurrVal<='Z'))
*LineBegin=CurrVal-'A'+'a';
else if (CurrVal==':')
{
*LineBegin='\0';
LineBegin++;
break;
}
LineBegin++;
}
while (LineBegin!=LineEnd)
{
if (*LineBegin!=' ')
{
*OutValue=LineBegin;
break;
}
else
LineBegin++;
}
while (LineBegin!=LineEnd)
{
if (*LineBegin=='\r')
{
*LineBegin++='\0';
return LineBegin;
}
else
LineBegin++;
}
return nullptr;
}
void Header::FormatDateTime(time_t Timestamp, char *TargetBuff)
{
tm TM;
if (!UD::TimeUtils::GMTime(&Timestamp,&TM))
strftime(TargetBuff,30,"%a, %d %b %Y %H:%M:%S GMT",&TM);
else
*TargetBuff='\0';
}
bool Header::InitHeaderNameMap()
{
for (unsigned int x=HN_UNKNOWN + 1; x!=HN_NOTUSED; ++x)
AddToHeaderMap((HEADERNAME)x);
return true;
}
<|endoftext|>
|
<commit_before>#include <QtWidgets>
#include "codeeditor.h"
void
CodeEditor::initUI(void)
{
QFont font("Courier New");
font.setStyleHint(QFont::Monospace);
setFont(font);
const int tabStop = 2; // 4 characters
QFontMetrics metrics(font);
setTabStopWidth(tabStop * metrics.width(' '));
lineNumberArea = new LineNumberArea(this);
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
updateLineNumberAreaWidth(0);
highlightCurrentLine();
highlighter = new Highlighter(document());
QTextCursor cursor(textCursor());
cursor.movePosition(QTextCursor::Start);
setTextCursor(cursor);
ensureCursorVisible();
setFocus();
}
CodeEditor::CodeEditor(QFile& file, QWidget *parent) :
QPlainTextEdit(parent)
{
initUI();
if (file.isOpen()) {
setPlainText(file.readAll());
filepath = QFileInfo(file).absoluteFilePath();
filename = QFileInfo(file).fileName();
} else {
filepath = "";
filename = "Untitled";
}
connect(document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(replaceTabs(int,int,int)));
}
void CodeEditor::replaceTabs(int pos,int,int add)
{
if (add>0) {
QTextCursor cursor(document());
cursor.setPosition(pos);
cursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,add);
QString sel = cursor.selectedText();
if (sel.indexOf('\t')!=-1) {
sel = sel.replace('\t'," ");
cursor.insertText(sel);
}
}
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
return space;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::yellow).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
BracketData* bd = static_cast<BracketData*>(textCursor().block().userData());
if (bd) {
QVector<Bracket>& brackets = bd->brackets;
int pos = textCursor().block().position();
for (int i=0; i<brackets.size(); i++) {
int curPos = textCursor().position()-textCursor().block().position();
Bracket& b = brackets[i];
int parenPos0 = -1;
int parenPos1 = -1;
int errPos = -1;
if (b.pos == curPos-1 && (b.b == '(' || b.b == '{' || b.b == '[')) {
parenPos1 = matchLeft(textCursor().block(), b.b, i+1, 0);
if (parenPos1 != -1) {
parenPos0 = pos+b.pos;
} else {
errPos = pos+b.pos;
}
} else if (b.pos == curPos-1 && (b.b == ')' || b.b == '}' || b.b == ']')) {
parenPos0 = matchRight(textCursor().block(), b.b, i-1, 0);
if (parenPos0 != -1) {
parenPos1 = pos+b.pos;
} else {
errPos = pos+b.pos;
}
}
if (parenPos0 != -1 && parenPos1 != -1) {
QTextEdit::ExtraSelection sel;
QTextCharFormat format = sel.format;
format.setBackground(Qt::green);
sel.format = format;
QTextCursor cursor = textCursor();
cursor.setPosition(parenPos0);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
sel.cursor = cursor;
extraSelections.append(sel);
cursor.setPosition(parenPos1);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
sel.cursor = cursor;
extraSelections.append(sel);
}
if (errPos != -1) {
QTextEdit::ExtraSelection sel;
QTextCharFormat format = sel.format;
format.setBackground(Qt::red);
sel.format = format;
QTextCursor cursor = textCursor();
cursor.setPosition(errPos);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
sel.cursor = cursor;
extraSelections.append(sel);
}
}
}
setExtraSelections(extraSelections);
}
int CodeEditor::matchLeft(QTextBlock block, QChar b, int i, int nLeft)
{
QChar match;
switch (b.toLatin1()) {
case '(' : match = ')'; break;
case '{' : match = '}'; break;
case '[' : match = ']'; break;
default: break; // should not happen
}
while (block.isValid()) {
BracketData* bd = static_cast<BracketData*>(block.userData());
QVector<Bracket>& brackets = bd->brackets;
int docPos = block.position();
for (; i<brackets.size(); i++) {
Bracket& b = brackets[i];
if (b.b=='(' || b.b=='{' || b.b=='[') {
nLeft++;
} else if (b.b==match && nLeft==0) {
return docPos+b.pos;
} else {
nLeft--;
}
}
block = block.next();
i = 0;
}
return -1;
}
int CodeEditor::matchRight(QTextBlock block, QChar b, int i, int nRight)
{
QChar match;
switch (b.toLatin1()) {
case ')' : match = '('; break;
case '}' : match = '{'; break;
case ']' : match = '['; break;
default: break; // should not happen
}
while (block.isValid()) {
BracketData* bd = static_cast<BracketData*>(block.userData());
QVector<Bracket>& brackets = bd->brackets;
if (i==-1)
i = brackets.size()-1;
int docPos = block.position();
for (; i>-1 && brackets.size()>0; i--) {
Bracket& b = brackets[i];
if (b.b==')' || b.b=='}' || b.b==']') {
nRight++;
} else if (b.b==match && nRight==0) {
return docPos+b.pos;
} else {
nRight--;
}
}
block = block.previous();
i = -1;
}
return -1;
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), Qt::lightGray);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
<commit_msg>Do not replace tabs for now (messes up the undo stack)<commit_after>#include <QtWidgets>
#include "codeeditor.h"
void
CodeEditor::initUI(void)
{
QFont font("Courier New");
font.setStyleHint(QFont::Monospace);
setFont(font);
const int tabStop = 2; // 4 characters
QFontMetrics metrics(font);
setTabStopWidth(tabStop * metrics.width(' '));
lineNumberArea = new LineNumberArea(this);
connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
updateLineNumberAreaWidth(0);
highlightCurrentLine();
highlighter = new Highlighter(document());
QTextCursor cursor(textCursor());
cursor.movePosition(QTextCursor::Start);
setTextCursor(cursor);
ensureCursorVisible();
setFocus();
}
CodeEditor::CodeEditor(QFile& file, QWidget *parent) :
QPlainTextEdit(parent)
{
initUI();
if (file.isOpen()) {
setPlainText(file.readAll());
filepath = QFileInfo(file).absoluteFilePath();
filename = QFileInfo(file).fileName();
} else {
filepath = "";
filename = "Untitled";
}
// connect(document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(replaceTabs(int,int,int)));
}
void CodeEditor::replaceTabs(int pos,int,int add)
{
if (add>0) {
QTextCursor cursor(document());
cursor.setPosition(pos);
cursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,add);
QString sel = cursor.selectedText();
if (sel.indexOf('\t')!=-1) {
sel = sel.replace('\t'," ");
cursor.insertText(sel);
}
}
}
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while (max >= 10) {
max /= 10;
++digits;
}
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
return space;
}
void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}
void CodeEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void CodeEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void CodeEditor::highlightCurrentLine()
{
QList<QTextEdit::ExtraSelection> extraSelections;
if (!isReadOnly()) {
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor(Qt::yellow).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();
extraSelections.append(selection);
}
BracketData* bd = static_cast<BracketData*>(textCursor().block().userData());
if (bd) {
QVector<Bracket>& brackets = bd->brackets;
int pos = textCursor().block().position();
for (int i=0; i<brackets.size(); i++) {
int curPos = textCursor().position()-textCursor().block().position();
Bracket& b = brackets[i];
int parenPos0 = -1;
int parenPos1 = -1;
int errPos = -1;
if (b.pos == curPos-1 && (b.b == '(' || b.b == '{' || b.b == '[')) {
parenPos1 = matchLeft(textCursor().block(), b.b, i+1, 0);
if (parenPos1 != -1) {
parenPos0 = pos+b.pos;
} else {
errPos = pos+b.pos;
}
} else if (b.pos == curPos-1 && (b.b == ')' || b.b == '}' || b.b == ']')) {
parenPos0 = matchRight(textCursor().block(), b.b, i-1, 0);
if (parenPos0 != -1) {
parenPos1 = pos+b.pos;
} else {
errPos = pos+b.pos;
}
}
if (parenPos0 != -1 && parenPos1 != -1) {
QTextEdit::ExtraSelection sel;
QTextCharFormat format = sel.format;
format.setBackground(Qt::green);
sel.format = format;
QTextCursor cursor = textCursor();
cursor.setPosition(parenPos0);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
sel.cursor = cursor;
extraSelections.append(sel);
cursor.setPosition(parenPos1);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
sel.cursor = cursor;
extraSelections.append(sel);
}
if (errPos != -1) {
QTextEdit::ExtraSelection sel;
QTextCharFormat format = sel.format;
format.setBackground(Qt::red);
sel.format = format;
QTextCursor cursor = textCursor();
cursor.setPosition(errPos);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
sel.cursor = cursor;
extraSelections.append(sel);
}
}
}
setExtraSelections(extraSelections);
}
int CodeEditor::matchLeft(QTextBlock block, QChar b, int i, int nLeft)
{
QChar match;
switch (b.toLatin1()) {
case '(' : match = ')'; break;
case '{' : match = '}'; break;
case '[' : match = ']'; break;
default: break; // should not happen
}
while (block.isValid()) {
BracketData* bd = static_cast<BracketData*>(block.userData());
QVector<Bracket>& brackets = bd->brackets;
int docPos = block.position();
for (; i<brackets.size(); i++) {
Bracket& b = brackets[i];
if (b.b=='(' || b.b=='{' || b.b=='[') {
nLeft++;
} else if (b.b==match && nLeft==0) {
return docPos+b.pos;
} else {
nLeft--;
}
}
block = block.next();
i = 0;
}
return -1;
}
int CodeEditor::matchRight(QTextBlock block, QChar b, int i, int nRight)
{
QChar match;
switch (b.toLatin1()) {
case ')' : match = '('; break;
case '}' : match = '{'; break;
case ']' : match = '['; break;
default: break; // should not happen
}
while (block.isValid()) {
BracketData* bd = static_cast<BracketData*>(block.userData());
QVector<Bracket>& brackets = bd->brackets;
if (i==-1)
i = brackets.size()-1;
int docPos = block.position();
for (; i>-1 && brackets.size()>0; i--) {
Bracket& b = brackets[i];
if (b.b==')' || b.b=='}' || b.b==']') {
nRight++;
} else if (b.b==match && nRight==0) {
return docPos+b.pos;
} else {
nRight--;
}
}
block = block.previous();
i = -1;
}
return -1;
}
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), Qt::lightGray);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
<|endoftext|>
|
<commit_before>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file JavascriptModule.cpp
* @brief Enables Javascript execution and scripting in Naali.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "JavascriptModule.h"
#include "ScriptMetaTypeDefines.h"
#include "JavascriptInstance.h"
#include "AssetAPI.h"
#include "EC_Script.h"
#include "ScriptAssetFactory.h"
#include "EC_DynamicComponent.h"
#include "EventManager.h"
#include "SceneManager.h"
#include "Input.h"
#include "UiServiceInterface.h"
#include "ISoundService.h"
#include "Frame.h"
#include "Console.h"
#include "ConsoleCommandServiceInterface.h"
#include "NaaliCoreTypeDefines.h"
#include <QtScript>
Q_SCRIPT_DECLARE_QMETAOBJECT(QPushButton, QWidget*) ///@todo Remove? This is already done in ScriptMetaTypeDefines.cpp
#include "MemoryLeakCheck.h"
std::string JavascriptModule::type_name_static_ = "Javascript";
JavascriptModule *javascriptModuleInstance_ = 0;
JavascriptModule::JavascriptModule() :
IModule(type_name_static_),
engine(new QScriptEngine(this))
{
}
JavascriptModule::~JavascriptModule()
{
}
void JavascriptModule::Load()
{
DECLARE_MODULE_EC(EC_Script);
DECLARE_MODULE_EC(EC_DynamicComponent);
framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new ScriptAssetFactory));
}
void JavascriptModule::PreInitialize()
{
}
void JavascriptModule::Initialize()
{
connect(GetFramework(), SIGNAL(SceneAdded(const QString&)), this, SLOT(SceneAdded(const QString&)));
LogInfo("Module " + Name() + " initializing...");
assert(!javascriptModuleInstance_);
javascriptModuleInstance_ = this;
// Register ourselves as javascript scripting service.
boost::shared_ptr<JavascriptModule> jsmodule = framework_->GetModuleManager()->GetModule<JavascriptModule>().lock();
boost::weak_ptr<ScriptServiceInterface> service = boost::dynamic_pointer_cast<ScriptServiceInterface>(jsmodule);
framework_->GetServiceManager()->RegisterService(Service::ST_JavascriptScripting, service);
engine->globalObject().setProperty("print", engine->newFunction(Print));
QScriptValue objectbutton= engine->scriptValueFromQMetaObject<QPushButton>();
engine->globalObject().setProperty("QPushButton", objectbutton);
JavascriptModule::RunScript("jsmodules/lib/json2.js");
RunString("print('Hello from qtscript');");
frameworkEventCategory_ = framework_->GetEventManager()->QueryEventCategory("Framework");
}
void JavascriptModule::PostInitialize()
{
RegisterNaaliCoreMetaTypes();
RegisterConsoleCommand(Console::CreateCommand(
"JsExec", "Execute given code in the embedded Javascript interpreter. Usage: JsExec(mycodestring)",
Console::Bind(this, &JavascriptModule::ConsoleRunString)));
RegisterConsoleCommand(Console::CreateCommand(
"JsLoad", "Execute a javascript file. JsLoad(myjsfile.js)",
Console::Bind(this, &JavascriptModule::ConsoleRunFile)));
RegisterConsoleCommand(Console::CreateCommand(
"JsReloadScripts", "Reloads and re-executes startup scripts.",
Console::Bind(this, &JavascriptModule::ConsoleReloadScripts)));
// Initialize startup scripts
LoadStartupScripts();
}
void JavascriptModule::Uninitialize()
{
UnloadStartupScripts();
}
void JavascriptModule::Update(f64 frametime)
{
RESETPROFILER;
}
bool JavascriptModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data)
{
if (category_id == frameworkEventCategory_)
{
if (event_id == Foundation::PROGRAM_OPTIONS)
{
Foundation::ProgramOptionsEvent *po_event = static_cast<Foundation::ProgramOptionsEvent*>(data);
if (po_event->options.count("run"))
{
commandLineStartupScript_ = po_event->options["run"].as<std::string>();
JavascriptInstance* jsInstance = new JavascriptInstance(commandLineStartupScript_.c_str(), this);
PrepareScriptInstance(jsInstance);
startupScripts_.push_back(jsInstance);
jsInstance->Run();
}
}
}
return false;
}
Console::CommandResult JavascriptModule::ConsoleRunString(const StringVector ¶ms)
{
if (params.size() != 1)
return Console::ResultFailure("Usage: JsExec(print 1 + 1)");
JavascriptModule::RunString(QString::fromStdString(params[0]));
return Console::ResultSuccess();
}
Console::CommandResult JavascriptModule::ConsoleRunFile(const StringVector ¶ms)
{
if (params.size() != 1)
return Console::ResultFailure("Usage: JsLoad(myfile.js)");
JavascriptModule::RunScript(QString::fromStdString(params[0]));
return Console::ResultSuccess();
}
Console::CommandResult JavascriptModule::ConsoleReloadScripts(const StringVector ¶ms)
{
LoadStartupScripts();
return Console::ResultSuccess();
}
JavascriptModule *JavascriptModule::GetInstance()
{
assert(javascriptModuleInstance_);
return javascriptModuleInstance_;
}
void JavascriptModule::RunString(const QString &codestr, const QVariantMap &context)
{
QMapIterator<QString, QVariant> i(context);
while (i.hasNext())
{
i.next();
engine->globalObject().setProperty(i.key(), engine->newQObject(i.value().value<QObject*>()));
}
engine->evaluate(codestr);
}
void JavascriptModule::RunScript(const QString &scriptFileName)
{
QFile scriptFile(scriptFileName);
scriptFile.open(QIODevice::ReadOnly);
engine->evaluate(scriptFile.readAll(), scriptFileName);
scriptFile.close();
}
void JavascriptModule::SceneAdded(const QString &name)
{
Scene::ScenePtr scene = GetFramework()->GetScene(name);
connect(scene.get(), SIGNAL(ComponentAdded(Scene::Entity*, IComponent*, AttributeChange::Type)),
SLOT(ComponentAdded(Scene::Entity*, IComponent*, AttributeChange::Type)));
connect(scene.get(), SIGNAL(ComponentRemoved(Scene::Entity*, IComponent*, AttributeChange::Type)),
SLOT(ComponentRemoved(Scene::Entity*, IComponent*, AttributeChange::Type)));
}
void JavascriptModule::ScriptAssetChanged(ScriptAssetPtr newScript)
{
PROFILE(JSModule_ScriptAssetChanged);
EC_Script *sender = dynamic_cast<EC_Script*>(this->sender());
assert(sender && "JavascriptModule::ScriptAssetChanged needs to be invoked from EC_Script!");
if (!sender)
return;
// First clean up any previous running script from EC_Script, if any exists.
// (but only clean up scripts of our script type, other engines can clean up theirs)
if (dynamic_cast<JavascriptInstance*>(sender->GetScriptInstance()))
sender->SetScriptInstance(0);
// EC_Script can host scripts of different types, and all script engines listen to asset changes.
// First we'll need to validate whether the user even specified a script file that's QtScript.
QString scriptType = sender->type.Get().trimmed().toLower();
if (scriptType != "js" && scriptType.length() > 0)
return; // The user enforced a foreign script type using the EC_Script type field.
if (newScript->Name().endsWith(".js") || scriptType == "js") // We're positively using QtScript.
{
JavascriptInstance *jsInstance = new JavascriptInstance(newScript, this);
jsInstance->SetOwnerComponent(sender->GetSharedPtr());
sender->SetScriptInstance(jsInstance);
// Register all core APIs and names to this script engine.
PrepareScriptInstance(jsInstance, sender);
if (sender->runOnLoad.Get())
sender->Run();
}
}
void JavascriptModule::ComponentAdded(Scene::Entity* entity, IComponent* comp, AttributeChange::Type change)
{
if (comp->TypeName() == EC_Script::TypeNameStatic())
connect(comp, SIGNAL(ScriptAssetChanged(ScriptAssetPtr)), this, SLOT(ScriptAssetChanged(ScriptAssetPtr)), Qt::UniqueConnection);
}
void JavascriptModule::ComponentRemoved(Scene::Entity* entity, IComponent* comp, AttributeChange::Type change)
{
if (comp->TypeName() == EC_Script::TypeNameStatic())
disconnect(comp, SIGNAL(ScriptAssetChanged(ScriptAssetPtr)), this, SLOT(ScriptAssetChanged(ScriptAssetPtr)));
}
void JavascriptModule::LoadStartupScripts()
{
UnloadStartupScripts();
std::string path = "./jsmodules/startup";
std::vector<std::string> scripts;
try
{
boost::filesystem::directory_iterator i(path);
boost::filesystem::directory_iterator end_iter;
while (i != end_iter)
{
if (boost::filesystem::is_regular_file(i->status()))
{
std::string ext = i->path().extension();
boost::algorithm::to_lower(ext);
if (ext == ".js")
scripts.push_back(i->path().string());
}
++i;
}
}
catch (std::exception &/*e*/)
{
}
// Create a script instance for each of the files, register services for it and try to run.
for (uint i = 0; i < scripts.size(); ++i)
{
JavascriptInstance* jsInstance = new JavascriptInstance(QString::fromStdString(scripts[i]), this);
PrepareScriptInstance(jsInstance);
startupScripts_.push_back(jsInstance);
jsInstance->Run();
}
}
void JavascriptModule::UnloadStartupScripts()
{
// Stop the startup scripts, if any running
for (uint i = 0; i < startupScripts_.size(); ++i)
startupScripts_[i]->Unload();
for (uint i = 0; i < startupScripts_.size(); ++i)
delete startupScripts_[i];
startupScripts_.clear();
}
void JavascriptModule::PrepareScriptInstance(JavascriptInstance* instance, EC_Script *comp)
{
static std::set<QObject*> checked;
// Register framework's dynamic properties (service objects) and the framework itself to the script engine
QList<QByteArray> properties = framework_->dynamicPropertyNames();
for (uint i = 0; i < properties.size(); ++i)
{
QString name = properties[i];
QObject* serviceobject = framework_->property(name.toStdString().c_str()).value<QObject*>();
instance->RegisterService(serviceobject, name);
if (checked.find(serviceobject) == checked.end())
{
// Check if the service object has an OnScriptEngineCreated() slot, and give it a chance to perform further actions
const QMetaObject* meta = serviceobject->metaObject();
if (meta->indexOfSlot("OnScriptEngineCreated(QScriptEngine*)") != -1)
QObject::connect(this, SIGNAL(ScriptEngineCreated(QScriptEngine*)), serviceobject, SLOT(OnScriptEngineCreated(QScriptEngine*)));
checked.insert(serviceobject);
}
}
instance->RegisterService(framework_, "framework");
instance->RegisterService(instance, "engine");
for(uint i = 0; i < properties.size(); ++i)
instance->RegisterService(framework_->property(properties[i]).value<QObject*>(), properties[i]);
if (comp)
{
// Set entity and scene that own the EC_Script component.
instance->RegisterService(comp->GetParentEntity(), "me");
instance->RegisterService(comp->GetParentEntity()->GetScene(), "scene");
}
emit ScriptEngineCreated(instance->GetEngine());
}
QScriptValue Print(QScriptContext *context, QScriptEngine *engine)
{
std::cout << "{QtScript} " << context->argument(0).toString().toStdString() << "\n";
return QScriptValue();
}
QScriptValue ScriptRunFile(QScriptContext *context, QScriptEngine *engine)
{
JavascriptModule::GetInstance()->RunScript(context->argument(0).toString());
return QScriptValue();
}
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
POCO_BEGIN_MANIFEST(IModule)
POCO_EXPORT_CLASS(JavascriptModule)
POCO_END_MANIFEST
<commit_msg>Cleaned up old test code from JavascriptModule.cpp<commit_after>/**
* For conditions of distribution and use, see copyright notice in license.txt
*
* @file JavascriptModule.cpp
* @brief Enables Javascript execution and scripting in Naali.
*/
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "JavascriptModule.h"
#include "ScriptMetaTypeDefines.h"
#include "JavascriptInstance.h"
#include "AssetAPI.h"
#include "EC_Script.h"
#include "ScriptAssetFactory.h"
#include "EC_DynamicComponent.h"
#include "EventManager.h"
#include "SceneManager.h"
#include "Input.h"
#include "UiServiceInterface.h"
#include "ISoundService.h"
#include "Frame.h"
#include "Console.h"
#include "ConsoleCommandServiceInterface.h"
#include "NaaliCoreTypeDefines.h"
#include <QtScript>
#include "MemoryLeakCheck.h"
std::string JavascriptModule::type_name_static_ = "Javascript";
JavascriptModule *javascriptModuleInstance_ = 0;
JavascriptModule::JavascriptModule() :
IModule(type_name_static_),
engine(new QScriptEngine(this))
{
}
JavascriptModule::~JavascriptModule()
{
}
void JavascriptModule::Load()
{
DECLARE_MODULE_EC(EC_Script);
DECLARE_MODULE_EC(EC_DynamicComponent);
framework_->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new ScriptAssetFactory));
}
void JavascriptModule::PreInitialize()
{
}
void JavascriptModule::Initialize()
{
connect(GetFramework(), SIGNAL(SceneAdded(const QString&)), this, SLOT(SceneAdded(const QString&)));
LogInfo("Module " + Name() + " initializing...");
assert(!javascriptModuleInstance_);
javascriptModuleInstance_ = this;
// Register ourselves as javascript scripting service.
boost::shared_ptr<JavascriptModule> jsmodule = framework_->GetModuleManager()->GetModule<JavascriptModule>().lock();
boost::weak_ptr<ScriptServiceInterface> service = boost::dynamic_pointer_cast<ScriptServiceInterface>(jsmodule);
framework_->GetServiceManager()->RegisterService(Service::ST_JavascriptScripting, service);
engine->globalObject().setProperty("print", engine->newFunction(Print));
frameworkEventCategory_ = framework_->GetEventManager()->QueryEventCategory("Framework");
}
void JavascriptModule::PostInitialize()
{
RegisterNaaliCoreMetaTypes();
RegisterConsoleCommand(Console::CreateCommand(
"JsExec", "Execute given code in the embedded Javascript interpreter. Usage: JsExec(mycodestring)",
Console::Bind(this, &JavascriptModule::ConsoleRunString)));
RegisterConsoleCommand(Console::CreateCommand(
"JsLoad", "Execute a javascript file. JsLoad(myjsfile.js)",
Console::Bind(this, &JavascriptModule::ConsoleRunFile)));
RegisterConsoleCommand(Console::CreateCommand(
"JsReloadScripts", "Reloads and re-executes startup scripts.",
Console::Bind(this, &JavascriptModule::ConsoleReloadScripts)));
// Initialize startup scripts
LoadStartupScripts();
}
void JavascriptModule::Uninitialize()
{
UnloadStartupScripts();
}
void JavascriptModule::Update(f64 frametime)
{
RESETPROFILER;
}
bool JavascriptModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data)
{
if (category_id == frameworkEventCategory_)
{
if (event_id == Foundation::PROGRAM_OPTIONS)
{
Foundation::ProgramOptionsEvent *po_event = static_cast<Foundation::ProgramOptionsEvent*>(data);
if (po_event->options.count("run"))
{
commandLineStartupScript_ = po_event->options["run"].as<std::string>();
JavascriptInstance* jsInstance = new JavascriptInstance(commandLineStartupScript_.c_str(), this);
PrepareScriptInstance(jsInstance);
startupScripts_.push_back(jsInstance);
jsInstance->Run();
}
}
}
return false;
}
Console::CommandResult JavascriptModule::ConsoleRunString(const StringVector ¶ms)
{
if (params.size() != 1)
return Console::ResultFailure("Usage: JsExec(print 1 + 1)");
JavascriptModule::RunString(QString::fromStdString(params[0]));
return Console::ResultSuccess();
}
Console::CommandResult JavascriptModule::ConsoleRunFile(const StringVector ¶ms)
{
if (params.size() != 1)
return Console::ResultFailure("Usage: JsLoad(myfile.js)");
JavascriptModule::RunScript(QString::fromStdString(params[0]));
return Console::ResultSuccess();
}
Console::CommandResult JavascriptModule::ConsoleReloadScripts(const StringVector ¶ms)
{
LoadStartupScripts();
return Console::ResultSuccess();
}
JavascriptModule *JavascriptModule::GetInstance()
{
assert(javascriptModuleInstance_);
return javascriptModuleInstance_;
}
void JavascriptModule::RunString(const QString &codestr, const QVariantMap &context)
{
QMapIterator<QString, QVariant> i(context);
while (i.hasNext())
{
i.next();
engine->globalObject().setProperty(i.key(), engine->newQObject(i.value().value<QObject*>()));
}
engine->evaluate(codestr);
}
void JavascriptModule::RunScript(const QString &scriptFileName)
{
QFile scriptFile(scriptFileName);
scriptFile.open(QIODevice::ReadOnly);
engine->evaluate(scriptFile.readAll(), scriptFileName);
scriptFile.close();
}
void JavascriptModule::SceneAdded(const QString &name)
{
Scene::ScenePtr scene = GetFramework()->GetScene(name);
connect(scene.get(), SIGNAL(ComponentAdded(Scene::Entity*, IComponent*, AttributeChange::Type)),
SLOT(ComponentAdded(Scene::Entity*, IComponent*, AttributeChange::Type)));
connect(scene.get(), SIGNAL(ComponentRemoved(Scene::Entity*, IComponent*, AttributeChange::Type)),
SLOT(ComponentRemoved(Scene::Entity*, IComponent*, AttributeChange::Type)));
}
void JavascriptModule::ScriptAssetChanged(ScriptAssetPtr newScript)
{
PROFILE(JSModule_ScriptAssetChanged);
EC_Script *sender = dynamic_cast<EC_Script*>(this->sender());
assert(sender && "JavascriptModule::ScriptAssetChanged needs to be invoked from EC_Script!");
if (!sender)
return;
// First clean up any previous running script from EC_Script, if any exists.
// (but only clean up scripts of our script type, other engines can clean up theirs)
if (dynamic_cast<JavascriptInstance*>(sender->GetScriptInstance()))
sender->SetScriptInstance(0);
// EC_Script can host scripts of different types, and all script engines listen to asset changes.
// First we'll need to validate whether the user even specified a script file that's QtScript.
QString scriptType = sender->type.Get().trimmed().toLower();
if (scriptType != "js" && scriptType.length() > 0)
return; // The user enforced a foreign script type using the EC_Script type field.
if (newScript->Name().endsWith(".js") || scriptType == "js") // We're positively using QtScript.
{
JavascriptInstance *jsInstance = new JavascriptInstance(newScript, this);
jsInstance->SetOwnerComponent(sender->GetSharedPtr());
sender->SetScriptInstance(jsInstance);
// Register all core APIs and names to this script engine.
PrepareScriptInstance(jsInstance, sender);
if (sender->runOnLoad.Get())
sender->Run();
}
}
void JavascriptModule::ComponentAdded(Scene::Entity* entity, IComponent* comp, AttributeChange::Type change)
{
if (comp->TypeName() == EC_Script::TypeNameStatic())
connect(comp, SIGNAL(ScriptAssetChanged(ScriptAssetPtr)), this, SLOT(ScriptAssetChanged(ScriptAssetPtr)), Qt::UniqueConnection);
}
void JavascriptModule::ComponentRemoved(Scene::Entity* entity, IComponent* comp, AttributeChange::Type change)
{
if (comp->TypeName() == EC_Script::TypeNameStatic())
disconnect(comp, SIGNAL(ScriptAssetChanged(ScriptAssetPtr)), this, SLOT(ScriptAssetChanged(ScriptAssetPtr)));
}
void JavascriptModule::LoadStartupScripts()
{
UnloadStartupScripts();
std::string path = "./jsmodules/startup";
std::vector<std::string> scripts;
try
{
boost::filesystem::directory_iterator i(path);
boost::filesystem::directory_iterator end_iter;
while (i != end_iter)
{
if (boost::filesystem::is_regular_file(i->status()))
{
std::string ext = i->path().extension();
boost::algorithm::to_lower(ext);
if (ext == ".js")
scripts.push_back(i->path().string());
}
++i;
}
}
catch (std::exception &/*e*/)
{
}
// Create a script instance for each of the files, register services for it and try to run.
for (uint i = 0; i < scripts.size(); ++i)
{
JavascriptInstance* jsInstance = new JavascriptInstance(QString::fromStdString(scripts[i]), this);
PrepareScriptInstance(jsInstance);
startupScripts_.push_back(jsInstance);
jsInstance->Run();
}
}
void JavascriptModule::UnloadStartupScripts()
{
// Stop the startup scripts, if any running
for (uint i = 0; i < startupScripts_.size(); ++i)
startupScripts_[i]->Unload();
for (uint i = 0; i < startupScripts_.size(); ++i)
delete startupScripts_[i];
startupScripts_.clear();
}
void JavascriptModule::PrepareScriptInstance(JavascriptInstance* instance, EC_Script *comp)
{
static std::set<QObject*> checked;
// Register framework's dynamic properties (service objects) and the framework itself to the script engine
QList<QByteArray> properties = framework_->dynamicPropertyNames();
for (uint i = 0; i < properties.size(); ++i)
{
QString name = properties[i];
QObject* serviceobject = framework_->property(name.toStdString().c_str()).value<QObject*>();
instance->RegisterService(serviceobject, name);
if (checked.find(serviceobject) == checked.end())
{
// Check if the service object has an OnScriptEngineCreated() slot, and give it a chance to perform further actions
const QMetaObject* meta = serviceobject->metaObject();
if (meta->indexOfSlot("OnScriptEngineCreated(QScriptEngine*)") != -1)
QObject::connect(this, SIGNAL(ScriptEngineCreated(QScriptEngine*)), serviceobject, SLOT(OnScriptEngineCreated(QScriptEngine*)));
checked.insert(serviceobject);
}
}
instance->RegisterService(framework_, "framework");
instance->RegisterService(instance, "engine");
for(uint i = 0; i < properties.size(); ++i)
instance->RegisterService(framework_->property(properties[i]).value<QObject*>(), properties[i]);
if (comp)
{
// Set entity and scene that own the EC_Script component.
instance->RegisterService(comp->GetParentEntity(), "me");
instance->RegisterService(comp->GetParentEntity()->GetScene(), "scene");
}
emit ScriptEngineCreated(instance->GetEngine());
}
QScriptValue Print(QScriptContext *context, QScriptEngine *engine)
{
std::cout << "{QtScript} " << context->argument(0).toString().toStdString() << "\n";
return QScriptValue();
}
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
POCO_BEGIN_MANIFEST(IModule)
POCO_EXPORT_CLASS(JavascriptModule)
POCO_END_MANIFEST
<|endoftext|>
|
<commit_before>#define CATCH_CONFIG_MAIN
#include <stdlib.h>
#include <string.h>
#include "catch.hpp"
#include <cserial.h>
#ifdef _WIN32
#define snprintf _snprintf_s
#define sprintf sprintf_s
#define strcat strcat_s
#endif
TEST_CASE("Loopback send/receive", "[tx][rx][loopback]")
{
struct cserial_port txPort, rxPort;
struct cserial_port_conf conf = {
conf.baud = 19200,
conf.parity = PARITY_NONE,
conf.csize = 8,
conf.stopbits = 1,
};
char *txDev, *rxDev;
char tx[32], rx[32];
int txLen;
int ret;
memset(tx, 0, sizeof(tx));
memset(rx, 0, sizeof(rx));
snprintf(tx, sizeof(tx), "Erich");
/* Get the device file to transmit data out. */
txDev = getenv("CSERIAL_TX");
INFO("transmitting using: " << txDev);
REQUIRE(txDev != 0);
/* Get the device file to receive data in. */
rxDev = getenv("CSERIAL_RX");
INFO("receiving using: " << rxDev);
REQUIRE(rxDev != 0);
ret = cserial_open(&txPort, &conf, txDev);
REQUIRE(ret == 0);
ret = cserial_open(&rxPort, &conf, rxDev);
REQUIRE(ret == 0);
txLen = strlen(tx);
ret = cserial_write(&txPort, tx, txLen);
REQUIRE(ret == txLen);
ret = cserial_read(&rxPort, rx, sizeof(rx));
/* We should receive everything we transmitted. */
REQUIRE(ret == txLen);
ret = cserial_close(&txPort);
ret = cserial_close(&rxPort);
REQUIRE(ret == 0);
}
<commit_msg>Fixed memory leak in unit test.<commit_after>#define CATCH_CONFIG_MAIN
#include <stdlib.h>
#include <string.h>
#include "catch.hpp"
#include <cserial.h>
#ifdef _WIN32
#define snprintf _snprintf_s
#define sprintf sprintf_s
#define strcat strcat_s
#endif
TEST_CASE("Loopback send/receive", "[tx][rx][loopback]")
{
struct cserial_port txPort, rxPort;
struct cserial_port_conf conf = {
conf.baud = 19200,
conf.parity = PARITY_NONE,
conf.csize = 8,
conf.stopbits = 1,
};
char *txDev, *rxDev;
char tx[32], rx[32];
int txLen;
int ret;
memset(tx, 0, sizeof(tx));
memset(rx, 0, sizeof(rx));
snprintf(tx, sizeof(tx), "Erich");
/* Get the device file to transmit data out. */
txDev = getenv("CSERIAL_TX");
INFO("transmitting using: " << txDev);
REQUIRE(txDev != 0);
/* Get the device file to receive data in. */
rxDev = getenv("CSERIAL_RX");
INFO("receiving using: " << rxDev);
REQUIRE(rxDev != 0);
ret = cserial_open(&txPort, &conf, txDev);
REQUIRE(ret == 0);
ret = cserial_open(&rxPort, &conf, rxDev);
REQUIRE(ret == 0);
txLen = strlen(tx);
ret = cserial_write(&txPort, tx, txLen);
REQUIRE(ret == txLen);
ret = cserial_read(&rxPort, rx, sizeof(rx));
/* We should receive everything we transmitted. */
REQUIRE(ret == txLen);
ret = cserial_close(&txPort);
ret = cserial_close(&rxPort);
REQUIRE(ret == 0);
free(txPort.device);
free(rxPort.device);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: managedframe.cpp
// Purpose: Implementation of wxExManagedFrame class.
// Author: Anton van Wezenbeek
// Created: 2010-04-11
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/wxcrt.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/defs.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/vi.h>
#if wxUSE_GUI
// Support class.
// Offers a text ctrl related to a vi object.
class wxExViTextCtrl: public wxTextCtrl
{
public:
/// Constructor. Creates empty control.
wxExViTextCtrl(
wxWindow* parent,
wxExManagedFrame* frame,
wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize);
/// Returns vi component.
wxExVi* GetVi() {return m_vi;};
/// Sets vi component.
void SetVi(wxExVi* vi);
protected:
void OnCommand(wxCommandEvent& event);
void OnEnter(wxCommandEvent& event);
void OnFocus(wxFocusEvent& event);
void OnKey(wxKeyEvent& event);
private:
wxExManagedFrame* m_Frame;
wxExVi* m_vi;
bool m_UserInput;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
EVT_UPDATE_UI_RANGE(
ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()
wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style)
: wxExFrame(parent, id, title, style)
{
m_Manager.SetManagedWindow(this);
wxExToolBar* toolBar = new wxExToolBar(this);
toolBar->AddControls();
DoAddControl(toolBar);
AddToolBarPane(toolBar, "TOOLBAR", _("Toolbar"));
AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar"));
// A vi panel starts with small static text for : or /, then
// comes the vi ctrl for getting user input.
wxPanel* panel = new wxPanel(this);
m_viTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString);
m_viTextCtrl = new wxExViTextCtrl(panel, this, wxID_ANY);
wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
sizer->AddGrowableCol(1);
sizer->Add(m_viTextPrefix, wxSizerFlags().Expand());
sizer->Add(m_viTextCtrl, wxSizerFlags().Expand());
panel->SetSizerAndFit(sizer);
AddToolBarPane(panel, "VIBAR");
m_Manager.Update();
}
wxExManagedFrame::~wxExManagedFrame()
{
m_Manager.UnInit();
}
bool wxExManagedFrame::AddToolBarPane(
wxWindow* window,
const wxString& name,
const wxString& caption)
{
wxAuiPaneInfo pane;
pane
.LeftDockable(false)
.RightDockable(false)
.Name(name);
// If the toolbar has a caption, it is at the top,
// otherwise fixed at the bottom and initially hidden.
if (!caption.empty())
{
pane
.Top()
.ToolbarPane()
.Caption(caption);
}
else
{
pane
.Bottom()
.CloseButton(false)
.Hide()
.DockFixed(true)
.Movable(false)
.CaptionVisible(false);
}
return m_Manager.AddPane(window, pane);
}
void wxExManagedFrame::GetViCommand(wxExVi* vi, const wxString& command)
{
m_viTextPrefix->SetLabel(command);
m_viTextCtrl->SetVi(vi);
m_Manager.GetPane("VIBAR").Show();
m_Manager.Update();
}
bool wxExManagedFrame::GetViCommandIsFind() const
{
return m_viTextPrefix->GetLabel() == "/" || m_viTextPrefix->GetLabel() == "?";
}
bool wxExManagedFrame::GetViCommandIsFindNext() const
{
return GetViCommandIsFind() && m_viTextPrefix->GetLabel() == "/";
}
void wxExManagedFrame::HideViBar()
{
if (m_Manager.GetPane("VIBAR").IsShown())
{
m_Manager.GetPane("VIBAR").Hide();
m_Manager.Update();
m_viTextCtrl->GetVi()->GetSTC()->SetFocus();
}
}
void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_PREFERENCES:
wxExSTC::ConfigDialog(this,
_("Editor Options"),
wxExSTC::STC_CONFIG_MODELESS |
wxExSTC::STC_CONFIG_SIMPLE |
wxExSTC::STC_CONFIG_WITH_APPLY,
event.GetId());
break;
case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;
default:
wxFAIL;
}
}
void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case ID_VIEW_FINDBAR:
event.Check(m_Manager.GetPane("FINDBAR").IsShown());
break;
case ID_VIEW_TOOLBAR:
event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
break;
default:
wxFAIL;
}
}
void wxExManagedFrame::ShowViMessage(const wxString& text)
{
if (GetStatusBar()->IsShown())
{
GetStatusBar()->SetStatusText(text);
m_Manager.GetPane("VIBAR").Hide();
}
else
{
m_viTextPrefix->SetLabel(text);
m_viTextCtrl->Hide();
m_Manager.GetPane("VIBAR").Show();
}
m_Manager.Update();
}
void wxExManagedFrame::TogglePane(const wxString& pane)
{
wxAuiPaneInfo& info = m_Manager.GetPane(pane);
wxASSERT(info.IsOk());
info.IsShown() ? info.Hide(): info.Show();
m_Manager.Update();
}
// Implementation of support class.
BEGIN_EVENT_TABLE(wxExViTextCtrl, wxTextCtrl)
EVT_CHAR(wxExViTextCtrl::OnKey)
EVT_SET_FOCUS(wxExViTextCtrl::OnFocus)
EVT_TEXT(wxID_ANY, wxExViTextCtrl::OnCommand)
EVT_TEXT_ENTER(wxID_ANY, wxExViTextCtrl::OnEnter)
END_EVENT_TABLE()
wxExViTextCtrl::wxExViTextCtrl(
wxWindow* parent,
wxExManagedFrame* frame,
wxWindowID id,
const wxPoint& pos,
const wxSize& size)
: wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER)
, m_Frame(frame)
, m_vi(NULL)
, m_UserInput(false)
{
}
void wxExViTextCtrl::OnCommand(wxCommandEvent& event)
{
event.Skip();
if (m_UserInput && m_vi != NULL && m_Frame->GetViCommandIsFind())
{
m_vi->GetSTC()->PositionRestore();
m_vi->GetSTC()->FindNext(
GetValue(),
m_vi->GetSearchFlags(),
m_Frame->GetViCommandIsFindNext());
}
}
void wxExViTextCtrl::OnEnter(wxCommandEvent& event)
{
event.Skip();
if (!m_Frame->GetViCommandIsFind())
{
if (m_vi != NULL)
{
if (m_vi->ExecCommand(GetValue()))
{
m_Frame->HideViBar();
}
}
}
else
{
if (m_UserInput)
{
if (!GetValue().empty())
{
wxExFindReplaceData::Get()->SetFindString(GetValue());
}
}
else if (m_vi != NULL)
{
m_vi->GetSTC()->FindNext(
GetValue(),
m_vi->GetSearchFlags(),
m_Frame->GetViCommandIsFindNext());
}
m_Frame->HideViBar();
}
}
void wxExViTextCtrl::OnFocus(wxFocusEvent& event)
{
event.Skip();
if (m_vi != NULL)
{
m_vi->GetSTC()->PositionSave();
}
}
void wxExViTextCtrl::OnKey(wxKeyEvent& event)
{
const auto key = event.GetKeyCode();
if (key == WXK_ESCAPE)
{
if (m_vi != NULL)
{
m_vi->GetSTC()->PositionRestore();
}
m_Frame->HideViBar();
m_UserInput = false;
}
else
{
m_UserInput = true;
event.Skip();
}
}
void wxExViTextCtrl::SetVi(wxExVi* vi)
{
if (vi->GetSTC()->IsBeingDeleted())
{
wxLogStatus("invalid vi");
m_vi = NULL;
}
else
{
m_vi = vi;
m_UserInput = false;
Show();
if (m_Frame->GetViCommandIsFind())
{
// sync with frd data.
SetValue(wxExFindReplaceData::Get()->GetFindString());
SelectAll();
}
else
{
Clear();
}
SetFocus();
}
}
#endif // wxUSE_GUI
<commit_msg>Edited extension/src/managedframe.cpp via GitHub<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: managedframe.cpp
// Purpose: Implementation of wxExManagedFrame class.
// Author: Anton van Wezenbeek
// Created: 2010-04-11
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/wxcrt.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/defs.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/vi.h>
#if wxUSE_GUI
// Support class.
// Offers a text ctrl related to a vi object.
class wxExViTextCtrl: public wxTextCtrl
{
public:
/// Constructor. Creates empty control.
wxExViTextCtrl(
wxWindow* parent,
wxExManagedFrame* frame,
wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize);
/// Returns vi component.
wxExVi* GetVi() {return m_vi;};
/// Sets vi component.
void SetVi(wxExVi* vi);
protected:
void OnCommand(wxCommandEvent& event);
void OnEnter(wxCommandEvent& event);
void OnFocus(wxFocusEvent& event);
void OnKey(wxKeyEvent& event);
private:
wxExManagedFrame* m_Frame;
wxExVi* m_vi;
bool m_UserInput;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
EVT_UPDATE_UI_RANGE(
ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()
wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
long style)
: wxExFrame(parent, id, title, style)
{
m_Manager.SetManagedWindow(this);
wxExToolBar* toolBar = new wxExToolBar(this);
toolBar->AddControls();
DoAddControl(toolBar);
AddToolBarPane(toolBar, "TOOLBAR", _("Toolbar"));
AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar"));
// A vi panel starts with small static text for : or /, then
// comes the vi ctrl for getting user input.
wxPanel* panel = new wxPanel(this);
m_viTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString);
m_viTextCtrl = new wxExViTextCtrl(panel, this, wxID_ANY);
wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
sizer->AddGrowableCol(1);
sizer->Add(m_viTextPrefix, wxSizerFlags().Expand());
sizer->Add(m_viTextCtrl, wxSizerFlags().Expand());
panel->SetSizerAndFit(sizer);
AddToolBarPane(panel, "VIBAR");
m_Manager.Update();
}
wxExManagedFrame::~wxExManagedFrame()
{
m_Manager.UnInit();
}
bool wxExManagedFrame::AddToolBarPane(
wxWindow* window,
const wxString& name,
const wxString& caption)
{
wxAuiPaneInfo pane;
pane
.LeftDockable(false)
.RightDockable(false)
.Name(name);
// If the toolbar has a caption, it is at the top,
// otherwise fixed at the bottom and initially hidden.
if (!caption.empty())
{
pane
.Top()
.ToolbarPane()
.Caption(caption);
}
else
{
pane
.Bottom()
.CloseButton(false)
.Hide()
.DockFixed(true)
.Movable(false)
.CaptionVisible(false);
}
return m_Manager.AddPane(window, pane);
}
void wxExManagedFrame::GetViCommand(wxExVi* vi, const wxString& command)
{
m_viTextPrefix->SetLabel(command);
m_viTextCtrl->SetVi(vi);
m_Manager.GetPane("VIBAR").Show();
m_Manager.Update();
}
bool wxExManagedFrame::GetViCommandIsFind() const
{
return m_viTextPrefix->GetLabel() == "/" || m_viTextPrefix->GetLabel() == "?";
}
bool wxExManagedFrame::GetViCommandIsFindNext() const
{
return GetViCommandIsFind() && m_viTextPrefix->GetLabel() == "/";
}
void wxExManagedFrame::HideViBar()
{
if (m_Manager.GetPane("VIBAR").IsShown())
{
m_Manager.GetPane("VIBAR").Hide();
m_Manager.Update();
m_viTextCtrl->GetVi()->GetSTC()->SetFocus();
}
}
void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
switch (event.GetId())
{
case wxID_PREFERENCES:
wxExSTC::ConfigDialog(this,
_("Editor Options"),
wxExSTC::STC_CONFIG_MODELESS |
wxExSTC::STC_CONFIG_SIMPLE |
wxExSTC::STC_CONFIG_WITH_APPLY,
event.GetId());
break;
case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;
default:
wxFAIL;
}
}
void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
switch (event.GetId())
{
case ID_VIEW_FINDBAR:
event.Check(m_Manager.GetPane("FINDBAR").IsShown());
break;
case ID_VIEW_TOOLBAR:
event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
break;
default:
wxFAIL;
}
}
void wxExManagedFrame::ShowViMessage(const wxString& text)
{
if (GetStatusBar()->IsShown())
{
GetStatusBar()->SetStatusText(text);
m_Manager.GetPane("VIBAR").Hide();
}
else
{
m_viTextPrefix->SetLabel(text);
m_viTextCtrl->Hide();
m_Manager.GetPane("VIBAR").Show();
}
m_Manager.Update();
}
void wxExManagedFrame::TogglePane(const wxString& pane)
{
wxAuiPaneInfo& info = m_Manager.GetPane(pane);
wxASSERT(info.IsOk());
info.IsShown() ? info.Hide(): info.Show();
m_Manager.Update();
}
// Implementation of support class.
BEGIN_EVENT_TABLE(wxExViTextCtrl, wxTextCtrl)
EVT_CHAR(wxExViTextCtrl::OnKey)
EVT_SET_FOCUS(wxExViTextCtrl::OnFocus)
EVT_TEXT(wxID_ANY, wxExViTextCtrl::OnCommand)
EVT_TEXT_ENTER(wxID_ANY, wxExViTextCtrl::OnEnter)
END_EVENT_TABLE()
wxExViTextCtrl::wxExViTextCtrl(
wxWindow* parent,
wxExManagedFrame* frame,
wxWindowID id,
const wxPoint& pos,
const wxSize& size)
: wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER)
, m_Frame(frame)
, m_vi(NULL)
, m_UserInput(false)
{
}
void wxExViTextCtrl::OnCommand(wxCommandEvent& event)
{
event.Skip();
if (m_UserInput && m_vi != NULL && m_Frame->GetViCommandIsFind())
{
m_vi->GetSTC()->PositionRestore();
m_vi->GetSTC()->FindNext(
GetValue(),
m_vi->GetSearchFlags(),
m_Frame->GetViCommandIsFindNext());
}
}
void wxExViTextCtrl::OnEnter(wxCommandEvent& event)
{
event.Skip();
if (!m_Frame->GetViCommandIsFind())
{
if (m_vi != NULL)
{
if (m_vi->ExecCommand(GetValue()))
{
wxConfigBase::Get()->Write("vicommand", GetValue()));
m_Frame->HideViBar();
}
}
}
else
{
if (m_UserInput)
{
if (!GetValue().empty())
{
wxExFindReplaceData::Get()->SetFindString(GetValue());
}
}
else if (m_vi != NULL)
{
m_vi->GetSTC()->FindNext(
GetValue(),
m_vi->GetSearchFlags(),
m_Frame->GetViCommandIsFindNext());
}
m_Frame->HideViBar();
}
}
void wxExViTextCtrl::OnFocus(wxFocusEvent& event)
{
event.Skip();
if (m_vi != NULL)
{
m_vi->GetSTC()->PositionSave();
}
}
void wxExViTextCtrl::OnKey(wxKeyEvent& event)
{
const auto key = event.GetKeyCode();
if (key == WXK_ESCAPE)
{
if (m_vi != NULL)
{
m_vi->GetSTC()->PositionRestore();
}
m_Frame->HideViBar();
m_UserInput = false;
}
else
{
m_UserInput = true;
event.Skip();
}
}
void wxExViTextCtrl::SetVi(wxExVi* vi)
{
m_UserInput = false;
if (vi->GetSTC()->IsBeingDeleted())
{
wxLogStatus("invalid vi");
m_vi = NULL;
}
else
{
m_vi = vi;
Show();
if (m_Frame->GetViCommandIsFind())
{
SetValue(wxExFindReplaceData::Get()->GetFindString());
}
else
{
SetValue(wxConfigBase::Get()->Read("vicommand", wxEmptyString));
}
SelectAll();
SetFocus();
}
}
#endif // wxUSE_GUI
<|endoftext|>
|
<commit_before>#include <gl/glew.h>
#include "StageCanvas.h"
#include "Exception.h"
#include "ExceptionDlg.h"
#include "EditPanelImpl.h"
#include "KeysState.h"
#include "subject_id.h"
#include "panel_msg.h"
#include "EE_DTex.h"
#include "EE_GTxt.h"
#include <unirender/UR_RenderContext.h>
#include <shaderlab/ShaderMgr.h>
#include <sprite2/RenderCtxStack.h>
#include <sprite2/SprTimer.h>
#include <gum/GUM_ShaderLab.h>
#include <gum/GUM_DTex.h>
#include <gum/RenderContext.h>
#include <gum/GUM_AsyncTask.h>
#include <gum/AudioContext.h>
namespace ee
{
BEGIN_EVENT_TABLE(StageCanvas, wxGLCanvas)
EVT_SIZE(StageCanvas::OnSize)
EVT_PAINT(StageCanvas::OnPaint)
// EVT_ERASE_BACKGROUND(StageCanvas::OnEraseBackground)
EVT_MOUSE_EVENTS(StageCanvas::OnMouse)
EVT_KEY_DOWN(StageCanvas::OnKeyDown)
EVT_KEY_UP(StageCanvas::OnKeyUp)
EVT_CHAR(StageCanvas::OnChar)
EVT_TIMER(TIMER_ID, StageCanvas::OnTimer)
EVT_KILL_FOCUS(StageCanvas::OnKillFocus)
END_EVENT_TABLE()
static const int GL_ATTRIB[20] = {WX_GL_RGBA, WX_GL_MIN_RED, 1, WX_GL_MIN_GREEN, 1,
WX_GL_MIN_BLUE, 1, WX_GL_DEPTH_SIZE, 1,
WX_GL_DOUBLEBUFFER,WX_GL_STENCIL_SIZE, 8, 0};
static const float FPS = 30;
StageCanvas::StageCanvas(wxWindow* stage_wnd, EditPanelImpl* stage,
wxGLContext* glctx, bool use_context_stack)
: wxGLCanvas(stage_wnd, wxID_ANY, GL_ATTRIB)
, m_share_context(false)
, m_use_context_stack(use_context_stack)
, m_stage(stage)
, m_width(0), m_height(0)
, m_dirty(false)
, m_cam_dirty(false)
, m_render_ctx_idx(-1)
, m_timer(this, TIMER_ID)
, m_draw(true)
{
if (glctx) {
m_share_context = true;
m_gl_ctx = glctx;
} else {
m_share_context = false;
m_gl_ctx = new wxGLContext(this);
Init();
}
m_bg_color.FromFloat(0.5f, 0.5f, 0.5f);
m_timer.Start(1000 / FPS);
RegistSubject(SetCanvasDirtySJ::Instance());
if (m_use_context_stack) {
m_render_ctx_idx = s2::RenderCtxStack::Instance()->Push(s2::RenderContext());
}
}
StageCanvas::~StageCanvas()
{
m_timer.Stop();
if (!m_share_context) {
delete m_gl_ctx;
}
if (m_use_context_stack)
{
s2::RenderCtxStack::Instance()->Pop();
const s2::RenderContext* ctx = s2::RenderCtxStack::Instance()->Top();
if (ctx) {
gum::RenderContext::Instance()->OnSize(ctx->GetScreenWidth(), ctx->GetScreenHeight());
}
}
}
void StageCanvas::SetCurrentCanvas()
{
SetCurrent(*m_gl_ctx);
s2::RenderCtxStack::Instance()->Bind(m_render_ctx_idx);
}
void StageCanvas::SetBgColor(const s2::Color& color)
{
m_bg_color = color;
}
void StageCanvas::OnNotify(int sj_id, void* ud)
{
switch (sj_id)
{
case MSG_SET_CANVAS_DIRTY:
m_dirty = true;
break;
}
}
void StageCanvas::Init()
{
SetCurrentCanvas();
if (glewInit() != GLEW_OK) {
exit(1);
}
s2::SprTimer::Instance()->Init();
// prepare 2d
// todo: move to child, for defferent init (such as 3d ?)
gum::ShaderLab::Instance()->Init();
gum::AudioContext::Instance()->Init();
DTex::Init();
GTxt::Init();
try {
// ShaderContext::Reload();
// ShaderContext::Reset();
glEnable(GL_TEXTURE_2D);
} catch (Exception& e) {
ExceptionDlg dlg(m_parent, e);
dlg.ShowModal();
}
}
void StageCanvas::OnSize(wxSizeEvent& event)
{
SetCurrentCanvas();
wxSize size = event.GetSize();
m_width = size.GetWidth();
m_height = size.GetHeight();
OnSize(m_width, m_height);
sl::ShaderMgr::Instance()->GetContext()->ClearTextureCache();
}
void StageCanvas::OnPaint(wxPaintEvent& event)
{
if (!m_draw) {
return;
}
// Makes the OpenGL state that is represented by the OpenGL rendering
// context context current
SetCurrentCanvas();
OnDrawWhole();
m_dirty = false;
m_cam_dirty = false;
sl::ShaderMgr::Instance()->FlushShader();
glFlush();
SwapBuffers();
gum::ShaderLab::Instance()->Update(1 / 30.0f);
// wxPaintDC dc(this);
// OnDrawDC();
}
// void StageCanvas::OnEraseBackground(wxEraseEvent& event)
// {
// }
void StageCanvas::OnMouse(wxMouseEvent& event)
{
m_stage->OnMouse(event);
// The handler of this event should normally call event.Skip() to allow the default processing
// to take place as otherwise the window under mouse wouldn't get the focus.
if (event.LeftDown()) {
event.Skip();
}
}
void StageCanvas::OnKeyDown(wxKeyEvent& event)
{
m_stage->OnKeyDown(event);
}
void StageCanvas::OnKeyUp(wxKeyEvent& event)
{
m_stage->OnKeyUp(event);
}
void StageCanvas::OnChar(wxKeyEvent& event)
{
m_stage->OnChar(event);
}
void StageCanvas::OnTimer(wxTimerEvent& event)
{
OnTimer();
float dt = 0.166f;
clock_t curr_time = clock();
static clock_t last_time = 0;
if (last_time != 0) {
dt = (float)(curr_time - last_time) / CLOCKS_PER_SEC;
}
last_time = curr_time;
if (s2::SprTimer::Instance()->Update(dt)) {
m_dirty = true;
}
gum::DTex::Instance()->Flush();
gum::AsyncTask::Instance()->Update();
bool dirty = m_stage->Update();
if (dirty) {
m_dirty = dirty;
}
if (m_dirty || m_cam_dirty) {
Refresh();
}
}
void StageCanvas::OnKillFocus(wxFocusEvent& event)
{
m_stage->GetKeyState().Reset();
}
}<commit_msg>add s2 init<commit_after>#include <gl/glew.h>
#include "StageCanvas.h"
#include "Exception.h"
#include "ExceptionDlg.h"
#include "EditPanelImpl.h"
#include "KeysState.h"
#include "subject_id.h"
#include "panel_msg.h"
#include "EE_DTex.h"
#include "EE_GTxt.h"
#include <unirender/UR_RenderContext.h>
#include <shaderlab/ShaderMgr.h>
#include <sprite2/RenderCtxStack.h>
#include <sprite2/SprTimer.h>
#include <gum/GUM_ShaderLab.h>
#include <gum/GUM_DTex.h>
#include <gum/RenderContext.h>
#include <gum/GUM_AsyncTask.h>
#include <gum/AudioContext.h>
#include <gum/GUM_Sprite2.h>
namespace ee
{
BEGIN_EVENT_TABLE(StageCanvas, wxGLCanvas)
EVT_SIZE(StageCanvas::OnSize)
EVT_PAINT(StageCanvas::OnPaint)
// EVT_ERASE_BACKGROUND(StageCanvas::OnEraseBackground)
EVT_MOUSE_EVENTS(StageCanvas::OnMouse)
EVT_KEY_DOWN(StageCanvas::OnKeyDown)
EVT_KEY_UP(StageCanvas::OnKeyUp)
EVT_CHAR(StageCanvas::OnChar)
EVT_TIMER(TIMER_ID, StageCanvas::OnTimer)
EVT_KILL_FOCUS(StageCanvas::OnKillFocus)
END_EVENT_TABLE()
static const int GL_ATTRIB[20] = {WX_GL_RGBA, WX_GL_MIN_RED, 1, WX_GL_MIN_GREEN, 1,
WX_GL_MIN_BLUE, 1, WX_GL_DEPTH_SIZE, 1,
WX_GL_DOUBLEBUFFER,WX_GL_STENCIL_SIZE, 8, 0};
static const float FPS = 30;
StageCanvas::StageCanvas(wxWindow* stage_wnd, EditPanelImpl* stage,
wxGLContext* glctx, bool use_context_stack)
: wxGLCanvas(stage_wnd, wxID_ANY, GL_ATTRIB)
, m_share_context(false)
, m_use_context_stack(use_context_stack)
, m_stage(stage)
, m_width(0), m_height(0)
, m_dirty(false)
, m_cam_dirty(false)
, m_render_ctx_idx(-1)
, m_timer(this, TIMER_ID)
, m_draw(true)
{
if (glctx) {
m_share_context = true;
m_gl_ctx = glctx;
} else {
m_share_context = false;
m_gl_ctx = new wxGLContext(this);
Init();
}
m_bg_color.FromFloat(0.5f, 0.5f, 0.5f);
m_timer.Start(1000 / FPS);
RegistSubject(SetCanvasDirtySJ::Instance());
if (m_use_context_stack) {
m_render_ctx_idx = s2::RenderCtxStack::Instance()->Push(s2::RenderContext());
}
}
StageCanvas::~StageCanvas()
{
m_timer.Stop();
if (!m_share_context) {
delete m_gl_ctx;
}
if (m_use_context_stack)
{
s2::RenderCtxStack::Instance()->Pop();
const s2::RenderContext* ctx = s2::RenderCtxStack::Instance()->Top();
if (ctx) {
gum::RenderContext::Instance()->OnSize(ctx->GetScreenWidth(), ctx->GetScreenHeight());
}
}
}
void StageCanvas::SetCurrentCanvas()
{
SetCurrent(*m_gl_ctx);
s2::RenderCtxStack::Instance()->Bind(m_render_ctx_idx);
}
void StageCanvas::SetBgColor(const s2::Color& color)
{
m_bg_color = color;
}
void StageCanvas::OnNotify(int sj_id, void* ud)
{
switch (sj_id)
{
case MSG_SET_CANVAS_DIRTY:
m_dirty = true;
break;
}
}
void StageCanvas::Init()
{
SetCurrentCanvas();
if (glewInit() != GLEW_OK) {
exit(1);
}
s2::SprTimer::Instance()->Init();
// prepare 2d
// todo: move to child, for defferent init (such as 3d ?)
gum::ShaderLab::Instance()->Init();
gum::AudioContext::Instance()->Init();
gum::Sprite2::Init();
DTex::Init();
GTxt::Init();
try {
// ShaderContext::Reload();
// ShaderContext::Reset();
glEnable(GL_TEXTURE_2D);
} catch (Exception& e) {
ExceptionDlg dlg(m_parent, e);
dlg.ShowModal();
}
}
void StageCanvas::OnSize(wxSizeEvent& event)
{
SetCurrentCanvas();
wxSize size = event.GetSize();
m_width = size.GetWidth();
m_height = size.GetHeight();
OnSize(m_width, m_height);
sl::ShaderMgr::Instance()->GetContext()->ClearTextureCache();
}
void StageCanvas::OnPaint(wxPaintEvent& event)
{
if (!m_draw) {
return;
}
// Makes the OpenGL state that is represented by the OpenGL rendering
// context context current
SetCurrentCanvas();
OnDrawWhole();
m_dirty = false;
m_cam_dirty = false;
sl::ShaderMgr::Instance()->FlushShader();
glFlush();
SwapBuffers();
gum::ShaderLab::Instance()->Update(1 / 30.0f);
// wxPaintDC dc(this);
// OnDrawDC();
}
// void StageCanvas::OnEraseBackground(wxEraseEvent& event)
// {
// }
void StageCanvas::OnMouse(wxMouseEvent& event)
{
m_stage->OnMouse(event);
// The handler of this event should normally call event.Skip() to allow the default processing
// to take place as otherwise the window under mouse wouldn't get the focus.
if (event.LeftDown()) {
event.Skip();
}
}
void StageCanvas::OnKeyDown(wxKeyEvent& event)
{
m_stage->OnKeyDown(event);
}
void StageCanvas::OnKeyUp(wxKeyEvent& event)
{
m_stage->OnKeyUp(event);
}
void StageCanvas::OnChar(wxKeyEvent& event)
{
m_stage->OnChar(event);
}
void StageCanvas::OnTimer(wxTimerEvent& event)
{
OnTimer();
float dt = 0.166f;
clock_t curr_time = clock();
static clock_t last_time = 0;
if (last_time != 0) {
dt = (float)(curr_time - last_time) / CLOCKS_PER_SEC;
}
last_time = curr_time;
if (s2::SprTimer::Instance()->Update(dt)) {
m_dirty = true;
}
gum::DTex::Instance()->Flush();
gum::AsyncTask::Instance()->Update();
bool dirty = m_stage->Update();
if (dirty) {
m_dirty = dirty;
}
if (m_dirty || m_cam_dirty) {
Refresh();
}
}
void StageCanvas::OnKillFocus(wxFocusEvent& event)
{
m_stage->GetKeyState().Reset();
}
}<|endoftext|>
|
<commit_before>/*!
* This file is part of CameraPlus.
*
* Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "batteryinfo.h"
#include <QBatteryInfo>
#if defined(QT4)
#include <QDeclarativeInfo>
#elif defined(QT5)
#include <QQmlInfo>
#endif
BatteryInfo::BatteryInfo(QObject *parent) :
QObject(parent),
m_battery(0),
m_isGood(true) {
}
BatteryInfo::~BatteryInfo() {
setActive(false);
}
bool BatteryInfo::isGood() const {
return m_isGood;
}
bool BatteryInfo::isActive() const {
return m_battery != 0;
}
void BatteryInfo::setActive(bool active) {
if (isActive() == active) {
return;
}
if (!active) {
m_battery->deleteLater();
m_battery = 0;
}
else {
m_battery = new QBatteryInfo(this);
QObject::connect(m_battery, SIGNAL(batteryStatusChanged(int, QBatteryInfo::BatteryStatus)),
this, SLOT(check()));
QObject::connect(m_battery, SIGNAL(chargingStateChanged(int, QBatteryInfo::ChargingState)),
this, SLOT(check()));
}
emit activeChanged();
if (m_battery) {
check();
}
}
void BatteryInfo::check() {
bool isGood = false;
if (!m_battery) {
qmlInfo(this) << "BatteryInfo has to be activated first";
isGood = true;
} else if (m_battery->chargingState(0) == QBatteryInfo::Charging) {
isGood = true;
} else {
QBatteryInfo::BatteryStatus state = m_battery->batteryStatus(0);
if (state == QBatteryInfo::BatteryOk || state == QBatteryInfo::BatteryFull) {
isGood = true;
} else {
isGood = false;
}
}
if (isGood != m_isGood) {
m_isGood = isGood;
emit isGoodChanged();
}
}
<commit_msg>sailfish: initial Qt 5.2 port<commit_after>/*!
* This file is part of CameraPlus.
*
* Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "batteryinfo.h"
#include <QBatteryInfo>
#if defined(QT4)
#include <QDeclarativeInfo>
#elif defined(QT5)
#include <QQmlInfo>
#endif
BatteryInfo::BatteryInfo(QObject *parent) :
QObject(parent),
m_battery(0),
m_isGood(true) {
}
BatteryInfo::~BatteryInfo() {
setActive(false);
}
bool BatteryInfo::isGood() const {
return m_isGood;
}
bool BatteryInfo::isActive() const {
return m_battery != 0;
}
void BatteryInfo::setActive(bool active) {
if (isActive() == active) {
return;
}
if (!active) {
m_battery->deleteLater();
m_battery = 0;
}
else {
m_battery = new QBatteryInfo(this);
QObject::connect(m_battery, SIGNAL(levelStatusChanged(QBatteryInfo::LevelStatus)),
this, SLOT(check()));
QObject::connect(m_battery, SIGNAL(chargingStateChanged(QBatteryInfo::ChargingState)),
this, SLOT(check()));
}
emit activeChanged();
if (m_battery) {
check();
}
}
void BatteryInfo::check() {
bool isGood = false;
if (!m_battery) {
qmlInfo(this) << "BatteryInfo has to be activated first";
isGood = true;
} else if (m_battery->chargingState() == QBatteryInfo::Charging) {
isGood = true;
} else {
QBatteryInfo::LevelStatus state = m_battery->levelStatus();
if (state == QBatteryInfo::LevelOk || state == QBatteryInfo::LevelFull) {
isGood = true;
} else {
isGood = false;
}
}
if (isGood != m_isGood) {
m_isGood = isGood;
emit isGoodChanged();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xmlfiltercommon.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-08-20 08:30:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLFILTERCOMMON_HXX_
#define _XMLFILTERCOMMON_HXX_
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAME_HPP_
#include <com/sun/star/container/XHierarchicalName.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#include <vector>
// --------------------------------------------------------------------
extern ::rtl::OUString string_encode( const ::rtl::OUString & rText );
extern ::rtl::OUString xmlname_encode( const ::rtl::OUString & rText );
extern ::rtl::OUString string_decode( const ::rtl::OUString & rText );
// --------------------------------------------------------------------
extern bool isFileURL( const ::rtl::OUString & rURL );
// --------------------------------------------------------------------
bool copyStreams( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xIS, ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > xOS );
bool createDirectory( ::rtl::OUString& rURL );
// --------------------------------------------------------------------
class filter_info_impl
{
public:
rtl::OUString maFilterName;
rtl::OUString maType;
rtl::OUString maDocumentService;
rtl::OUString maFilterService;
rtl::OUString maInterfaceName;
rtl::OUString maComment;
rtl::OUString maExtension;
rtl::OUString maDTD;
rtl::OUString maExportXSLT;
rtl::OUString maImportXSLT;
rtl::OUString maImportTemplate;
rtl::OUString maDocType;
rtl::OUString maImportService;
rtl::OUString maExportService;
sal_Int32 maFlags;
sal_Int32 maFileFormatVersion;
sal_Int32 mnDocumentIconID;
sal_Bool mbReadonly;
filter_info_impl();
filter_info_impl( const filter_info_impl& rInfo );
int operator==( const filter_info_impl& ) const;
com::sun::star::uno::Sequence< rtl::OUString > getFilterUserData() const;
};
// --------------------------------------------------------------------
struct application_info_impl
{
rtl::OUString maDocumentService;
rtl::OUString maDocumentUIName;
rtl::OUString maXMLImporter;
rtl::OUString maXMLExporter;
application_info_impl( const sal_Char * pDocumentService, ResId& rUINameRes, const sal_Char * mpXMLImporter, const sal_Char * mpXMLExporter );
};
// --------------------------------------------------------------------
extern std::vector< application_info_impl* >& getApplicationInfos();
extern rtl::OUString getApplicationUIName( const rtl::OUString& rServiceName );
extern const application_info_impl* getApplicationInfo( const rtl::OUString& rServiceName );
extern ResMgr* getXSLTDialogResMgr();
#define RESID(x) ResId(x, getXSLTDialogResMgr() )
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.242); FILE MERGED 2005/09/05 14:31:53 rt 1.5.242.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlfiltercommon.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 22:17:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLFILTERCOMMON_HXX_
#define _XMLFILTERCOMMON_HXX_
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAME_HPP_
#include <com/sun/star/container/XHierarchicalName.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#include <vector>
// --------------------------------------------------------------------
extern ::rtl::OUString string_encode( const ::rtl::OUString & rText );
extern ::rtl::OUString xmlname_encode( const ::rtl::OUString & rText );
extern ::rtl::OUString string_decode( const ::rtl::OUString & rText );
// --------------------------------------------------------------------
extern bool isFileURL( const ::rtl::OUString & rURL );
// --------------------------------------------------------------------
bool copyStreams( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xIS, ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > xOS );
bool createDirectory( ::rtl::OUString& rURL );
// --------------------------------------------------------------------
class filter_info_impl
{
public:
rtl::OUString maFilterName;
rtl::OUString maType;
rtl::OUString maDocumentService;
rtl::OUString maFilterService;
rtl::OUString maInterfaceName;
rtl::OUString maComment;
rtl::OUString maExtension;
rtl::OUString maDTD;
rtl::OUString maExportXSLT;
rtl::OUString maImportXSLT;
rtl::OUString maImportTemplate;
rtl::OUString maDocType;
rtl::OUString maImportService;
rtl::OUString maExportService;
sal_Int32 maFlags;
sal_Int32 maFileFormatVersion;
sal_Int32 mnDocumentIconID;
sal_Bool mbReadonly;
filter_info_impl();
filter_info_impl( const filter_info_impl& rInfo );
int operator==( const filter_info_impl& ) const;
com::sun::star::uno::Sequence< rtl::OUString > getFilterUserData() const;
};
// --------------------------------------------------------------------
struct application_info_impl
{
rtl::OUString maDocumentService;
rtl::OUString maDocumentUIName;
rtl::OUString maXMLImporter;
rtl::OUString maXMLExporter;
application_info_impl( const sal_Char * pDocumentService, ResId& rUINameRes, const sal_Char * mpXMLImporter, const sal_Char * mpXMLExporter );
};
// --------------------------------------------------------------------
extern std::vector< application_info_impl* >& getApplicationInfos();
extern rtl::OUString getApplicationUIName( const rtl::OUString& rServiceName );
extern const application_info_impl* getApplicationInfo( const rtl::OUString& rServiceName );
extern ResMgr* getXSLTDialogResMgr();
#define RESID(x) ResId(x, getXSLTDialogResMgr() )
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "views/controls/textfield/textfield_views_model.h"
#include "views/test/test_views_delegate.h"
#include "views/views_delegate.h"
namespace views {
#define EXPECT_STR_EQ(ascii, utf16) \
EXPECT_EQ(ASCIIToWide(ascii), UTF16ToWide(utf16))
TEST(TextfieldViewsModelTest, EditString) {
TextfieldViewsModel model;
// append two strings
model.Append(ASCIIToUTF16("HILL"));
EXPECT_STR_EQ("HILL", model.text());
model.Append(ASCIIToUTF16("WORLD"));
EXPECT_STR_EQ("HILLWORLD", model.text());
// Insert "E" to make hello
model.MoveCursorRight(false);
model.Insert('E');
EXPECT_STR_EQ("HEILLWORLD", model.text());
// Replace "I" with "L"
model.Replace('L');
EXPECT_STR_EQ("HELLLWORLD", model.text());
model.Replace('L');
model.Replace('O');
EXPECT_STR_EQ("HELLOWORLD", model.text());
// Delete 6th char "W", then delete 5th char O"
EXPECT_EQ(5U, model.cursor_pos());
EXPECT_TRUE(model.Delete());
EXPECT_STR_EQ("HELLOORLD", model.text());
EXPECT_TRUE(model.Backspace());
EXPECT_EQ(4U, model.cursor_pos());
EXPECT_STR_EQ("HELLORLD", model.text());
// Move the cursor to start. backspace should fail.
model.MoveCursorToStart(false);
EXPECT_FALSE(model.Backspace());
EXPECT_STR_EQ("HELLORLD", model.text());
// Move the cursor to the end. delete should fail.
model.MoveCursorToEnd(false);
EXPECT_FALSE(model.Delete());
EXPECT_STR_EQ("HELLORLD", model.text());
// but backspace should work.
EXPECT_TRUE(model.Backspace());
EXPECT_STR_EQ("HELLORL", model.text());
}
TEST(TextfieldViewsModelTest, EmptyString) {
TextfieldViewsModel model;
EXPECT_EQ(string16(), model.text());
EXPECT_EQ(string16(), model.GetSelectedText());
EXPECT_EQ(string16(), model.GetVisibleText());
model.MoveCursorLeft(true);
EXPECT_EQ(0U, model.cursor_pos());
model.MoveCursorRight(true);
EXPECT_EQ(0U, model.cursor_pos());
EXPECT_EQ(string16(), model.GetSelectedText());
EXPECT_FALSE(model.Delete());
EXPECT_FALSE(model.Backspace());
}
TEST(TextfieldViewsModelTest, Selection) {
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO"));
model.MoveCursorRight(false);
model.MoveCursorRight(true);
EXPECT_STR_EQ("E", model.GetSelectedText());
model.MoveCursorRight(true);
EXPECT_STR_EQ("EL", model.GetSelectedText());
model.MoveCursorToStart(true);
EXPECT_STR_EQ("H", model.GetSelectedText());
model.MoveCursorToEnd(true);
EXPECT_STR_EQ("ELLO", model.GetSelectedText());
model.ClearSelection();
EXPECT_EQ(string16(), model.GetSelectedText());
model.SelectAll();
EXPECT_STR_EQ("HELLO", model.GetSelectedText());
// Select and move cursor
model.MoveCursorTo(1U, false);
model.MoveCursorTo(3U, true);
EXPECT_STR_EQ("EL", model.GetSelectedText());
model.MoveCursorLeft(false);
EXPECT_EQ(1U, model.cursor_pos());
model.MoveCursorTo(1U, false);
model.MoveCursorTo(3U, true);
model.MoveCursorRight(false);
EXPECT_EQ(3U, model.cursor_pos());
// Select all and move cursor
model.SelectAll();
model.MoveCursorLeft(false);
EXPECT_EQ(0U, model.cursor_pos());
model.SelectAll();
model.MoveCursorRight(false);
EXPECT_EQ(5U, model.cursor_pos());
}
TEST(TextfieldViewsModelTest, SelectionAndEdit) {
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO"));
model.MoveCursorRight(false);
model.MoveCursorRight(true);
model.MoveCursorRight(true); // select "EL"
EXPECT_TRUE(model.Backspace());
EXPECT_STR_EQ("HLO", model.text());
model.Append(ASCIIToUTF16("ILL"));
model.MoveCursorRight(true);
model.MoveCursorRight(true); // select "LO"
EXPECT_TRUE(model.Delete());
EXPECT_STR_EQ("HILL", model.text());
EXPECT_EQ(1U, model.cursor_pos());
model.MoveCursorRight(true); // select "I"
model.Insert('E');
EXPECT_STR_EQ("HELL", model.text());
model.MoveCursorToStart(false);
model.MoveCursorRight(true); // select "H"
model.Replace('B');
EXPECT_STR_EQ("BELL", model.text());
model.MoveCursorToEnd(false);
model.MoveCursorLeft(true);
model.MoveCursorLeft(true); // select ">LL"
model.Replace('E');
EXPECT_STR_EQ("BEE", model.text());
}
TEST(TextfieldViewsModelTest, Password) {
TextfieldViewsModel model;
model.set_is_password(true);
model.Append(ASCIIToUTF16("HELLO"));
EXPECT_STR_EQ("*****", model.GetVisibleText());
EXPECT_STR_EQ("HELLO", model.text());
EXPECT_TRUE(model.Delete());
EXPECT_STR_EQ("****", model.GetVisibleText());
EXPECT_STR_EQ("ELLO", model.text());
EXPECT_EQ(0U, model.cursor_pos());
model.SelectAll();
EXPECT_STR_EQ("ELLO", model.GetSelectedText());
EXPECT_EQ(0U, model.cursor_pos());
model.Insert('X');
EXPECT_STR_EQ("*", model.GetVisibleText());
EXPECT_STR_EQ("X", model.text());
}
TEST(TextfieldViewsModelTest, Word) {
TextfieldViewsModel model;
model.Append(
ASCIIToUTF16("The answer to Life, the Universe, and Everything"));
model.MoveCursorToNextWord(false);
EXPECT_EQ(3U, model.cursor_pos());
model.MoveCursorToNextWord(false);
EXPECT_EQ(10U, model.cursor_pos());
model.MoveCursorToNextWord(false);
model.MoveCursorToNextWord(false);
EXPECT_EQ(18U, model.cursor_pos());
// Should passes the non word char ','
model.MoveCursorToNextWord(true);
EXPECT_EQ(23U, model.cursor_pos());
EXPECT_STR_EQ(", the", model.GetSelectedText());
// Move to the end.
model.MoveCursorToNextWord(true);
model.MoveCursorToNextWord(true);
model.MoveCursorToNextWord(true);
EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
// Should be safe to go next word at the end.
model.MoveCursorToNextWord(true);
EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
model.Insert('2');
EXPECT_EQ(19U, model.cursor_pos());
// Now backwards.
model.MoveCursorLeft(false); // leave 2.
model.MoveCursorToPreviousWord(true);
EXPECT_EQ(14U, model.cursor_pos());
EXPECT_STR_EQ("Life", model.GetSelectedText());
model.MoveCursorToPreviousWord(true);
EXPECT_STR_EQ("to Life", model.GetSelectedText());
model.MoveCursorToPreviousWord(true);
model.MoveCursorToPreviousWord(true);
model.MoveCursorToPreviousWord(true); // Select to the begining.
EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
// Should be safe to go pervious word at the begining.
model.MoveCursorToPreviousWord(true);
EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
model.Replace('4');
EXPECT_EQ(string16(), model.GetSelectedText());
EXPECT_STR_EQ("42", model.GetVisibleText());
}
TEST(TextfieldViewsModelTest, TextFragment) {
TextfieldViewsModel model;
TextfieldViewsModel::TextFragments fragments;
// Empty string
model.GetFragments(&fragments);
EXPECT_EQ(1U, fragments.size());
fragments.clear();
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(0U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
// Some string
model.Append(ASCIIToUTF16("Hello world"));
model.GetFragments(&fragments);
EXPECT_EQ(1U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(11U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
// Select 1st word
model.MoveCursorToNextWord(true);
model.GetFragments(&fragments);
EXPECT_EQ(2U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(5U, fragments[0].end);
EXPECT_TRUE(fragments[0].selected);
EXPECT_EQ(5U, fragments[1].begin);
EXPECT_EQ(11U, fragments[1].end);
EXPECT_FALSE(fragments[1].selected);
// Select empty string
model.ClearSelection();
model.MoveCursorRight(true);
model.GetFragments(&fragments);
EXPECT_EQ(3U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(5U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
EXPECT_EQ(5U, fragments[1].begin);
EXPECT_EQ(6U, fragments[1].end);
EXPECT_TRUE(fragments[1].selected);
EXPECT_EQ(6U, fragments[2].begin);
EXPECT_EQ(11U, fragments[2].end);
EXPECT_FALSE(fragments[2].selected);
// Select to the end.
model.MoveCursorToEnd(true);
model.GetFragments(&fragments);
EXPECT_EQ(2U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(5U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
EXPECT_EQ(5U, fragments[1].begin);
EXPECT_EQ(11U, fragments[1].end);
EXPECT_TRUE(fragments[1].selected);
}
TEST(TextfieldViewsModelTest, SetText) {
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO"));
model.MoveCursorToEnd(false);
model.SetText(ASCIIToUTF16("GOODBYE"));
EXPECT_STR_EQ("GOODBYE", model.text());
EXPECT_EQ(5U, model.cursor_pos());
model.SelectAll();
EXPECT_STR_EQ("GOODBYE", model.GetSelectedText());
// Selection move the current pos to the begining.
EXPECT_EQ(0U, model.cursor_pos());
model.MoveCursorToEnd(false);
EXPECT_EQ(7U, model.cursor_pos());
model.SetText(ASCIIToUTF16("BYE"));
EXPECT_EQ(3U, model.cursor_pos());
EXPECT_EQ(string16(), model.GetSelectedText());
model.SetText(ASCIIToUTF16(""));
EXPECT_EQ(0U, model.cursor_pos());
}
TEST(TextfieldViewsModelTest, Clipboard) {
scoped_ptr<TestViewsDelegate> test_views_delegate(new TestViewsDelegate());
views::ViewsDelegate::views_delegate = test_views_delegate.get();
ui::Clipboard* clipboard
= views::ViewsDelegate::views_delegate->GetClipboard();
string16 initial_clipboard_text;
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &initial_clipboard_text);
string16 clipboard_text;
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO WORLD"));
model.MoveCursorToEnd(false);
// Test for cut: Empty selection.
EXPECT_FALSE(model.Cut());
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ(UTF16ToUTF8(initial_clipboard_text), clipboard_text);
EXPECT_STR_EQ("HELLO WORLD", model.text());
EXPECT_EQ(11U, model.cursor_pos());
// Test for cut: Non-empty selection.
model.MoveCursorToPreviousWord(true);
EXPECT_TRUE(model.Cut());
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO ", model.text());
EXPECT_EQ(6U, model.cursor_pos());
// Test for copy: Empty selection.
model.Copy();
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO ", model.text());
EXPECT_EQ(6U, model.cursor_pos());
// Test for copy: Non-empty selection.
model.Append(ASCIIToUTF16("HELLO WORLD"));
model.SelectAll();
model.Copy();
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO HELLO WORLD", model.text());
EXPECT_EQ(0U, model.cursor_pos());
// Test for paste.
model.ClearSelection();
model.MoveCursorToEnd(false);
model.MoveCursorToPreviousWord(true);
EXPECT_TRUE(model.Paste());
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO HELLO HELLO HELLO WORLD", model.text());
EXPECT_EQ(29U, model.cursor_pos());
}
} // namespace views
<commit_msg>Revert 71170 - Delete test view delegate at end of test<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "views/controls/textfield/textfield_views_model.h"
#include "views/test/test_views_delegate.h"
#include "views/views_delegate.h"
namespace views {
#define EXPECT_STR_EQ(ascii, utf16) \
EXPECT_EQ(ASCIIToWide(ascii), UTF16ToWide(utf16))
TEST(TextfieldViewsModelTest, EditString) {
TextfieldViewsModel model;
// append two strings
model.Append(ASCIIToUTF16("HILL"));
EXPECT_STR_EQ("HILL", model.text());
model.Append(ASCIIToUTF16("WORLD"));
EXPECT_STR_EQ("HILLWORLD", model.text());
// Insert "E" to make hello
model.MoveCursorRight(false);
model.Insert('E');
EXPECT_STR_EQ("HEILLWORLD", model.text());
// Replace "I" with "L"
model.Replace('L');
EXPECT_STR_EQ("HELLLWORLD", model.text());
model.Replace('L');
model.Replace('O');
EXPECT_STR_EQ("HELLOWORLD", model.text());
// Delete 6th char "W", then delete 5th char O"
EXPECT_EQ(5U, model.cursor_pos());
EXPECT_TRUE(model.Delete());
EXPECT_STR_EQ("HELLOORLD", model.text());
EXPECT_TRUE(model.Backspace());
EXPECT_EQ(4U, model.cursor_pos());
EXPECT_STR_EQ("HELLORLD", model.text());
// Move the cursor to start. backspace should fail.
model.MoveCursorToStart(false);
EXPECT_FALSE(model.Backspace());
EXPECT_STR_EQ("HELLORLD", model.text());
// Move the cursor to the end. delete should fail.
model.MoveCursorToEnd(false);
EXPECT_FALSE(model.Delete());
EXPECT_STR_EQ("HELLORLD", model.text());
// but backspace should work.
EXPECT_TRUE(model.Backspace());
EXPECT_STR_EQ("HELLORL", model.text());
}
TEST(TextfieldViewsModelTest, EmptyString) {
TextfieldViewsModel model;
EXPECT_EQ(string16(), model.text());
EXPECT_EQ(string16(), model.GetSelectedText());
EXPECT_EQ(string16(), model.GetVisibleText());
model.MoveCursorLeft(true);
EXPECT_EQ(0U, model.cursor_pos());
model.MoveCursorRight(true);
EXPECT_EQ(0U, model.cursor_pos());
EXPECT_EQ(string16(), model.GetSelectedText());
EXPECT_FALSE(model.Delete());
EXPECT_FALSE(model.Backspace());
}
TEST(TextfieldViewsModelTest, Selection) {
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO"));
model.MoveCursorRight(false);
model.MoveCursorRight(true);
EXPECT_STR_EQ("E", model.GetSelectedText());
model.MoveCursorRight(true);
EXPECT_STR_EQ("EL", model.GetSelectedText());
model.MoveCursorToStart(true);
EXPECT_STR_EQ("H", model.GetSelectedText());
model.MoveCursorToEnd(true);
EXPECT_STR_EQ("ELLO", model.GetSelectedText());
model.ClearSelection();
EXPECT_EQ(string16(), model.GetSelectedText());
model.SelectAll();
EXPECT_STR_EQ("HELLO", model.GetSelectedText());
// Select and move cursor
model.MoveCursorTo(1U, false);
model.MoveCursorTo(3U, true);
EXPECT_STR_EQ("EL", model.GetSelectedText());
model.MoveCursorLeft(false);
EXPECT_EQ(1U, model.cursor_pos());
model.MoveCursorTo(1U, false);
model.MoveCursorTo(3U, true);
model.MoveCursorRight(false);
EXPECT_EQ(3U, model.cursor_pos());
// Select all and move cursor
model.SelectAll();
model.MoveCursorLeft(false);
EXPECT_EQ(0U, model.cursor_pos());
model.SelectAll();
model.MoveCursorRight(false);
EXPECT_EQ(5U, model.cursor_pos());
}
TEST(TextfieldViewsModelTest, SelectionAndEdit) {
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO"));
model.MoveCursorRight(false);
model.MoveCursorRight(true);
model.MoveCursorRight(true); // select "EL"
EXPECT_TRUE(model.Backspace());
EXPECT_STR_EQ("HLO", model.text());
model.Append(ASCIIToUTF16("ILL"));
model.MoveCursorRight(true);
model.MoveCursorRight(true); // select "LO"
EXPECT_TRUE(model.Delete());
EXPECT_STR_EQ("HILL", model.text());
EXPECT_EQ(1U, model.cursor_pos());
model.MoveCursorRight(true); // select "I"
model.Insert('E');
EXPECT_STR_EQ("HELL", model.text());
model.MoveCursorToStart(false);
model.MoveCursorRight(true); // select "H"
model.Replace('B');
EXPECT_STR_EQ("BELL", model.text());
model.MoveCursorToEnd(false);
model.MoveCursorLeft(true);
model.MoveCursorLeft(true); // select ">LL"
model.Replace('E');
EXPECT_STR_EQ("BEE", model.text());
}
TEST(TextfieldViewsModelTest, Password) {
TextfieldViewsModel model;
model.set_is_password(true);
model.Append(ASCIIToUTF16("HELLO"));
EXPECT_STR_EQ("*****", model.GetVisibleText());
EXPECT_STR_EQ("HELLO", model.text());
EXPECT_TRUE(model.Delete());
EXPECT_STR_EQ("****", model.GetVisibleText());
EXPECT_STR_EQ("ELLO", model.text());
EXPECT_EQ(0U, model.cursor_pos());
model.SelectAll();
EXPECT_STR_EQ("ELLO", model.GetSelectedText());
EXPECT_EQ(0U, model.cursor_pos());
model.Insert('X');
EXPECT_STR_EQ("*", model.GetVisibleText());
EXPECT_STR_EQ("X", model.text());
}
TEST(TextfieldViewsModelTest, Word) {
TextfieldViewsModel model;
model.Append(
ASCIIToUTF16("The answer to Life, the Universe, and Everything"));
model.MoveCursorToNextWord(false);
EXPECT_EQ(3U, model.cursor_pos());
model.MoveCursorToNextWord(false);
EXPECT_EQ(10U, model.cursor_pos());
model.MoveCursorToNextWord(false);
model.MoveCursorToNextWord(false);
EXPECT_EQ(18U, model.cursor_pos());
// Should passes the non word char ','
model.MoveCursorToNextWord(true);
EXPECT_EQ(23U, model.cursor_pos());
EXPECT_STR_EQ(", the", model.GetSelectedText());
// Move to the end.
model.MoveCursorToNextWord(true);
model.MoveCursorToNextWord(true);
model.MoveCursorToNextWord(true);
EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
// Should be safe to go next word at the end.
model.MoveCursorToNextWord(true);
EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText());
model.Insert('2');
EXPECT_EQ(19U, model.cursor_pos());
// Now backwards.
model.MoveCursorLeft(false); // leave 2.
model.MoveCursorToPreviousWord(true);
EXPECT_EQ(14U, model.cursor_pos());
EXPECT_STR_EQ("Life", model.GetSelectedText());
model.MoveCursorToPreviousWord(true);
EXPECT_STR_EQ("to Life", model.GetSelectedText());
model.MoveCursorToPreviousWord(true);
model.MoveCursorToPreviousWord(true);
model.MoveCursorToPreviousWord(true); // Select to the begining.
EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
// Should be safe to go pervious word at the begining.
model.MoveCursorToPreviousWord(true);
EXPECT_STR_EQ("The answer to Life", model.GetSelectedText());
model.Replace('4');
EXPECT_EQ(string16(), model.GetSelectedText());
EXPECT_STR_EQ("42", model.GetVisibleText());
}
TEST(TextfieldViewsModelTest, TextFragment) {
TextfieldViewsModel model;
TextfieldViewsModel::TextFragments fragments;
// Empty string
model.GetFragments(&fragments);
EXPECT_EQ(1U, fragments.size());
fragments.clear();
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(0U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
// Some string
model.Append(ASCIIToUTF16("Hello world"));
model.GetFragments(&fragments);
EXPECT_EQ(1U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(11U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
// Select 1st word
model.MoveCursorToNextWord(true);
model.GetFragments(&fragments);
EXPECT_EQ(2U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(5U, fragments[0].end);
EXPECT_TRUE(fragments[0].selected);
EXPECT_EQ(5U, fragments[1].begin);
EXPECT_EQ(11U, fragments[1].end);
EXPECT_FALSE(fragments[1].selected);
// Select empty string
model.ClearSelection();
model.MoveCursorRight(true);
model.GetFragments(&fragments);
EXPECT_EQ(3U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(5U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
EXPECT_EQ(5U, fragments[1].begin);
EXPECT_EQ(6U, fragments[1].end);
EXPECT_TRUE(fragments[1].selected);
EXPECT_EQ(6U, fragments[2].begin);
EXPECT_EQ(11U, fragments[2].end);
EXPECT_FALSE(fragments[2].selected);
// Select to the end.
model.MoveCursorToEnd(true);
model.GetFragments(&fragments);
EXPECT_EQ(2U, fragments.size());
EXPECT_EQ(0U, fragments[0].begin);
EXPECT_EQ(5U, fragments[0].end);
EXPECT_FALSE(fragments[0].selected);
EXPECT_EQ(5U, fragments[1].begin);
EXPECT_EQ(11U, fragments[1].end);
EXPECT_TRUE(fragments[1].selected);
}
TEST(TextfieldViewsModelTest, SetText) {
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO"));
model.MoveCursorToEnd(false);
model.SetText(ASCIIToUTF16("GOODBYE"));
EXPECT_STR_EQ("GOODBYE", model.text());
EXPECT_EQ(5U, model.cursor_pos());
model.SelectAll();
EXPECT_STR_EQ("GOODBYE", model.GetSelectedText());
// Selection move the current pos to the begining.
EXPECT_EQ(0U, model.cursor_pos());
model.MoveCursorToEnd(false);
EXPECT_EQ(7U, model.cursor_pos());
model.SetText(ASCIIToUTF16("BYE"));
EXPECT_EQ(3U, model.cursor_pos());
EXPECT_EQ(string16(), model.GetSelectedText());
model.SetText(ASCIIToUTF16(""));
EXPECT_EQ(0U, model.cursor_pos());
}
TEST(TextfieldViewsModelTest, Clipboard) {
views::ViewsDelegate::views_delegate = new TestViewsDelegate();
ui::Clipboard* clipboard
= views::ViewsDelegate::views_delegate->GetClipboard();
string16 initial_clipboard_text;
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &initial_clipboard_text);
string16 clipboard_text;
TextfieldViewsModel model;
model.Append(ASCIIToUTF16("HELLO WORLD"));
model.MoveCursorToEnd(false);
// Test for cut: Empty selection.
EXPECT_FALSE(model.Cut());
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ(UTF16ToUTF8(initial_clipboard_text), clipboard_text);
EXPECT_STR_EQ("HELLO WORLD", model.text());
EXPECT_EQ(11U, model.cursor_pos());
// Test for cut: Non-empty selection.
model.MoveCursorToPreviousWord(true);
EXPECT_TRUE(model.Cut());
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO ", model.text());
EXPECT_EQ(6U, model.cursor_pos());
// Test for copy: Empty selection.
model.Copy();
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO ", model.text());
EXPECT_EQ(6U, model.cursor_pos());
// Test for copy: Non-empty selection.
model.Append(ASCIIToUTF16("HELLO WORLD"));
model.SelectAll();
model.Copy();
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO HELLO WORLD", model.text());
EXPECT_EQ(0U, model.cursor_pos());
// Test for paste.
model.ClearSelection();
model.MoveCursorToEnd(false);
model.MoveCursorToPreviousWord(true);
EXPECT_TRUE(model.Paste());
clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &clipboard_text);
EXPECT_STR_EQ("HELLO HELLO WORLD", clipboard_text);
EXPECT_STR_EQ("HELLO HELLO HELLO HELLO WORLD", model.text());
EXPECT_EQ(29U, model.cursor_pos());
}
} // namespace views
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dispatchhelper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:41:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
//_______________________________________________
// includes of other projects
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// non exported const
//_______________________________________________
// non exported definitions
//_______________________________________________
// declarations
//_______________________________________________
// XInterface, XTypeProvider, XServiceInfo
DEFINE_XINTERFACE_4(DispatchHelper ,
OWeakObject ,
DIRECT_INTERFACE(css::lang::XTypeProvider ),
DIRECT_INTERFACE(css::lang::XServiceInfo ),
DIRECT_INTERFACE(css::frame::XDispatchHelper ),
DIRECT_INTERFACE(css::frame::XDispatchResultListener))
DEFINE_XTYPEPROVIDER_4(DispatchHelper ,
css::lang::XTypeProvider ,
css::lang::XServiceInfo ,
css::frame::XDispatchHelper ,
css::frame::XDispatchResultListener)
DEFINE_XSERVICEINFO_MULTISERVICE(DispatchHelper ,
::cppu::OWeakObject ,
SERVICENAME_DISPATCHHELPER ,
IMPLEMENTATIONNAME_DISPATCHHELPER)
DEFINE_INIT_SERVICE( DispatchHelper, {} )
//_______________________________________________
/** ctor.
@param xSMGR the global uno service manager, which can be used to create own needed services.
*/
DispatchHelper::DispatchHelper( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )
: ThreadHelpBase( )
, OWeakObject ( )
// Init member
, m_xSMGR (xSMGR)
{
}
//_______________________________________________
/** dtor.
*/
DispatchHelper::~DispatchHelper()
{
}
//_______________________________________________
/** capsulate all steps of a dispatch request and provide so an easy way for dispatches.
@param xDispatchProvider
identifies the object, which provides may be valid dispatch objects for this execute.
@param sURL
describes the requested feature.
@param sTargetFrameName
points to the frame, which must be used (or may be created) for this dispatch.
@param nSearchFlags
in case the <var>sTargetFrameName</var> isn't unique, these flags regulate further searches.
@param lArguments
optional arguments for this request.
@return An Any which capsulate a possible result of the internal wrapped dispatch.
*/
css::uno::Any SAL_CALL DispatchHelper::executeDispatch(
const css::uno::Reference< css::frame::XDispatchProvider >& xDispatchProvider ,
const ::rtl::OUString& sURL ,
const ::rtl::OUString& sTargetFrameName ,
sal_Int32 nSearchFlags ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments )
throw(css::uno::RuntimeException)
{
css::uno::Reference< css::uno::XInterface > xTHIS(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
// check for valid parameters
if (
(!xDispatchProvider.is()) ||
(sURL.getLength()<1 )
)
{
return css::uno::Any();
}
// parse given URL
/* SAFE { */
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::util::XURLTransformer > xParser(m_xSMGR->createInstance(SERVICENAME_URLTRANSFORMER), css::uno::UNO_QUERY);
aReadLock.unlock();
/* } SAFE */
css::util::URL aURL;
aURL.Complete = sURL;
xParser->parseStrict(aURL);
// search dispatcher
css::uno::Reference< css::frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, sTargetFrameName, nSearchFlags);
css::uno::Reference< css::frame::XNotifyingDispatch > xNotifyDispatch (xDispatch, css::uno::UNO_QUERY);
// make sure that synchronous execution is used (if possible)
css::uno::Sequence< css::beans::PropertyValue > aArguments( lArguments );
sal_Int32 nLength = lArguments.getLength();
aArguments.realloc( nLength + 1 );
aArguments[ nLength ].Name = ::rtl::OUString::createFromAscii("SynchronMode");
aArguments[ nLength ].Value <<= (sal_Bool) sal_True;
css::uno::Any aResult;
if (xNotifyDispatch.is())
{
// dispatch it with guaranteed notification
// Here we can hope for a result ... instead of the normal dispatch.
css::uno::Reference< css::frame::XDispatchResultListener > xListener(xTHIS, css::uno::UNO_QUERY);
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_xBroadcaster = css::uno::Reference< css::uno::XInterface >(xNotifyDispatch, css::uno::UNO_QUERY);
m_aResult = css::uno::Any();
m_aBlock.reset();
aWriteLock.unlock();
/* } SAFE */
// dispatch it and wait for a notification
// TODO/MBA: waiting in main thread?!
xNotifyDispatch->dispatchWithNotification(aURL, aArguments, xListener);
//m_aBlock.wait();
aResult = m_aResult;
}
else
if (xDispatch.is())
{
// dispatch it without any chance to get a result
xDispatch->dispatch( aURL, aArguments );
}
return aResult;
}
//_______________________________________________
/** callback for started dispatch with guaranteed notifications.
We must save the result, so the method executeDispatch() can return it.
Further we must release the broadcaster (otherwhise it can't die)
and unblock the waiting executeDispatch() request.
@param aResult
describes the result of the dispatch operation
*/
void SAL_CALL DispatchHelper::dispatchFinished( const css::frame::DispatchResultEvent& aResult )
throw(css::uno::RuntimeException)
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_aResult <<= aResult;
m_aBlock.set();
m_xBroadcaster.clear();
/* } SAFE */
}
//_______________________________________________
/** we has to realease our broadcaster reference.
@param aEvent
describe the source of this event and MUST be our save broadcaster!
*/
void SAL_CALL DispatchHelper::disposing( const css::lang::EventObject& aEvent )
throw(css::uno::RuntimeException)
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_aResult.clear();
m_aBlock.set();
m_xBroadcaster.clear();
/* } SAFE */
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.5.32); FILE MERGED 2005/11/16 15:20:32 pl 1.5.32.1: #i55991# removed warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dispatchhelper.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:26:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
//_______________________________________________
// includes of other projects
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// non exported const
//_______________________________________________
// non exported definitions
//_______________________________________________
// declarations
//_______________________________________________
// XInterface, XTypeProvider, XServiceInfo
DEFINE_XINTERFACE_4(DispatchHelper ,
OWeakObject ,
DIRECT_INTERFACE(css::lang::XTypeProvider ),
DIRECT_INTERFACE(css::lang::XServiceInfo ),
DIRECT_INTERFACE(css::frame::XDispatchHelper ),
DIRECT_INTERFACE(css::frame::XDispatchResultListener))
DEFINE_XTYPEPROVIDER_4(DispatchHelper ,
css::lang::XTypeProvider ,
css::lang::XServiceInfo ,
css::frame::XDispatchHelper ,
css::frame::XDispatchResultListener)
DEFINE_XSERVICEINFO_MULTISERVICE(DispatchHelper ,
::cppu::OWeakObject ,
SERVICENAME_DISPATCHHELPER ,
IMPLEMENTATIONNAME_DISPATCHHELPER)
DEFINE_INIT_SERVICE( DispatchHelper, {} )
//_______________________________________________
/** ctor.
@param xSMGR the global uno service manager, which can be used to create own needed services.
*/
DispatchHelper::DispatchHelper( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )
: ThreadHelpBase( )
, OWeakObject ( )
// Init member
, m_xSMGR (xSMGR)
{
}
//_______________________________________________
/** dtor.
*/
DispatchHelper::~DispatchHelper()
{
}
//_______________________________________________
/** capsulate all steps of a dispatch request and provide so an easy way for dispatches.
@param xDispatchProvider
identifies the object, which provides may be valid dispatch objects for this execute.
@param sURL
describes the requested feature.
@param sTargetFrameName
points to the frame, which must be used (or may be created) for this dispatch.
@param nSearchFlags
in case the <var>sTargetFrameName</var> isn't unique, these flags regulate further searches.
@param lArguments
optional arguments for this request.
@return An Any which capsulate a possible result of the internal wrapped dispatch.
*/
css::uno::Any SAL_CALL DispatchHelper::executeDispatch(
const css::uno::Reference< css::frame::XDispatchProvider >& xDispatchProvider ,
const ::rtl::OUString& sURL ,
const ::rtl::OUString& sTargetFrameName ,
sal_Int32 nSearchFlags ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments )
throw(css::uno::RuntimeException)
{
css::uno::Reference< css::uno::XInterface > xTHIS(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
// check for valid parameters
if (
(!xDispatchProvider.is()) ||
(sURL.getLength()<1 )
)
{
return css::uno::Any();
}
// parse given URL
/* SAFE { */
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::util::XURLTransformer > xParser(m_xSMGR->createInstance(SERVICENAME_URLTRANSFORMER), css::uno::UNO_QUERY);
aReadLock.unlock();
/* } SAFE */
css::util::URL aURL;
aURL.Complete = sURL;
xParser->parseStrict(aURL);
// search dispatcher
css::uno::Reference< css::frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, sTargetFrameName, nSearchFlags);
css::uno::Reference< css::frame::XNotifyingDispatch > xNotifyDispatch (xDispatch, css::uno::UNO_QUERY);
// make sure that synchronous execution is used (if possible)
css::uno::Sequence< css::beans::PropertyValue > aArguments( lArguments );
sal_Int32 nLength = lArguments.getLength();
aArguments.realloc( nLength + 1 );
aArguments[ nLength ].Name = ::rtl::OUString::createFromAscii("SynchronMode");
aArguments[ nLength ].Value <<= (sal_Bool) sal_True;
css::uno::Any aResult;
if (xNotifyDispatch.is())
{
// dispatch it with guaranteed notification
// Here we can hope for a result ... instead of the normal dispatch.
css::uno::Reference< css::frame::XDispatchResultListener > xListener(xTHIS, css::uno::UNO_QUERY);
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_xBroadcaster = css::uno::Reference< css::uno::XInterface >(xNotifyDispatch, css::uno::UNO_QUERY);
m_aResult = css::uno::Any();
m_aBlock.reset();
aWriteLock.unlock();
/* } SAFE */
// dispatch it and wait for a notification
// TODO/MBA: waiting in main thread?!
xNotifyDispatch->dispatchWithNotification(aURL, aArguments, xListener);
//m_aBlock.wait();
aResult = m_aResult;
}
else
if (xDispatch.is())
{
// dispatch it without any chance to get a result
xDispatch->dispatch( aURL, aArguments );
}
return aResult;
}
//_______________________________________________
/** callback for started dispatch with guaranteed notifications.
We must save the result, so the method executeDispatch() can return it.
Further we must release the broadcaster (otherwhise it can't die)
and unblock the waiting executeDispatch() request.
@param aResult
describes the result of the dispatch operation
*/
void SAL_CALL DispatchHelper::dispatchFinished( const css::frame::DispatchResultEvent& aResult )
throw(css::uno::RuntimeException)
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_aResult <<= aResult;
m_aBlock.set();
m_xBroadcaster.clear();
/* } SAFE */
}
//_______________________________________________
/** we has to realease our broadcaster reference.
@param aEvent
describe the source of this event and MUST be our save broadcaster!
*/
void SAL_CALL DispatchHelper::disposing( const css::lang::EventObject& )
throw(css::uno::RuntimeException)
{
/* SAFE { */
WriteGuard aWriteLock(m_aLock);
m_aResult.clear();
m_aBlock.set();
m_xBroadcaster.clear();
/* } SAFE */
}
}
<|endoftext|>
|
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Brent A. Fulgham <bfulgham@debian.org>
* Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#ifndef _Profiler_hh
#define _Profiler_hh
#include <Prague/Sys/ntree.hh>
#include <ctime>
#include <iostream>
#include <string>
#include <iomanip.h>
namespace Prague
{
struct CheckPoint
{
CheckPoint(const string &s) : name(s), count(0), start(0), stop(0), elapsed(0) {}
CheckPoint(CheckPoint *cp)
: name(cp->name),
count(cp->count),
start(cp->start),
stop(cp->stop),
elapsed(cp->elapsed)
{}
void indent(ostream &os, unsigned short ind) { while (ind--) os.put(' ');}
void output(ostream &os, unsigned short ind)
{
indent(os, ind); os << name << ": " << setw(10) << count;
indent(os, ind); os << " Times. Total Time: ";
indent(os, ind); os << setprecision(8) << setw(12);
indent(os, ind); os.setf( ios::fixed, ios::floatfield);
indent(os, ind); os << elapsed/CLOCKS_PER_SEC;
indent(os, ind); os << " Avg/Iter.: ";
indent(os, ind); os << setprecision(8) << setw(12);
indent(os, ind); os << elapsed/count/CLOCKS_PER_SEC << endl;
}
string name;
long count;
clock_t start;
clock_t stop;
double elapsed;
};
class Profiler
{
typedef ntree<CheckPoint *> table_t;
typedef ntree<CheckPoint *>::node item_t;
typedef ntree<CheckPoint *>::node::child_iterator child_iterator;
typedef ntree<CheckPoint *>::node::const_child_iterator const_child_iterator;
typedef ntree<CheckPoint *>::node::up_iterator up_iterator;
public:
Profiler(const string &name)
{
if (!count++)
{
table = new table_t(new CheckPoint("root"));
current = &table->root();
os = &cout;
}
child_iterator i = lookup(name);
current = &*i;
current->value->count++;
current->value->start = clock();
}
~Profiler()
{
current->value->stop = clock();
current->value->elapsed += (current->value->stop - current->value->start);
up_iterator i = current->up_begin();
current = &*++i;
if (!--count)
{
dump(*current, 0);
clean(*current);
}
}
static void setOutput(ostream &o) { os = &o;}
private:
static child_iterator lookup(const string &name)
{
for (child_iterator i = current->child_begin(); i != current->child_end(); i++)
if ((*i).value->name == name) return i;
return current->push_back(new CheckPoint(name));
}
static void dump(const item_t &root, unsigned short ind)
{
for (const_child_iterator i = root.child_begin(); i != root.child_end(); i++)
dump(*i, ind + 1);
if (ind) root.value->output(*os, ind); // don't output the root
}
void dump() { dump(*current, 0);}
static void clean(const item_t &root)
{
for (const_child_iterator i = root.child_begin(); i != root.child_end(); i++)
clean(*i);
delete root.value;
}
static long count;
static table_t *table;
static item_t *current;
static ostream *os;
};
};
#endif /* _Profiler_hh */
<commit_msg>*** empty log message ***<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Brent A. Fulgham <bfulgham@debian.org>
* Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#ifndef _Profiler_hh
#define _Profiler_hh
#include <Prague/Sys/ntree.hh>
#include <ctime>
#include <iostream>
#include <string>
#include <iomanip.h>
namespace Prague
{
struct CheckPoint
{
CheckPoint(const string &s) : name(s), count(0), start(0), stop(0), elapsed(0) {}
CheckPoint(CheckPoint *cp)
: name(cp->name),
count(cp->count),
start(cp->start),
stop(cp->stop),
elapsed(cp->elapsed)
{}
void indent(ostream &os, unsigned short ind) { while (ind--) os.put(' ');}
void output(ostream &os, unsigned short ind)
{
indent(os, ind);
os << name << ": " << setw(10) << count;
os << " Times. Total Time: ";
os << setprecision(8) << setw(12);
os.setf( ios::fixed, ios::floatfield);
os << elapsed/CLOCKS_PER_SEC;
os << " Avg/Iter.: ";
os << setprecision(8) << setw(12);
os << elapsed/count/CLOCKS_PER_SEC << endl;
}
string name;
long count;
clock_t start;
clock_t stop;
double elapsed;
};
class Profiler
{
typedef ntree<CheckPoint *> table_t;
typedef ntree<CheckPoint *>::node item_t;
typedef ntree<CheckPoint *>::node::child_iterator child_iterator;
typedef ntree<CheckPoint *>::node::const_child_iterator const_child_iterator;
typedef ntree<CheckPoint *>::node::up_iterator up_iterator;
public:
Profiler(const string &name)
{
if (!count++)
{
table = new table_t(new CheckPoint("root"));
current = &table->root();
os = &cout;
}
child_iterator i = lookup(name);
current = &*i;
current->value->count++;
current->value->start = clock();
}
~Profiler()
{
current->value->stop = clock();
current->value->elapsed += (current->value->stop - current->value->start);
up_iterator i = current->up_begin();
current = &*++i;
if (!--count)
{
dump(*current, 0);
clean(*current);
delete table;
}
}
static void setOutput(ostream &o) { os = &o;}
static void dump() { dump(*current, 0);}
private:
static child_iterator lookup(const string &name)
{
for (child_iterator i = current->child_begin(); i != current->child_end(); i++)
if ((*i).value->name == name) return i;
return current->push_back(new CheckPoint(name));
}
static void dump(const item_t &root, unsigned short ind)
{
for (const_child_iterator i = root.child_begin(); i != root.child_end(); i++)
dump(*i, ind + 1);
if (ind) root.value->output(*os, ind); // don't output the root
}
static void clean(const item_t &root)
{
for (const_child_iterator i = root.child_begin(); i != root.child_end(); i++)
clean(*i);
delete root.value;
}
static long count;
static table_t *table;
static item_t *current;
static ostream *os;
};
};
#endif /* _Profiler_hh */
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include "Endian.h"
TEST(EndianTest, TestBitSwap) {
uint64_t x = 0x0123456789abcdefull;
uint64_t rev_x = 0xefcdab8967452301ull;
EXPECT_EQ(rev_x, bswap_64(x));
uint32_t y = 0x01234567;
uint32_t rev_y = 0x67452301;
EXPECT_EQ(rev_y, bswap_32(y));
uint16_t z = 0x0123;
uint16_t rev_z = 0x2301;
EXPECT_EQ(rev_z, bswap_16(z));
}<commit_msg>added another single test<commit_after>#include <gtest/gtest.h>
#include "Endian.h"
TEST(EndianTest, TestBitSwap) {
uint64_t x = 0x0123456789abcdefull;
uint64_t rev_x = 0xefcdab8967452301ull;
EXPECT_EQ(rev_x, bswap_64(x));
uint32_t y = 0x01234567;
uint32_t rev_y = 0x67452301;
EXPECT_EQ(rev_y, bswap_32(y));
uint16_t z = 0x0123;
uint16_t rev_z = 0x2301;
EXPECT_EQ(rev_z, bswap_16(z));
uint64_t w = 0x0123456789abcdefull;
EXPECT_EQ(w, bswap_64(bswap_64(w)));
}<|endoftext|>
|
<commit_before>#include "Test.h"
#include <string>
using namespace std;
extern "C" int test_snprintf(char *, size_t, const char *, ...);
class SnprintfTest : public evil::Test {};
TEST_F(SnprintfTest, no_args) {
char dst[sizeof("abc")];
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "abc"));
EXPECT_EQ("abc"s, string(dst));
}
TEST_F(SnprintfTest, format_invalid) {
char dst[sizeof("%?")];
evil::UBChecker checker{1};
EXPECT_EQ(2, test_snprintf(dst, sizeof(dst), "%?"));
EXPECT_EQ("%?"s, string(dst));
}
TEST_F(SnprintfTest, format_string) {
char dst[16];
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "AB%s", "abc"));
EXPECT_EQ("ABabc"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "A%sB", "abc"));
EXPECT_EQ("AabcB"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "%sAB", "abc"));
EXPECT_EQ("abcAB"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "% 5s", "abc"));
EXPECT_EQ(" abc"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%.3s", "abcde"));
EXPECT_EQ("abc"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "% 5.3s", "abcde"));
EXPECT_EQ(" abc"s, string(dst));
{
evil::UBChecker checker{1};
EXPECT_EQ(6, test_snprintf(dst, sizeof(dst), "%s", NULL));
EXPECT_EQ("(null)"s, string(dst));
}
}
TEST_F(SnprintfTest, format_char) {
char dst[sizeof("xAB")];
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "AB%c", 'a'));
EXPECT_EQ("ABa"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "A%cB", 'a'));
EXPECT_EQ("AaB"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%cAB", 'a'));
EXPECT_EQ("aAB"s, string(dst));
}
TEST_F(SnprintfTest, format_char_outside_range) {
char dst[sizeof("A")];
EXPECT_EQ(1, test_snprintf(dst, sizeof(dst), "%c", 'A' - 256));
EXPECT_EQ("A"s, string(dst));
EXPECT_EQ(1, test_snprintf(dst, sizeof(dst), "%c", 'A' + 256));
EXPECT_EQ("A"s, string(dst));
}
TEST_F(SnprintfTest, format_int) {
char dst[16];
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%d", 123));
EXPECT_EQ("123"s, string(dst));
EXPECT_EQ(4, test_snprintf(dst, sizeof(dst), "%d", -123));
EXPECT_EQ("-123"s, string(dst));
}
<commit_msg>Tests for loading width/precision from argument<commit_after>#include "Test.h"
#include <string>
using namespace std;
extern "C" int test_snprintf(char *, size_t, const char *, ...);
class SnprintfTest : public evil::Test {};
TEST_F(SnprintfTest, no_args) {
char dst[sizeof("abc")];
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "abc"));
EXPECT_EQ("abc"s, string(dst));
}
TEST_F(SnprintfTest, format_invalid) {
char dst[sizeof("%?")];
evil::UBChecker checker{1};
EXPECT_EQ(2, test_snprintf(dst, sizeof(dst), "%?"));
EXPECT_EQ("%?"s, string(dst));
}
TEST_F(SnprintfTest, format_string) {
char dst[16];
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "AB%s", "abc"));
EXPECT_EQ("ABabc"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "A%sB", "abc"));
EXPECT_EQ("AabcB"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "%sAB", "abc"));
EXPECT_EQ("abcAB"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "% 5s", "abc"));
EXPECT_EQ(" abc"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%.3s", "abcde"));
EXPECT_EQ("abc"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "% 5.3s", "abcde"));
EXPECT_EQ(" abc"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "% *s", 5, "abc"));
EXPECT_EQ(" abc"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%.*s", 3, "abcde"));
EXPECT_EQ("abc"s, string(dst));
EXPECT_EQ(5, test_snprintf(dst, sizeof(dst), "% *.*s", 5, 3, "abcde"));
EXPECT_EQ(" abc"s, string(dst));
{
evil::UBChecker checker{1};
EXPECT_EQ(6, test_snprintf(dst, sizeof(dst), "%s", NULL));
EXPECT_EQ("(null)"s, string(dst));
}
}
TEST_F(SnprintfTest, format_char) {
char dst[sizeof("xAB")];
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "AB%c", 'a'));
EXPECT_EQ("ABa"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "A%cB", 'a'));
EXPECT_EQ("AaB"s, string(dst));
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%cAB", 'a'));
EXPECT_EQ("aAB"s, string(dst));
}
TEST_F(SnprintfTest, format_char_outside_range) {
char dst[sizeof("A")];
EXPECT_EQ(1, test_snprintf(dst, sizeof(dst), "%c", 'A' - 256));
EXPECT_EQ("A"s, string(dst));
EXPECT_EQ(1, test_snprintf(dst, sizeof(dst), "%c", 'A' + 256));
EXPECT_EQ("A"s, string(dst));
}
TEST_F(SnprintfTest, format_int) {
char dst[16];
EXPECT_EQ(3, test_snprintf(dst, sizeof(dst), "%d", 123));
EXPECT_EQ("123"s, string(dst));
EXPECT_EQ(4, test_snprintf(dst, sizeof(dst), "%d", -123));
EXPECT_EQ("-123"s, string(dst));
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperQtWidgetListEditItemModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperStringListInterface.h"
namespace otb
{
namespace Wrapper
{
/*
TRANSLATOR otb::Wapper::ListEditItemModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
const char * const
HEADERS[ ListEditItemModel::COLUMN_COUNT ] =
{
QT_TRANSLATE_NOOP( "otb::Wrapper::ListEditItemModel", "Name" ),
// QT_TRANSLATE_NOOP( "otb::Wrapper::ListEditItemModel", "Browse" ),
};
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
ListEditItemModel
::ListEditItemModel( StringListInterface * sli,
QObject * p ) :
QAbstractItemModel( p ),
m_StringList( sli )
{
assert( sli!=nullptr );
}
/*******************************************************************************/
ListEditItemModel
::~ListEditItemModel()
{
}
/*****************************************************************************/
/* QAbstractItemModel overloads */
/*****************************************************************************/
int
ListEditItemModel
::columnCount( const QModelIndex & ) const
{
// qDebug() << this << "::columnCount(" << parent << ")";
return COLUMN_COUNT;
}
/*****************************************************************************/
QVariant
ListEditItemModel
::data( const QModelIndex & idx, int role ) const
{
// qDebug() << this << "::data(" << idx << "," << role << ")";
// Get layer.
assert( m_StringList!=NULL );
assert( idx.isValid() );
assert( !idx.parent().isValid() );
assert( idx.internalPointer()!=NULL );
const StringListInterface * stringList =
static_cast< const StringListInterface * >( idx.internalPointer() );
assert( stringList!=nullptr );
// Return data given role.
switch( role )
{
case Qt::CheckStateRole:
#if 0
if( idx.column()!=COLUMN_NAME )
return QVariant();
else
{
assert( idx.row() >= 0 );
return stringList->IsActive( idx.row() );
}
#endif
break;
case Qt::EditRole:
case Qt::DisplayRole:
switch( idx.column() )
{
case COLUMN_NAME:
{
assert( idx.row() >= 0 );
std::string filename(
stringList->GetNthFileName( idx.row() )
);
// qDebug() << "Filename:" << QString( "%1" ).arg( filename.c_str() );
return
filename.empty()
? ( role==Qt::EditRole ? QString() : "EMPTY" )
: QFile::decodeName( filename.c_str()
);
}
break;
default:
break;
}
break;
case Qt::FontRole:
break;
case Qt::ToolTipRole:
switch( idx.column() )
{
case COLUMN_NAME:
assert( idx.row() >= 0 );
return QString::fromStdString( stringList->GetToolTip( idx.row() ) );
break;
}
break;
case USER_ROLE_DIRECTION:
assert( idx.row()>=0 );
return stringList->GetDirection( idx.row() );
break;
case USER_ROLE_FILTER:
assert( idx.row()>=0 );
return QString::fromStdString( stringList->GetFilenameFilter( idx.row() ) );
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
Qt::ItemFlags
ListEditItemModel
::flags( const QModelIndex & idx ) const
{
if( !idx.isValid() )
return QAbstractItemModel::flags( idx );
Qt::ItemFlags iflags =
QAbstractItemModel::flags( idx )
// | Qt::ItemIsDragEnabled
// | Qt::ItemIsDropEnabled
;
if( idx.column()==COLUMN_NAME )
iflags |=
Qt::ItemIsEditable
// | Qt::ItemIsUserCheckable
// | Qt::ItemIsDragEnabled
;
return iflags;
}
/*****************************************************************************/
bool
ListEditItemModel
::hasChildren( const QModelIndex & idx ) const
{
return !idx.isValid();
}
/*****************************************************************************/
QVariant
ListEditItemModel
::headerData( int section,
Qt::Orientation /**orientation*/,
int role ) const
{
// qDebug()
// << this << "::headerData("
// << section << "," << orientation << "," << role
// << ")";
// assert( orientation==Qt::Horizontal );
switch( role )
{
case Qt::DisplayRole:
assert( section>=0 && section<COLUMN_COUNT );
return tr( HEADERS[ section ] );
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::index( int row,
int column,
const QModelIndex & p ) const
{
// qDebug()
// << this << "::index(" << row << "," << column << "," << parent << ")";
if( m_StringList == nullptr )
return QModelIndex();
// qDebug()
// << "index:" << row << "," << column << "," << m_StringList->At( row );
assert( row>=0 && column>=0 );
#if 0
AbstractLayerModel * layer = m_StringList->At( row );
if( layer==NULL || p.isValid() )
return QModelIndex();
#endif
return
createIndex(
row,
column,
p.isValid()
? NULL
: m_StringList
);
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRow( int row, const QModelIndex & parent )
{
return insertRows( row, 1, parent );
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRows( int row, int count, const QModelIndex & parent )
{
// qDebug() << this << "::insertRows(" << row << "," << count << "," << parent << ")";
assert( m_StringList!=nullptr );
beginInsertRows( parent, row, count );
{
for( int r=row; r<row+count; ++r )
m_StringList->Insert( "", r );
}
endInsertRows();
return true;
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::parent( const QModelIndex & ) const
{
// qDebug() << this << "::parent(" << index << ")";
return QModelIndex();
}
/*****************************************************************************/
bool
ListEditItemModel
::removeRows( int row, int count, const QModelIndex & p )
{
assert( !p.isValid() );
assert( count==1 );
if( p.isValid() || count!=1 )
return false;
assert( m_StringList!=nullptr );
beginRemoveRows( p, row, row + count - 1 );
{
m_StringList->Erase( row, count );
}
endRemoveRows();
return true;
}
/*****************************************************************************/
int
ListEditItemModel
::rowCount( const QModelIndex & p ) const
{
// qDebug() << this << "::rowCount(" << p << ")";
// qDebug() << "row-count:" <<
// ( ( m_StringList==NULL || p.isValid() )
// ? 0
// : m_StringList->GetCount()
// );
return
( m_StringList==nullptr || p.isValid() )
? 0
: m_StringList->Size();
}
/*****************************************************************************/
bool
ListEditItemModel
::setData( const QModelIndex & idx,
const QVariant & value,
int role )
{
// qDebug()
// << this << "::setData(" << idx << "," << value << "," << role
// << ");";
assert( !idx.parent().isValid() );
assert( idx.row()>=0 );
assert( idx.internalPointer()!=nullptr );
StringListInterface * stringList =
static_cast< StringListInterface * >( idx.internalPointer() );
switch( idx.column() )
{
case COLUMN_NAME:
switch( role )
{
case Qt::EditRole:
stringList->SetNthFileName(
idx.row(),
QFile::encodeName( value.toString() ).data()
);
emit dataChanged( idx, idx );
return true;
break;
case Qt::CheckStateRole:
break;
case USER_ROLE_DIRECTION:
break;
default:
break;
}
break;
default:
break;
}
return false;
}
/*******************************************************************************/
bool
ListEditItemModel
::Swap( int row1, int row2 )
{
assert( m_StringList!=nullptr );
assert( row1>=0 );
assert( static_cast< unsigned int >( row1 )<m_StringList->Size() );
assert( row2>=0 );
assert( static_cast< unsigned int >( row2 )<m_StringList->Size() );
assert( row1!=row2 );
emit layoutAboutToBeChanged();
m_StringList->Swap( row1, row2 );
emit layoutChanged();
return true;
}
/*******************************************************************************/
bool
ListEditItemModel
::IsInput() const
{
assert( m_StringList!=nullptr );
return m_StringList->GetDirection()==Role_Input;
}
/*******************************************************************************/
bool
ListEditItemModel
::IsBrowsable() const
{
assert( m_StringList!=nullptr );
return m_StringList->IsFilename();
}
/*******************************************************************************/
QString
ListEditItemModel
::GetFilter() const
{
assert( m_StringList!=nullptr );
return QString::fromStdString( m_StringList->GetFilenameFilter() );
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
} // end namespace 'Wrapper'.
} // end namespace 'otb'
<commit_msg>ENH: Fixed ListEditItemModel::removeAll().<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperQtWidgetListEditItemModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperStringListInterface.h"
namespace otb
{
namespace Wrapper
{
/*
TRANSLATOR otb::Wapper::ListEditItemModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
const char * const
HEADERS[ ListEditItemModel::COLUMN_COUNT ] =
{
QT_TRANSLATE_NOOP( "otb::Wrapper::ListEditItemModel", "Name" ),
// QT_TRANSLATE_NOOP( "otb::Wrapper::ListEditItemModel", "Browse" ),
};
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
ListEditItemModel
::ListEditItemModel( StringListInterface * sli,
QObject * p ) :
QAbstractItemModel( p ),
m_StringList( sli )
{
assert( sli!=nullptr );
}
/*******************************************************************************/
ListEditItemModel
::~ListEditItemModel()
{
}
/*****************************************************************************/
/* QAbstractItemModel overloads */
/*****************************************************************************/
int
ListEditItemModel
::columnCount( const QModelIndex & ) const
{
// qDebug() << this << "::columnCount(" << parent << ")";
return COLUMN_COUNT;
}
/*****************************************************************************/
QVariant
ListEditItemModel
::data( const QModelIndex & idx, int role ) const
{
// qDebug() << this << "::data(" << idx << "," << role << ")";
// Get layer.
assert( m_StringList!=NULL );
assert( idx.isValid() );
assert( !idx.parent().isValid() );
assert( idx.internalPointer()!=NULL );
const StringListInterface * stringList =
static_cast< const StringListInterface * >( idx.internalPointer() );
assert( stringList!=nullptr );
// Return data given role.
switch( role )
{
case Qt::CheckStateRole:
#if 0
if( idx.column()!=COLUMN_NAME )
return QVariant();
else
{
assert( idx.row() >= 0 );
return stringList->IsActive( idx.row() );
}
#endif
break;
case Qt::EditRole:
case Qt::DisplayRole:
switch( idx.column() )
{
case COLUMN_NAME:
{
assert( idx.row() >= 0 );
std::string filename(
stringList->GetNthFileName( idx.row() )
);
// qDebug() << "Filename:" << QString( "%1" ).arg( filename.c_str() );
return
filename.empty()
? ( role==Qt::EditRole ? QString() : "EMPTY" )
: QFile::decodeName( filename.c_str()
);
}
break;
default:
break;
}
break;
case Qt::FontRole:
break;
case Qt::ToolTipRole:
switch( idx.column() )
{
case COLUMN_NAME:
assert( idx.row() >= 0 );
return QString::fromStdString( stringList->GetToolTip( idx.row() ) );
break;
}
break;
case USER_ROLE_DIRECTION:
assert( idx.row()>=0 );
return stringList->GetDirection( idx.row() );
break;
case USER_ROLE_FILTER:
assert( idx.row()>=0 );
return QString::fromStdString( stringList->GetFilenameFilter( idx.row() ) );
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
Qt::ItemFlags
ListEditItemModel
::flags( const QModelIndex & idx ) const
{
if( !idx.isValid() )
return QAbstractItemModel::flags( idx );
Qt::ItemFlags iflags =
QAbstractItemModel::flags( idx )
// | Qt::ItemIsDragEnabled
// | Qt::ItemIsDropEnabled
;
if( idx.column()==COLUMN_NAME )
iflags |=
Qt::ItemIsEditable
// | Qt::ItemIsUserCheckable
// | Qt::ItemIsDragEnabled
;
return iflags;
}
/*****************************************************************************/
bool
ListEditItemModel
::hasChildren( const QModelIndex & idx ) const
{
return !idx.isValid();
}
/*****************************************************************************/
QVariant
ListEditItemModel
::headerData( int section,
Qt::Orientation /**orientation*/,
int role ) const
{
// qDebug()
// << this << "::headerData("
// << section << "," << orientation << "," << role
// << ")";
// assert( orientation==Qt::Horizontal );
switch( role )
{
case Qt::DisplayRole:
assert( section>=0 && section<COLUMN_COUNT );
return tr( HEADERS[ section ] );
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::index( int row,
int column,
const QModelIndex & p ) const
{
// qDebug()
// << this << "::index(" << row << "," << column << "," << parent << ")";
if( m_StringList == nullptr )
return QModelIndex();
// qDebug()
// << "index:" << row << "," << column << "," << m_StringList->At( row );
assert( row>=0 && column>=0 );
#if 0
AbstractLayerModel * layer = m_StringList->At( row );
if( layer==NULL || p.isValid() )
return QModelIndex();
#endif
return
createIndex(
row,
column,
p.isValid()
? NULL
: m_StringList
);
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRow( int row, const QModelIndex & parent )
{
return insertRows( row, 1, parent );
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRows( int row, int count, const QModelIndex & parent )
{
// qDebug() << this << "::insertRows(" << row << "," << count << "," << parent << ")";
assert( m_StringList!=nullptr );
beginInsertRows( parent, row, count );
{
for( int r=row; r<row+count; ++r )
m_StringList->Insert( "", r );
}
endInsertRows();
return true;
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::parent( const QModelIndex & ) const
{
// qDebug() << this << "::parent(" << index << ")";
return QModelIndex();
}
/*****************************************************************************/
bool
ListEditItemModel
::removeRows( int row, int count, const QModelIndex & p )
{
assert( !p.isValid() );
assert( count>=1 );
if( p.isValid() || count<1 )
return false;
assert( m_StringList!=nullptr );
beginRemoveRows( p, row, row + count - 1 );
{
m_StringList->Erase( row, count );
}
endRemoveRows();
return true;
}
/*****************************************************************************/
int
ListEditItemModel
::rowCount( const QModelIndex & p ) const
{
// qDebug() << this << "::rowCount(" << p << ")";
// qDebug() << "row-count:" <<
// ( ( m_StringList==NULL || p.isValid() )
// ? 0
// : m_StringList->GetCount()
// );
return
( m_StringList==nullptr || p.isValid() )
? 0
: m_StringList->Size();
}
/*****************************************************************************/
bool
ListEditItemModel
::setData( const QModelIndex & idx,
const QVariant & value,
int role )
{
// qDebug()
// << this << "::setData(" << idx << "," << value << "," << role
// << ");";
assert( !idx.parent().isValid() );
assert( idx.row()>=0 );
assert( idx.internalPointer()!=nullptr );
StringListInterface * stringList =
static_cast< StringListInterface * >( idx.internalPointer() );
switch( idx.column() )
{
case COLUMN_NAME:
switch( role )
{
case Qt::EditRole:
stringList->SetNthFileName(
idx.row(),
QFile::encodeName( value.toString() ).data()
);
emit dataChanged( idx, idx );
return true;
break;
case Qt::CheckStateRole:
break;
case USER_ROLE_DIRECTION:
break;
default:
break;
}
break;
default:
break;
}
return false;
}
/*******************************************************************************/
bool
ListEditItemModel
::Swap( int row1, int row2 )
{
assert( m_StringList!=nullptr );
assert( row1>=0 );
assert( static_cast< unsigned int >( row1 )<m_StringList->Size() );
assert( row2>=0 );
assert( static_cast< unsigned int >( row2 )<m_StringList->Size() );
assert( row1!=row2 );
emit layoutAboutToBeChanged();
m_StringList->Swap( row1, row2 );
emit layoutChanged();
return true;
}
/*******************************************************************************/
bool
ListEditItemModel
::IsInput() const
{
assert( m_StringList!=nullptr );
return m_StringList->GetDirection()==Role_Input;
}
/*******************************************************************************/
bool
ListEditItemModel
::IsBrowsable() const
{
assert( m_StringList!=nullptr );
return m_StringList->IsFilename();
}
/*******************************************************************************/
QString
ListEditItemModel
::GetFilter() const
{
assert( m_StringList!=nullptr );
return QString::fromStdString( m_StringList->GetFilenameFilter() );
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
} // end namespace 'Wrapper'.
} // end namespace 'otb'
<|endoftext|>
|
<commit_before>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
* Copyright 2011 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <Configuration.h>
// Load configuration from a file.
ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");
#include <TRXManager.h>
#include <GSML1FEC.h>
#include <GSMConfig.h>
#include <GSMSAPMux.h>
#include <GSML3RRMessages.h>
#include <GSMLogicalChannel.h>
#include <ControlCommon.h>
#include <TransactionTable.h>
#include <SIPInterface.h>
#include <Globals.h>
#include <Logger.h>
#include <CLI.h>
#include <PowerManager.h>
#include <Configuration.h>
#include <PhysicalStatus.h>
#include <SubscriberRegistry.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#ifdef HAVE_LIBREADLINE // [
//# include <stdio.h>
# include <readline/readline.h>
# include <readline/history.h>
#endif // HAVE_LIBREADLINE ]
using namespace std;
using namespace GSM;
const char* gDateTime = __DATE__ " " __TIME__;
// All of the other globals that rely on the global configuration file need to
// be declared here.
// The TMSI Table.
Control::TMSITable gTMSITable(gConfig.getStr("Control.Reporting.TMSITable").c_str());
// The transaction table.
Control::TransactionTable gTransactionTable;
// Physical status reporting
GSM::PhysicalStatus gPhysStatus(gConfig.getStr("Control.Reporting.PhysStatusTable").c_str());
// The global SIPInterface object.
SIP::SIPInterface gSIPInterface;
// Configure the BTS object based on the config file.
// So don't create this until AFTER loading the config file.
GSMConfig gBTS;
// Our interface to the software-defined radio.
TransceiverManager gTRX(gConfig.getStr("TRX.IP").c_str(), gConfig.getNum("TRX.Port"));
// Subscriber registry
SubscriberRegistry gSubscriberRegistry;
/** Define a function to call any time the configuration database changes. */
void purgeConfig(void*,int,char const*, char const*, sqlite3_int64)
{
LOG(INFO) << "purging configuration cache";
gConfig.purge();
gBTS.regenerateBeacon();
}
const char* transceiverPath = "./transceiver";
pid_t gTransceiverPid = 0;
void startTransceiver()
{
// Start the transceiver binary, if the path is defined.
// If the path is not defined, the transceiver must be started by some other process.
char TRXnumARFCN[4];
sprintf(TRXnumARFCN,"%1d",1);
LOG(NOTICE) << "starting transceiver " << transceiverPath << " " << TRXnumARFCN;
gTransceiverPid = vfork();
LOG_ASSERT(gTransceiverPid>=0);
if (gTransceiverPid==0) {
// Pid==0 means this is the process that starts the transceiver.
execlp(transceiverPath,transceiverPath,TRXnumARFCN,NULL);
LOG(EMERG) << "cannot find " << transceiverPath;
_exit(1);
}
}
int main(int argc, char *argv[])
{
try {
srandom(time(NULL));
gConfig.setUpdateHook(purgeConfig);
gLogInit("openbts",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);
LOG(ALERT) << "OpenBTS starting, ver " << VERSION << " build date " << __DATE__;
COUT("\n\n" << gOpenBTSWelcome << "\n");
COUT("\nStarting the system...");
startTransceiver();
// Start the SIP interface.
gSIPInterface.start();
//
// Configure the radio.
//
// Start the transceiver interface.
// Sleep long enough for the USRP to bootload.
sleep(5);
gTRX.start();
// Set up the interface to the radio.
// Get a handle to the C0 transceiver interface.
ARFCNManager* C0radio = gTRX.ARFCN();
// Tuning.
// Make sure its off for tuning.
C0radio->powerOff();
// Get the ARFCN list.
unsigned C0 = gConfig.getNum("GSM.Radio.C0");
// Tune the radio.
LOG(INFO) << "tuning TRX to ARFCN " << C0;
ARFCNManager* radio = gTRX.ARFCN();
radio->tune(C0);
// Set TSC same as BCC everywhere.
C0radio->setTSC(gBTS.BCC());
// Set maximum expected delay spread.
C0radio->setMaxDelay(gConfig.getNum("GSM.Radio.MaxExpectedDelaySpread"));
// Set Receiver Gain
C0radio->setRxGain(gConfig.getNum("GSM.Radio.RxGain"));
// Turn on and power up.
C0radio->powerOn();
C0radio->setPower(gConfig.getNum("GSM.Radio.PowerManager.MinAttenDB"));
//
// Create a C-V channel set on C0T0.
//
// C-V on C0T0
C0radio->setSlot(0,5);
// SCH
SCHL1FEC SCH;
SCH.downstream(C0radio);
SCH.open();
// FCCH
FCCHL1FEC FCCH;
FCCH.downstream(C0radio);
FCCH.open();
// BCCH
BCCHL1FEC BCCH;
BCCH.downstream(C0radio);
BCCH.open();
// RACH
RACHL1FEC RACH(gRACHC5Mapping);
RACH.downstream(C0radio);
RACH.open();
// CCCHs
CCCHLogicalChannel CCCH0(gCCCH_0Mapping);
CCCH0.downstream(C0radio);
CCCH0.open();
CCCHLogicalChannel CCCH1(gCCCH_1Mapping);
CCCH1.downstream(C0radio);
CCCH1.open();
CCCHLogicalChannel CCCH2(gCCCH_2Mapping);
CCCH2.downstream(C0radio);
CCCH2.open();
// use CCCHs as AGCHs
gBTS.addAGCH(&CCCH0);
gBTS.addAGCH(&CCCH1);
gBTS.addAGCH(&CCCH2);
// C-V C0T0 SDCCHs
SDCCHLogicalChannel C0T0SDCCH[4] = {
SDCCHLogicalChannel(0,gSDCCH_4_0),
SDCCHLogicalChannel(0,gSDCCH_4_1),
SDCCHLogicalChannel(0,gSDCCH_4_2),
SDCCHLogicalChannel(0,gSDCCH_4_3),
};
Thread C0T0SDCCHControlThread[4];
for (int i=0; i<4; i++) {
C0T0SDCCH[i].downstream(C0radio);
C0T0SDCCHControlThread[i].start((void*(*)(void*))Control::DCCHDispatcher,&C0T0SDCCH[i]);
C0T0SDCCH[i].open();
gBTS.addSDCCH(&C0T0SDCCH[i]);
}
//
// Configure the other slots.
//
// Count configured slots.
unsigned sCount = 1;
if (gConfig.defines("GSM.Channels.C1sFirst")) {
// Create C-I slots.
for (int i=0; i<gConfig.getNum("GSM.Channels.NumC1s"); i++) {
gBTS.createCombinationI(gTRX,sCount);
sCount++;
}
}
// Create C-VII slots.
for (int i=0; i<gConfig.getNum("GSM.Channels.NumC7s"); i++) {
gBTS.createCombinationVII(gTRX,sCount);
sCount++;
}
if (!gConfig.defines("GSM.Channels.C1sFirst")) {
// Create C-I slots.
for (int i=0; i<gConfig.getNum("GSM.Channels.NumC1s"); i++) {
gBTS.createCombinationI(gTRX,sCount);
sCount++;
}
}
// Set up idle filling on C0 as needed.
while (sCount<8) {
gBTS.createCombination0(gTRX,sCount);
sCount++;
}
/*
Note: The number of different paging subchannels on
the CCCH is:
MAX(1,(3 - BS-AG-BLKS-RES)) * BS-PA-MFRMS
if CCCH-CONF = "001"
(9 - BS-AG-BLKS-RES) * BS-PA-MFRMS
for other values of CCCH-CONF
*/
// Set up the pager.
// Set up paging channels.
// HACK -- For now, use a single paging channel, since paging groups are broken.
gBTS.addPCH(&CCCH2);
// Be sure we are not over-reserving.
LOG_ASSERT(gConfig.getNum("GSM.CCCH.PCH.Reserve")<(int)gBTS.numAGCHs());
// OK, now it is safe to start the BTS.
gBTS.start();
#ifdef HAVE_LIBREADLINE // [
// start console
using_history();
static const char * const history_file_name = "/.openbts_history";
char *history_name = 0;
char *home_dir = getenv("HOME");
if(home_dir) {
size_t home_dir_len = strlen(home_dir);
size_t history_file_len = strlen(history_file_name);
size_t history_len = home_dir_len + history_file_len + 1;
if(history_len > home_dir_len) {
if(!(history_name = (char *)malloc(history_len))) {
LOG(ERR) << "malloc failed: " << strerror(errno);
exit(2);
}
memcpy(history_name, home_dir, home_dir_len);
memcpy(history_name + home_dir_len, history_file_name,
history_file_len + 1);
read_history(history_name);
}
}
#endif // HAVE_LIBREADLINE ]
LOG(INFO) << "system ready";
COUT("\n\nWelcome to OpenBTS. Type \"help\" to see available commands.");
// FIXME: We want to catch control-d (emacs keybinding for exit())
// The logging parts were removed from this loop.
// If we want them back, they will need to go into their own thread.
while (1) {
#ifdef HAVE_LIBREADLINE // [
char *inbuf = readline(gConfig.getStr("CLI.Prompt").c_str());
if (!inbuf) break;
if (*inbuf) {
add_history(inbuf);
// The parser returns -1 on exit.
if (gParser.process(inbuf, cout, cin)<0) {
free(inbuf);
break;
}
}
free(inbuf);
#else // HAVE_LIBREADLINE ][
cout << endl << gConfig.getStr("CLI.Prompt");
cout.flush();
char inbuf[1024];
cin.getline(inbuf,1024,'\n');
// The parser returns -1 on exit.
if (gParser.process(inbuf,cout,cin)<0) break;
#endif // !HAVE_LIBREADLINE ]
}
#ifdef HAVE_LIBREADLINE // [
if(history_name) {
int e = write_history(history_name);
if(e) {
fprintf(stderr, "error: history: %s\n", strerror(e));
}
free(history_name);
history_name = 0;
}
#endif // HAVE_LIBREADLINE ]
if (gTransceiverPid) kill(gTransceiverPid, SIGKILL);
}
catch (ConfigurationTableKeyNotFound e) {
LOG(ALERT) << "configuration key " << e.key() << " not defined";
exit(2);
}
}
// vim: ts=4 sw=4
<commit_msg>Remedying #538 in the public release<commit_after>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
* Copyright 2011 Range Networks, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <Configuration.h>
// Load configuration from a file.
ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");
#include <TRXManager.h>
#include <GSML1FEC.h>
#include <GSMConfig.h>
#include <GSMSAPMux.h>
#include <GSML3RRMessages.h>
#include <GSMLogicalChannel.h>
#include <ControlCommon.h>
#include <TransactionTable.h>
#include <SIPInterface.h>
#include <Globals.h>
#include <Logger.h>
#include <CLI.h>
#include <PowerManager.h>
#include <Configuration.h>
#include <PhysicalStatus.h>
#include <SubscriberRegistry.h>
#include <sys/wait.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#ifdef HAVE_LIBREADLINE // [
//# include <stdio.h>
# include <readline/readline.h>
# include <readline/history.h>
#endif // HAVE_LIBREADLINE ]
using namespace std;
using namespace GSM;
const char* gDateTime = __DATE__ " " __TIME__;
// All of the other globals that rely on the global configuration file need to
// be declared here.
// The TMSI Table.
Control::TMSITable gTMSITable(gConfig.getStr("Control.Reporting.TMSITable").c_str());
// The transaction table.
Control::TransactionTable gTransactionTable;
// Physical status reporting
GSM::PhysicalStatus gPhysStatus(gConfig.getStr("Control.Reporting.PhysStatusTable").c_str());
// The global SIPInterface object.
SIP::SIPInterface gSIPInterface;
// Configure the BTS object based on the config file.
// So don't create this until AFTER loading the config file.
GSMConfig gBTS;
// Our interface to the software-defined radio.
TransceiverManager gTRX(gConfig.getStr("TRX.IP").c_str(), gConfig.getNum("TRX.Port"));
// Subscriber registry
SubscriberRegistry gSubscriberRegistry;
/** Define a function to call any time the configuration database changes. */
void purgeConfig(void*,int,char const*, char const*, sqlite3_int64)
{
LOG(INFO) << "purging configuration cache";
gConfig.purge();
gBTS.regenerateBeacon();
}
const char* transceiverPath = "./transceiver";
pid_t gTransceiverPid = 0;
void startTransceiver()
{
// Start the transceiver binary, if the path is defined.
// If the path is not defined, the transceiver must be started by some other process.
char TRXnumARFCN[4];
sprintf(TRXnumARFCN,"%1d",1);
LOG(NOTICE) << "starting transceiver " << transceiverPath << " " << TRXnumARFCN;
gTransceiverPid = vfork();
LOG_ASSERT(gTransceiverPid>=0);
if (gTransceiverPid==0) {
// Pid==0 means this is the process that starts the transceiver.
execlp(transceiverPath,transceiverPath,TRXnumARFCN,NULL);
LOG(EMERG) << "cannot find " << transceiverPath;
_exit(1);
} else {
int status;
waitpid(gTransceiverPid, &status,0);
LOG(EMERG) << "Transceiver quit with status " << status << ". Exiting.";
exit(2);
}
}
int main(int argc, char *argv[])
{
try {
srandom(time(NULL));
gConfig.setUpdateHook(purgeConfig);
gLogInit("openbts",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);
LOG(ALERT) << "OpenBTS starting, ver " << VERSION << " build date " << __DATE__;
COUT("\n\n" << gOpenBTSWelcome << "\n");
COUT("\nStarting the system...");
Thread transceiverThread;
transceiverThread.start((void*(*)(void*)) startTransceiver, NULL);
// Start the SIP interface.
gSIPInterface.start();
//
// Configure the radio.
//
// Start the transceiver interface.
// Sleep long enough for the USRP to bootload.
sleep(5);
gTRX.start();
// Set up the interface to the radio.
// Get a handle to the C0 transceiver interface.
ARFCNManager* C0radio = gTRX.ARFCN();
// Tuning.
// Make sure its off for tuning.
C0radio->powerOff();
// Get the ARFCN list.
unsigned C0 = gConfig.getNum("GSM.Radio.C0");
// Tune the radio.
LOG(INFO) << "tuning TRX to ARFCN " << C0;
ARFCNManager* radio = gTRX.ARFCN();
radio->tune(C0);
// Set TSC same as BCC everywhere.
C0radio->setTSC(gBTS.BCC());
// Set maximum expected delay spread.
C0radio->setMaxDelay(gConfig.getNum("GSM.Radio.MaxExpectedDelaySpread"));
// Set Receiver Gain
C0radio->setRxGain(gConfig.getNum("GSM.Radio.RxGain"));
// Turn on and power up.
C0radio->powerOn();
C0radio->setPower(gConfig.getNum("GSM.Radio.PowerManager.MinAttenDB"));
//
// Create a C-V channel set on C0T0.
//
// C-V on C0T0
C0radio->setSlot(0,5);
// SCH
SCHL1FEC SCH;
SCH.downstream(C0radio);
SCH.open();
// FCCH
FCCHL1FEC FCCH;
FCCH.downstream(C0radio);
FCCH.open();
// BCCH
BCCHL1FEC BCCH;
BCCH.downstream(C0radio);
BCCH.open();
// RACH
RACHL1FEC RACH(gRACHC5Mapping);
RACH.downstream(C0radio);
RACH.open();
// CCCHs
CCCHLogicalChannel CCCH0(gCCCH_0Mapping);
CCCH0.downstream(C0radio);
CCCH0.open();
CCCHLogicalChannel CCCH1(gCCCH_1Mapping);
CCCH1.downstream(C0radio);
CCCH1.open();
CCCHLogicalChannel CCCH2(gCCCH_2Mapping);
CCCH2.downstream(C0radio);
CCCH2.open();
// use CCCHs as AGCHs
gBTS.addAGCH(&CCCH0);
gBTS.addAGCH(&CCCH1);
gBTS.addAGCH(&CCCH2);
// C-V C0T0 SDCCHs
SDCCHLogicalChannel C0T0SDCCH[4] = {
SDCCHLogicalChannel(0,gSDCCH_4_0),
SDCCHLogicalChannel(0,gSDCCH_4_1),
SDCCHLogicalChannel(0,gSDCCH_4_2),
SDCCHLogicalChannel(0,gSDCCH_4_3),
};
Thread C0T0SDCCHControlThread[4];
for (int i=0; i<4; i++) {
C0T0SDCCH[i].downstream(C0radio);
C0T0SDCCHControlThread[i].start((void*(*)(void*))Control::DCCHDispatcher,&C0T0SDCCH[i]);
C0T0SDCCH[i].open();
gBTS.addSDCCH(&C0T0SDCCH[i]);
}
//
// Configure the other slots.
//
// Count configured slots.
unsigned sCount = 1;
if (gConfig.defines("GSM.Channels.C1sFirst")) {
// Create C-I slots.
for (int i=0; i<gConfig.getNum("GSM.Channels.NumC1s"); i++) {
gBTS.createCombinationI(gTRX,sCount);
sCount++;
}
}
// Create C-VII slots.
for (int i=0; i<gConfig.getNum("GSM.Channels.NumC7s"); i++) {
gBTS.createCombinationVII(gTRX,sCount);
sCount++;
}
if (!gConfig.defines("GSM.Channels.C1sFirst")) {
// Create C-I slots.
for (int i=0; i<gConfig.getNum("GSM.Channels.NumC1s"); i++) {
gBTS.createCombinationI(gTRX,sCount);
sCount++;
}
}
// Set up idle filling on C0 as needed.
while (sCount<8) {
gBTS.createCombination0(gTRX,sCount);
sCount++;
}
/*
Note: The number of different paging subchannels on
the CCCH is:
MAX(1,(3 - BS-AG-BLKS-RES)) * BS-PA-MFRMS
if CCCH-CONF = "001"
(9 - BS-AG-BLKS-RES) * BS-PA-MFRMS
for other values of CCCH-CONF
*/
// Set up the pager.
// Set up paging channels.
// HACK -- For now, use a single paging channel, since paging groups are broken.
gBTS.addPCH(&CCCH2);
// Be sure we are not over-reserving.
LOG_ASSERT(gConfig.getNum("GSM.CCCH.PCH.Reserve")<(int)gBTS.numAGCHs());
// OK, now it is safe to start the BTS.
gBTS.start();
#ifdef HAVE_LIBREADLINE // [
// start console
using_history();
static const char * const history_file_name = "/.openbts_history";
char *history_name = 0;
char *home_dir = getenv("HOME");
if(home_dir) {
size_t home_dir_len = strlen(home_dir);
size_t history_file_len = strlen(history_file_name);
size_t history_len = home_dir_len + history_file_len + 1;
if(history_len > home_dir_len) {
if(!(history_name = (char *)malloc(history_len))) {
LOG(ERR) << "malloc failed: " << strerror(errno);
exit(2);
}
memcpy(history_name, home_dir, home_dir_len);
memcpy(history_name + home_dir_len, history_file_name,
history_file_len + 1);
read_history(history_name);
}
}
#endif // HAVE_LIBREADLINE ]
LOG(INFO) << "system ready";
COUT("\n\nWelcome to OpenBTS. Type \"help\" to see available commands.");
// FIXME: We want to catch control-d (emacs keybinding for exit())
// The logging parts were removed from this loop.
// If we want them back, they will need to go into their own thread.
while (1) {
#ifdef HAVE_LIBREADLINE // [
char *inbuf = readline(gConfig.getStr("CLI.Prompt").c_str());
if (!inbuf) break;
if (*inbuf) {
add_history(inbuf);
// The parser returns -1 on exit.
if (gParser.process(inbuf, cout, cin)<0) {
free(inbuf);
break;
}
}
free(inbuf);
#else // HAVE_LIBREADLINE ][
cout << endl << gConfig.getStr("CLI.Prompt");
cout.flush();
char inbuf[1024];
cin.getline(inbuf,1024,'\n');
// The parser returns -1 on exit.
if (gParser.process(inbuf,cout,cin)<0) break;
#endif // !HAVE_LIBREADLINE ]
}
#ifdef HAVE_LIBREADLINE // [
if(history_name) {
int e = write_history(history_name);
if(e) {
fprintf(stderr, "error: history: %s\n", strerror(e));
}
free(history_name);
history_name = 0;
}
#endif // HAVE_LIBREADLINE ]
if (gTransceiverPid) kill(gTransceiverPid, SIGKILL);
}
catch (ConfigurationTableKeyNotFound e) {
LOG(ALERT) << "configuration key " << e.key() << " not defined";
exit(2);
}
}
// vim: ts=4 sw=4
<|endoftext|>
|
<commit_before>//
// Created by salmon on 17-4-5.
//
#include "Domain.h"
#include "Attribute.h"
#include "MeshBase.h"
#include "Patch.h"
namespace simpla {
namespace engine {
struct Domain::pimpl_s {
std::shared_ptr<geometry::GeoObject> m_geo_object_;
std::shared_ptr<MeshBase> m_mesh_ = nullptr;
Patch* m_patch_ = nullptr;
};
Domain::Domain(const std::shared_ptr<MeshBase>& m, const std::shared_ptr<geometry::GeoObject>& g)
: SPObject(), m_pimpl_(new pimpl_s) {
m_pimpl_->m_mesh_ = m;
m_pimpl_->m_geo_object_ = g;
Click();
}
Domain::~Domain() {}
std::shared_ptr<data::DataTable> Domain::Serialize() const {
auto p = std::make_shared<data::DataTable>();
p->SetValue("Type", GetRegisterName());
p->SetValue("Name", GetName());
return p;
}
void Domain::Deserialize(const std::shared_ptr<DataTable>& t) { UNIMPLEMENTED; };
void Domain::Update() {}
void Domain::TearDown() {}
void Domain::Initialize() {}
void Domain::Finalize() {}
MeshBase const* Domain::GetMesh() const { return m_pimpl_->m_mesh_.get(); }
MeshBase* Domain::GetMesh() { return m_pimpl_->m_mesh_.get(); }
void Domain::SetGeoObject(std::shared_ptr<geometry::GeoObject> const& g) {
Click();
m_pimpl_->m_geo_object_ = g;
}
std::shared_ptr<geometry::GeoObject> Domain::GetGeoObject() const { return m_pimpl_->m_geo_object_; }
void Domain::Push(Patch* p) {
Click();
m_pimpl_->m_patch_ = p;
AttributeGroup::Push(p);
DoUpdate();
}
void Domain::Pop(Patch* p) {
auto res = m_pimpl_->m_patch_;
m_pimpl_->m_patch_ = nullptr;
AttributeGroup::Pop(p);
Click();
DoTearDown();
}
void Domain::DoInitialCondition(Patch* patch, Real time_now) {
Push(patch);
// if (GetMesh() != nullptr) {
// GetMesh()->InitializeData(time_now);
// GetMesh()->RegisterRanges(m_pimpl_->m_patch_->m_ranges, m_pimpl_->m_geo_object_, GetName());
// }
PreInitialCondition(this, time_now);
InitialCondition(time_now);
PostInitialCondition(this, time_now);
Pop(patch);
}
void Domain::DoBoundaryCondition(Patch* patch, Real time_now, Real dt) {
Push(patch);
GetMesh()->SetBoundaryCondition(time_now, dt);
PreBoundaryCondition(this, time_now, dt);
BoundaryCondition(time_now, dt);
PostBoundaryCondition(this, time_now, dt);
Pop(patch);
}
void Domain::DoAdvance(Patch* patch, Real time_now, Real dt) {
Push(patch);
PreAdvance(this, time_now, dt);
Advance(time_now, dt);
PostAdvance(this, time_now, dt);
Pop(patch);
}
} // namespace engine{
} // namespace simpla{<commit_msg>snapshot<commit_after>//
// Created by salmon on 17-4-5.
//
#include "Domain.h"
#include "Attribute.h"
#include "MeshBase.h"
#include "Patch.h"
namespace simpla {
namespace engine {
struct Domain::pimpl_s {
std::shared_ptr<geometry::GeoObject> m_geo_object_;
std::shared_ptr<MeshBase> m_mesh_ = nullptr;
Patch* m_patch_ = nullptr;
};
Domain::Domain(const std::shared_ptr<MeshBase>& m, const std::shared_ptr<geometry::GeoObject>& g)
: SPObject(), m_pimpl_(new pimpl_s) {
m_pimpl_->m_mesh_ = m;
m_pimpl_->m_geo_object_ = g;
Click();
}
Domain::~Domain() {}
std::shared_ptr<data::DataTable> Domain::Serialize() const {
auto p = std::make_shared<data::DataTable>();
p->SetValue("Type", GetRegisterName());
p->SetValue("Name", GetName());
return p;
}
void Domain::Deserialize(const std::shared_ptr<DataTable>& t) { UNIMPLEMENTED; };
void Domain::Update() {}
void Domain::TearDown() {}
void Domain::Initialize() {}
void Domain::Finalize() {}
MeshBase const* Domain::GetMesh() const { return m_pimpl_->m_mesh_.get(); }
MeshBase* Domain::GetMesh() { return m_pimpl_->m_mesh_.get(); }
void Domain::SetGeoObject(std::shared_ptr<geometry::GeoObject> const& g) {
Click();
m_pimpl_->m_geo_object_ = g;
}
std::shared_ptr<geometry::GeoObject> Domain::GetGeoObject() const { return m_pimpl_->m_geo_object_; }
void Domain::Push(Patch* p) {
Click();
m_pimpl_->m_patch_ = p;
m_pimpl_->m_mesh_->Push(p);
AttributeGroup::Push(p);
DoUpdate();
}
void Domain::Pop(Patch* p) {
AttributeGroup::Pop(p);
m_pimpl_->m_mesh_->Pop(p);
m_pimpl_->m_patch_ = nullptr;
Click();
DoTearDown();
}
void Domain::DoInitialCondition(Patch* patch, Real time_now) {
Push(patch);
PreInitialCondition(this, time_now);
InitialCondition(time_now);
PostInitialCondition(this, time_now);
Pop(patch);
}
void Domain::DoBoundaryCondition(Patch* patch, Real time_now, Real dt) {
Push(patch);
PreBoundaryCondition(this, time_now, dt);
BoundaryCondition(time_now, dt);
PostBoundaryCondition(this, time_now, dt);
Pop(patch);
}
void Domain::DoAdvance(Patch* patch, Real time_now, Real dt) {
Push(patch);
PreAdvance(this, time_now, dt);
Advance(time_now, dt);
PostAdvance(this, time_now, dt);
Pop(patch);
}
} // namespace engine{
} // namespace simpla{<|endoftext|>
|
<commit_before>#include "MeshUtils.hpp"
#include "libslic3r/Tesselate.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/TriangleMeshSlicer.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "slic3r/GUI/Camera.hpp"
#include <GL/glew.h>
#include <igl/unproject.h>
namespace Slic3r {
namespace GUI {
void MeshClipper::set_plane(const ClippingPlane& plane)
{
if (m_plane != plane) {
m_plane = plane;
m_triangles_valid = false;
}
}
void MeshClipper::set_limiting_plane(const ClippingPlane& plane)
{
if (m_limiting_plane != plane) {
m_limiting_plane = plane;
m_triangles_valid = false;
}
}
void MeshClipper::set_mesh(const TriangleMesh& mesh)
{
if (m_mesh != &mesh) {
m_mesh = &mesh;
m_triangles_valid = false;
m_triangles2d.resize(0);
}
}
void MeshClipper::set_negative_mesh(const TriangleMesh& mesh)
{
if (m_negative_mesh != &mesh) {
m_negative_mesh = &mesh;
m_triangles_valid = false;
m_triangles2d.resize(0);
}
}
void MeshClipper::set_transformation(const Geometry::Transformation& trafo)
{
if (! m_trafo.get_matrix().isApprox(trafo.get_matrix())) {
m_trafo = trafo;
m_triangles_valid = false;
m_triangles2d.resize(0);
}
}
void MeshClipper::render_cut()
{
if (! m_triangles_valid)
recalculate_triangles();
if (m_vertex_array.has_VBOs())
m_vertex_array.render();
}
void MeshClipper::recalculate_triangles()
{
const Transform3f& instance_matrix_no_translation_no_scaling = m_trafo.get_matrix(true,false,true).cast<float>();
const Vec3f& scaling = m_trafo.get_scaling_factor().cast<float>();
// Calculate clipping plane normal in mesh coordinates.
Vec3f up_noscale = instance_matrix_no_translation_no_scaling.inverse() * m_plane.get_normal().cast<float>();
Vec3d up (up_noscale(0)*scaling(0), up_noscale(1)*scaling(1), up_noscale(2)*scaling(2));
// Calculate distance from mesh origin to the clipping plane (in mesh coordinates).
float height_mesh = m_plane.distance(m_trafo.get_offset()) * (up_noscale.norm()/up.norm());
// Now do the cutting
MeshSlicingParams slicing_params;
slicing_params.trafo.rotate(Eigen::Quaternion<double, Eigen::DontAlign>::FromTwoVectors(up, Vec3d::UnitZ()));
assert(m_mesh->has_shared_vertices());
ExPolygons expolys = union_ex(slice_mesh(m_mesh->its, height_mesh, slicing_params));
if (m_negative_mesh && !m_negative_mesh->empty()) {
assert(m_negative_mesh->has_shared_vertices());
ExPolygons neg_expolys = union_ex(slice_mesh(m_negative_mesh->its, height_mesh, slicing_params));
expolys = diff_ex(expolys, neg_expolys);
}
// Triangulate and rotate the cut into world coords:
Eigen::Quaterniond q;
q.setFromTwoVectors(Vec3d::UnitZ(), up);
Transform3d tr = Transform3d::Identity();
tr.rotate(q);
tr = m_trafo.get_matrix() * tr;
height_mesh += 0.001f; // to avoid z-fighting
if (m_limiting_plane != ClippingPlane::ClipsNothing())
{
// Now remove whatever ended up below the limiting plane (e.g. sinking objects).
// First transform the limiting plane from world to mesh coords.
// Note that inverse of tr transforms the plane from world to horizontal.
Vec3d normal_old = m_limiting_plane.get_normal().normalized();
Vec3d normal_new = (tr.matrix().block<3,3>(0,0).transpose() * normal_old).normalized();
// normal_new should now be the plane normal in mesh coords. To find the offset,
// transform a point and set offset so it belongs to the transformed plane.
Vec3d pt = Vec3d::Zero();
double plane_offset = m_limiting_plane.get_data()[3];
if (std::abs(normal_old.z()) > 0.5) // normal is normalized, at least one of the coords if larger than sqrt(3)/3 = 0.57
pt.z() = - plane_offset / normal_old.z();
else if (std::abs(normal_old.y()) > 0.5)
pt.y() = - plane_offset / normal_old.y();
else
pt.x() = - plane_offset / normal_old.x();
pt = tr.inverse() * pt;
double offset = -(normal_new.dot(pt));
if (std::abs(normal_old.dot(m_plane.get_normal().normalized())) > 0.99) {
// The cuts are parallel, show all or nothing.
if (offset < height_mesh)
expolys.clear();
} else {
// The cut is a horizontal plane defined by z=height_mesh.
// ax+by+e=0 is the line of intersection with the limiting plane.
// Normalized so a^2 + b^2 = 1.
double len = std::hypot(normal_new.x(), normal_new.y());
if (len == 0.)
return;
double a = normal_new.x() / len;
double b = normal_new.y() / len;
double e = (normal_new.z() * height_mesh + offset) / len;
if (b == 0.)
return;
// We need a half-plane to limit the cut. Get angle of the intersecting line.
double angle = std::atan(-a/b);
if (b > 0) // select correct half-plane
angle += M_PI;
// We'll take a big rectangle above x-axis and rotate and translate
// it so it lies on our line. This will be the figure to subtract
// from the cut. The coordinates must not overflow after the transform,
// make the rectangle a bit smaller.
coord_t size = (std::numeric_limits<coord_t>::max() - scale_(std::max(std::abs(e*a), std::abs(e*b)))) / 4;
Polygons ep {Polygon({Point(-size, 0), Point(size, 0), Point(size, 2*size), Point(-size, 2*size)})};
ep.front().rotate(angle);
ep.front().translate(scale_(-e * a), scale_(-e * b));
expolys = diff_ex(expolys, ep);
}
}
m_triangles2d = triangulate_expolygons_2f(expolys, m_trafo.get_matrix().matrix().determinant() < 0.);
m_vertex_array.release_geometry();
for (auto it=m_triangles2d.cbegin(); it != m_triangles2d.cend(); it=it+3) {
m_vertex_array.push_geometry(tr * Vec3d((*(it+0))(0), (*(it+0))(1), height_mesh), up);
m_vertex_array.push_geometry(tr * Vec3d((*(it+1))(0), (*(it+1))(1), height_mesh), up);
m_vertex_array.push_geometry(tr * Vec3d((*(it+2))(0), (*(it+2))(1), height_mesh), up);
size_t idx = it - m_triangles2d.cbegin();
m_vertex_array.push_triangle(idx, idx+1, idx+2);
}
m_vertex_array.finalize_geometry(true);
m_triangles_valid = true;
}
Vec3f MeshRaycaster::get_triangle_normal(size_t facet_idx) const
{
return m_normals[facet_idx];
}
void MeshRaycaster::line_from_mouse_pos(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera,
Vec3d& point, Vec3d& direction) const
{
Matrix4d modelview = camera.get_view_matrix().matrix();
Matrix4d projection= camera.get_projection_matrix().matrix();
Vec4i viewport(camera.get_viewport().data());
Vec3d pt1;
Vec3d pt2;
igl::unproject(Vec3d(mouse_pos(0), viewport[3] - mouse_pos(1), 0.),
modelview, projection, viewport, pt1);
igl::unproject(Vec3d(mouse_pos(0), viewport[3] - mouse_pos(1), 1.),
modelview, projection, viewport, pt2);
Transform3d inv = trafo.inverse();
pt1 = inv * pt1;
pt2 = inv * pt2;
point = pt1;
direction = pt2-pt1;
}
bool MeshRaycaster::unproject_on_mesh(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera,
Vec3f& position, Vec3f& normal, const ClippingPlane* clipping_plane,
size_t* facet_idx) const
{
Vec3d point;
Vec3d direction;
line_from_mouse_pos(mouse_pos, trafo, camera, point, direction);
std::vector<sla::IndexedMesh::hit_result> hits = m_emesh.query_ray_hits(point, direction);
if (hits.empty())
return false; // no intersection found
unsigned i = 0;
// Remove points that are obscured or cut by the clipping plane.
// Also, remove anything below the bed (sinking objects).
for (i=0; i<hits.size(); ++i) {
Vec3d transformed_hit = trafo * hits[i].position();
if (transformed_hit.z() >= 0. &&
(! clipping_plane || ! clipping_plane->is_point_clipped(transformed_hit)))
break;
}
if (i==hits.size() || (hits.size()-i) % 2 != 0) {
// All hits are either clipped, or there is an odd number of unclipped
// hits - meaning the nearest must be from inside the mesh.
return false;
}
// Now stuff the points in the provided vector and calculate normals if asked about them:
position = hits[i].position().cast<float>();
normal = hits[i].normal().cast<float>();
if (facet_idx)
*facet_idx = hits[i].face();
return true;
}
std::vector<unsigned> MeshRaycaster::get_unobscured_idxs(const Geometry::Transformation& trafo, const Camera& camera, const std::vector<Vec3f>& points,
const ClippingPlane* clipping_plane) const
{
std::vector<unsigned> out;
const Transform3d& instance_matrix_no_translation_no_scaling = trafo.get_matrix(true,false,true);
Vec3f direction_to_camera = -camera.get_dir_forward().cast<float>();
Vec3f direction_to_camera_mesh = (instance_matrix_no_translation_no_scaling.inverse().cast<float>() * direction_to_camera).normalized().eval();
Vec3f scaling = trafo.get_scaling_factor().cast<float>();
direction_to_camera_mesh = Vec3f(direction_to_camera_mesh(0)*scaling(0), direction_to_camera_mesh(1)*scaling(1), direction_to_camera_mesh(2)*scaling(2));
const Transform3f inverse_trafo = trafo.get_matrix().inverse().cast<float>();
for (size_t i=0; i<points.size(); ++i) {
const Vec3f& pt = points[i];
if (clipping_plane && clipping_plane->is_point_clipped(pt.cast<double>()))
continue;
bool is_obscured = false;
// Cast a ray in the direction of the camera and look for intersection with the mesh:
std::vector<sla::IndexedMesh::hit_result> hits;
// Offset the start of the ray by EPSILON to account for numerical inaccuracies.
hits = m_emesh.query_ray_hits((inverse_trafo * pt + direction_to_camera_mesh * EPSILON).cast<double>(),
direction_to_camera.cast<double>());
if (! hits.empty()) {
// If the closest hit facet normal points in the same direction as the ray,
// we are looking through the mesh and should therefore discard the point:
if (hits.front().normal().dot(direction_to_camera_mesh.cast<double>()) > 0)
is_obscured = true;
// Eradicate all hits that the caller wants to ignore
for (unsigned j=0; j<hits.size(); ++j) {
if (clipping_plane && clipping_plane->is_point_clipped(trafo.get_matrix() * hits[j].position())) {
hits.erase(hits.begin()+j);
--j;
}
}
// FIXME: the intersection could in theory be behind the camera, but as of now we only have camera direction.
// Also, the threshold is in mesh coordinates, not in actual dimensions.
if (! hits.empty())
is_obscured = true;
}
if (! is_obscured)
out.push_back(i);
}
return out;
}
Vec3f MeshRaycaster::get_closest_point(const Vec3f& point, Vec3f* normal) const
{
int idx = 0;
Vec3d closest_point;
m_emesh.squared_distance(point.cast<double>(), idx, closest_point);
if (normal)
*normal = m_normals[idx];
return closest_point.cast<float>();
}
} // namespace GUI
} // namespace Slic3r
<commit_msg>Fixed painting on surfaces close to the bed (broken since 1360446)<commit_after>#include "MeshUtils.hpp"
#include "libslic3r/Tesselate.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/TriangleMeshSlicer.hpp"
#include "libslic3r/ClipperUtils.hpp"
#include "libslic3r/Model.hpp"
#include "slic3r/GUI/Camera.hpp"
#include <GL/glew.h>
#include <igl/unproject.h>
namespace Slic3r {
namespace GUI {
void MeshClipper::set_plane(const ClippingPlane& plane)
{
if (m_plane != plane) {
m_plane = plane;
m_triangles_valid = false;
}
}
void MeshClipper::set_limiting_plane(const ClippingPlane& plane)
{
if (m_limiting_plane != plane) {
m_limiting_plane = plane;
m_triangles_valid = false;
}
}
void MeshClipper::set_mesh(const TriangleMesh& mesh)
{
if (m_mesh != &mesh) {
m_mesh = &mesh;
m_triangles_valid = false;
m_triangles2d.resize(0);
}
}
void MeshClipper::set_negative_mesh(const TriangleMesh& mesh)
{
if (m_negative_mesh != &mesh) {
m_negative_mesh = &mesh;
m_triangles_valid = false;
m_triangles2d.resize(0);
}
}
void MeshClipper::set_transformation(const Geometry::Transformation& trafo)
{
if (! m_trafo.get_matrix().isApprox(trafo.get_matrix())) {
m_trafo = trafo;
m_triangles_valid = false;
m_triangles2d.resize(0);
}
}
void MeshClipper::render_cut()
{
if (! m_triangles_valid)
recalculate_triangles();
if (m_vertex_array.has_VBOs())
m_vertex_array.render();
}
void MeshClipper::recalculate_triangles()
{
const Transform3f& instance_matrix_no_translation_no_scaling = m_trafo.get_matrix(true,false,true).cast<float>();
const Vec3f& scaling = m_trafo.get_scaling_factor().cast<float>();
// Calculate clipping plane normal in mesh coordinates.
Vec3f up_noscale = instance_matrix_no_translation_no_scaling.inverse() * m_plane.get_normal().cast<float>();
Vec3d up (up_noscale(0)*scaling(0), up_noscale(1)*scaling(1), up_noscale(2)*scaling(2));
// Calculate distance from mesh origin to the clipping plane (in mesh coordinates).
float height_mesh = m_plane.distance(m_trafo.get_offset()) * (up_noscale.norm()/up.norm());
// Now do the cutting
MeshSlicingParams slicing_params;
slicing_params.trafo.rotate(Eigen::Quaternion<double, Eigen::DontAlign>::FromTwoVectors(up, Vec3d::UnitZ()));
assert(m_mesh->has_shared_vertices());
ExPolygons expolys = union_ex(slice_mesh(m_mesh->its, height_mesh, slicing_params));
if (m_negative_mesh && !m_negative_mesh->empty()) {
assert(m_negative_mesh->has_shared_vertices());
ExPolygons neg_expolys = union_ex(slice_mesh(m_negative_mesh->its, height_mesh, slicing_params));
expolys = diff_ex(expolys, neg_expolys);
}
// Triangulate and rotate the cut into world coords:
Eigen::Quaterniond q;
q.setFromTwoVectors(Vec3d::UnitZ(), up);
Transform3d tr = Transform3d::Identity();
tr.rotate(q);
tr = m_trafo.get_matrix() * tr;
height_mesh += 0.001f; // to avoid z-fighting
if (m_limiting_plane != ClippingPlane::ClipsNothing())
{
// Now remove whatever ended up below the limiting plane (e.g. sinking objects).
// First transform the limiting plane from world to mesh coords.
// Note that inverse of tr transforms the plane from world to horizontal.
Vec3d normal_old = m_limiting_plane.get_normal().normalized();
Vec3d normal_new = (tr.matrix().block<3,3>(0,0).transpose() * normal_old).normalized();
// normal_new should now be the plane normal in mesh coords. To find the offset,
// transform a point and set offset so it belongs to the transformed plane.
Vec3d pt = Vec3d::Zero();
double plane_offset = m_limiting_plane.get_data()[3];
if (std::abs(normal_old.z()) > 0.5) // normal is normalized, at least one of the coords if larger than sqrt(3)/3 = 0.57
pt.z() = - plane_offset / normal_old.z();
else if (std::abs(normal_old.y()) > 0.5)
pt.y() = - plane_offset / normal_old.y();
else
pt.x() = - plane_offset / normal_old.x();
pt = tr.inverse() * pt;
double offset = -(normal_new.dot(pt));
if (std::abs(normal_old.dot(m_plane.get_normal().normalized())) > 0.99) {
// The cuts are parallel, show all or nothing.
if (offset < height_mesh)
expolys.clear();
} else {
// The cut is a horizontal plane defined by z=height_mesh.
// ax+by+e=0 is the line of intersection with the limiting plane.
// Normalized so a^2 + b^2 = 1.
double len = std::hypot(normal_new.x(), normal_new.y());
if (len == 0.)
return;
double a = normal_new.x() / len;
double b = normal_new.y() / len;
double e = (normal_new.z() * height_mesh + offset) / len;
if (b == 0.)
return;
// We need a half-plane to limit the cut. Get angle of the intersecting line.
double angle = std::atan(-a/b);
if (b > 0) // select correct half-plane
angle += M_PI;
// We'll take a big rectangle above x-axis and rotate and translate
// it so it lies on our line. This will be the figure to subtract
// from the cut. The coordinates must not overflow after the transform,
// make the rectangle a bit smaller.
coord_t size = (std::numeric_limits<coord_t>::max() - scale_(std::max(std::abs(e*a), std::abs(e*b)))) / 4;
Polygons ep {Polygon({Point(-size, 0), Point(size, 0), Point(size, 2*size), Point(-size, 2*size)})};
ep.front().rotate(angle);
ep.front().translate(scale_(-e * a), scale_(-e * b));
expolys = diff_ex(expolys, ep);
}
}
m_triangles2d = triangulate_expolygons_2f(expolys, m_trafo.get_matrix().matrix().determinant() < 0.);
m_vertex_array.release_geometry();
for (auto it=m_triangles2d.cbegin(); it != m_triangles2d.cend(); it=it+3) {
m_vertex_array.push_geometry(tr * Vec3d((*(it+0))(0), (*(it+0))(1), height_mesh), up);
m_vertex_array.push_geometry(tr * Vec3d((*(it+1))(0), (*(it+1))(1), height_mesh), up);
m_vertex_array.push_geometry(tr * Vec3d((*(it+2))(0), (*(it+2))(1), height_mesh), up);
size_t idx = it - m_triangles2d.cbegin();
m_vertex_array.push_triangle(idx, idx+1, idx+2);
}
m_vertex_array.finalize_geometry(true);
m_triangles_valid = true;
}
Vec3f MeshRaycaster::get_triangle_normal(size_t facet_idx) const
{
return m_normals[facet_idx];
}
void MeshRaycaster::line_from_mouse_pos(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera,
Vec3d& point, Vec3d& direction) const
{
Matrix4d modelview = camera.get_view_matrix().matrix();
Matrix4d projection= camera.get_projection_matrix().matrix();
Vec4i viewport(camera.get_viewport().data());
Vec3d pt1;
Vec3d pt2;
igl::unproject(Vec3d(mouse_pos(0), viewport[3] - mouse_pos(1), 0.),
modelview, projection, viewport, pt1);
igl::unproject(Vec3d(mouse_pos(0), viewport[3] - mouse_pos(1), 1.),
modelview, projection, viewport, pt2);
Transform3d inv = trafo.inverse();
pt1 = inv * pt1;
pt2 = inv * pt2;
point = pt1;
direction = pt2-pt1;
}
bool MeshRaycaster::unproject_on_mesh(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera,
Vec3f& position, Vec3f& normal, const ClippingPlane* clipping_plane,
size_t* facet_idx) const
{
Vec3d point;
Vec3d direction;
line_from_mouse_pos(mouse_pos, trafo, camera, point, direction);
std::vector<sla::IndexedMesh::hit_result> hits = m_emesh.query_ray_hits(point, direction);
if (hits.empty())
return false; // no intersection found
unsigned i = 0;
// Remove points that are obscured or cut by the clipping plane.
// Also, remove anything below the bed (sinking objects).
for (i=0; i<hits.size(); ++i) {
Vec3d transformed_hit = trafo * hits[i].position();
if (transformed_hit.z() >= SINKING_Z_THRESHOLD &&
(! clipping_plane || ! clipping_plane->is_point_clipped(transformed_hit)))
break;
}
if (i==hits.size() || (hits.size()-i) % 2 != 0) {
// All hits are either clipped, or there is an odd number of unclipped
// hits - meaning the nearest must be from inside the mesh.
return false;
}
// Now stuff the points in the provided vector and calculate normals if asked about them:
position = hits[i].position().cast<float>();
normal = hits[i].normal().cast<float>();
if (facet_idx)
*facet_idx = hits[i].face();
return true;
}
std::vector<unsigned> MeshRaycaster::get_unobscured_idxs(const Geometry::Transformation& trafo, const Camera& camera, const std::vector<Vec3f>& points,
const ClippingPlane* clipping_plane) const
{
std::vector<unsigned> out;
const Transform3d& instance_matrix_no_translation_no_scaling = trafo.get_matrix(true,false,true);
Vec3f direction_to_camera = -camera.get_dir_forward().cast<float>();
Vec3f direction_to_camera_mesh = (instance_matrix_no_translation_no_scaling.inverse().cast<float>() * direction_to_camera).normalized().eval();
Vec3f scaling = trafo.get_scaling_factor().cast<float>();
direction_to_camera_mesh = Vec3f(direction_to_camera_mesh(0)*scaling(0), direction_to_camera_mesh(1)*scaling(1), direction_to_camera_mesh(2)*scaling(2));
const Transform3f inverse_trafo = trafo.get_matrix().inverse().cast<float>();
for (size_t i=0; i<points.size(); ++i) {
const Vec3f& pt = points[i];
if (clipping_plane && clipping_plane->is_point_clipped(pt.cast<double>()))
continue;
bool is_obscured = false;
// Cast a ray in the direction of the camera and look for intersection with the mesh:
std::vector<sla::IndexedMesh::hit_result> hits;
// Offset the start of the ray by EPSILON to account for numerical inaccuracies.
hits = m_emesh.query_ray_hits((inverse_trafo * pt + direction_to_camera_mesh * EPSILON).cast<double>(),
direction_to_camera.cast<double>());
if (! hits.empty()) {
// If the closest hit facet normal points in the same direction as the ray,
// we are looking through the mesh and should therefore discard the point:
if (hits.front().normal().dot(direction_to_camera_mesh.cast<double>()) > 0)
is_obscured = true;
// Eradicate all hits that the caller wants to ignore
for (unsigned j=0; j<hits.size(); ++j) {
if (clipping_plane && clipping_plane->is_point_clipped(trafo.get_matrix() * hits[j].position())) {
hits.erase(hits.begin()+j);
--j;
}
}
// FIXME: the intersection could in theory be behind the camera, but as of now we only have camera direction.
// Also, the threshold is in mesh coordinates, not in actual dimensions.
if (! hits.empty())
is_obscured = true;
}
if (! is_obscured)
out.push_back(i);
}
return out;
}
Vec3f MeshRaycaster::get_closest_point(const Vec3f& point, Vec3f* normal) const
{
int idx = 0;
Vec3d closest_point;
m_emesh.squared_distance(point.cast<double>(), idx, closest_point);
if (normal)
*normal = m_normals[idx];
return closest_point.cast<float>();
}
} // namespace GUI
} // namespace Slic3r
<|endoftext|>
|
<commit_before>/*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *
* *
* 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 *
*************************************************************************************/
#include "daemon.h"
#include "serializer.h"
#include "generator.h"
#include <QtCore/QDebug>
#include <kdemacros.h>
#include <KPluginFactory>
#include <kscreen/config.h>
#include <kscreen/configmonitor.h>
#include <kaction.h>
K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();)
K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen"))
KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& )
: KDEDModule(parent)
, m_iteration(0)
, m_pendingSave(false)
{
setenv("KSCREEN_BACKEND", "XRandR", 1);
KAction* action = new KAction(this);
action->setGlobalShortcut(KShortcut(Qt::Key_Display));
connect(action, SIGNAL(triggered(bool)), SLOT(displayButton()));
connect(Generator::self(), SIGNAL(ready()), SLOT(init()));
}
KScreenDaemon::~KScreenDaemon()
{
Generator::destroy();
}
void KScreenDaemon::init()
{
applyConfig();
monitorForChanges();
}
void KScreenDaemon::applyConfig()
{
qDebug() << "Applying config";
KScreen::Config* config = 0;
if (Serializer::configExists()) {
config = Serializer::config(Serializer::currentId());
} else {
config = Generator::self()->idealConfig();
}
KScreen::Config::setConfig(config);
}
void KScreenDaemon::configChanged()
{
qDebug() << "Change detected";
if (m_pendingSave) {
return;
}
qDebug() << "Scheduling screen save";
m_pendingSave = true;
QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection);
}
void KScreenDaemon::saveCurrentConfig()
{
qDebug() << "Saving current config";
m_pendingSave = false;
Serializer::saveConfig(KScreen::Config::current());
}
void KScreenDaemon::displayButton()
{
if (m_iteration > 5) {
m_iteration = 1;
}
Generator::displaySwitch(m_iteration);
}
void KScreenDaemon::monitorForChanges()
{
KScreen::Config* config = KScreen::Config::current();
KScreen::ConfigMonitor::instance()->addConfig(config);
KScreen::OutputList outputs = config->outputs();
Q_FOREACH(KScreen::Output* output, outputs) {
connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig()));
connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged()));
connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged()));
connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged()));
connect(output, SIGNAL(outputChanged()), SLOT(configChanged()));
connect(output, SIGNAL(clonesChanged()), SLOT(configChanged()));
connect(output, SIGNAL(posChanged()), SLOT(configChanged()));
connect(output, SIGNAL(rotationChanged()), SLOT(configChanged()));
}
}<commit_msg>Ups, displaySwitch is not static :p<commit_after>/*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *
* *
* 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 *
*************************************************************************************/
#include "daemon.h"
#include "serializer.h"
#include "generator.h"
#include <QtCore/QDebug>
#include <kdemacros.h>
#include <KPluginFactory>
#include <kscreen/config.h>
#include <kscreen/configmonitor.h>
#include <kaction.h>
K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();)
K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen"))
KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& )
: KDEDModule(parent)
, m_iteration(0)
, m_pendingSave(false)
{
setenv("KSCREEN_BACKEND", "XRandR", 1);
KAction* action = new KAction(this);
action->setGlobalShortcut(KShortcut(Qt::Key_Display));
connect(action, SIGNAL(triggered(bool)), SLOT(displayButton()));
connect(Generator::self(), SIGNAL(ready()), SLOT(init()));
}
KScreenDaemon::~KScreenDaemon()
{
Generator::destroy();
}
void KScreenDaemon::init()
{
applyConfig();
monitorForChanges();
}
void KScreenDaemon::applyConfig()
{
qDebug() << "Applying config";
KScreen::Config* config = 0;
if (Serializer::configExists()) {
config = Serializer::config(Serializer::currentId());
} else {
config = Generator::self()->idealConfig();
}
KScreen::Config::setConfig(config);
}
void KScreenDaemon::configChanged()
{
qDebug() << "Change detected";
if (m_pendingSave) {
return;
}
qDebug() << "Scheduling screen save";
m_pendingSave = true;
QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection);
}
void KScreenDaemon::saveCurrentConfig()
{
qDebug() << "Saving current config";
m_pendingSave = false;
Serializer::saveConfig(KScreen::Config::current());
}
void KScreenDaemon::displayButton()
{
if (m_iteration > 5) {
m_iteration = 1;
}
Generator::self()->displaySwitch(m_iteration);
}
void KScreenDaemon::monitorForChanges()
{
KScreen::Config* config = KScreen::Config::current();
KScreen::ConfigMonitor::instance()->addConfig(config);
KScreen::OutputList outputs = config->outputs();
Q_FOREACH(KScreen::Output* output, outputs) {
connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig()));
connect(output, SIGNAL(currentModeChanged()), SLOT(configChanged()));
connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged()));
connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged()));
connect(output, SIGNAL(outputChanged()), SLOT(configChanged()));
connect(output, SIGNAL(clonesChanged()), SLOT(configChanged()));
connect(output, SIGNAL(posChanged()), SLOT(configChanged()));
connect(output, SIGNAL(rotationChanged()), SLOT(configChanged()));
}
}<|endoftext|>
|
<commit_before>#include "ros/ros.h"
#include <gtest/gtest.h>
#include <Eigen/Dense>
#include <eigen_conversions/eigen_msg.h>
#include "geometry_msgs/Wrench.h"
#include "geometry_msgs/Pose.h"
#include "uranus_dp/State.h"
#include "uranus_dp/ToggleControlMode.h"
class OpenLoopControllerTest : public ::testing::Test {
public:
OpenLoopControllerTest()
{
pub = nh.advertise<geometry_msgs::Wrench>("open_loop_setpoint", 1);
sub = nh.subscribe("control_input", 5, &OpenLoopControllerTest::Callback, this);
// modeClient = nh.serviceClient<uranus_dp::ToggleControlMode>("toggle_control_mode");
message_received = false;
}
void SetUp()
{
while (!IsNodeReady())
{
ros::spinOnce();
}
}
void PublishSetpoint(double X, double Y, double Z, double K, double M, double N)
{
geometry_msgs::Wrench msg;
msg.force.x = X;
msg.force.y = Y;
msg.force.z = Z;
msg.torque.x = K;
msg.torque.y = M;
msg.torque.z = N;
pub.publish(msg);
}
void WaitForMessage()
{
while (!message_received)
{
ros::spinOnce();
}
}
// ros::ServiceClient modeClient;
Eigen::Matrix<double,6,1> tau;
static const double EPSILON = 1e-6; // Max absolute error
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
bool message_received;
void Callback(const geometry_msgs::Wrench& msg)
{
tf::wrenchMsgToEigen(msg, tau);
message_received = true;
}
bool IsNodeReady()
{
return (pub.getNumSubscribers() > 0) && (sub.getNumPublishers() > 0);
}
};
/*
* Make sure we receive any messages at all.
*/
TEST_F(OpenLoopControllerTest, CheckResponsiveness)
{
PublishSetpoint(1,2,3,4,5,6);
WaitForMessage();
EXPECT_TRUE(true);
}
/*
* Make sure open loop outputs the same as the input.
*/
TEST_F(OpenLoopControllerTest, DirectFeedthrough)
{
PublishSetpoint(-9.966, -7.907, 7.626, -6.023, 1.506, 2.805);
WaitForMessage();
EXPECT_NEAR(tau(0), -9.966, EPSILON);
EXPECT_NEAR(tau(1), -7.907, EPSILON);
EXPECT_NEAR(tau(2), 7.626, EPSILON);
EXPECT_NEAR(tau(3), -6.023, EPSILON);
EXPECT_NEAR(tau(4), 1.506, EPSILON);
EXPECT_NEAR(tau(5), 2.805, EPSILON);
}
/*
* Input zero speed and nonzero pose. Input same pose state and pose setpoint. Expect zero output.
*/
// TEST_F(OpenLoopControllerTest, ZeroErrorZeroOutput)
// {
// uranus_dp::ToggleControlMode srv;
// if (!modeClient.call(srv))
// {
// ROS_ERROR_STREAM("Failed to call service toggle_control_mode. New mode not activated.");
// }
// Eigen::Vector3d p(1,2,3);
// Eigen::Quaterniond q(4,5,6,7);
// q.normalize();
// Eigen::Vector3d v(0,0,0);
// Eigen::Vector3d omega(0,0,0);
// PublishState(p, q, v, omega);
// PublishStationkeeperSetpoint(p, q);
// WaitForMessage();
// EXPECT_NEAR(tau(0), 0, EPSILON);
// EXPECT_NEAR(tau(1), 0, EPSILON);
// EXPECT_NEAR(tau(2), 0, EPSILON);
// EXPECT_NEAR(tau(3), 0, EPSILON);
// EXPECT_NEAR(tau(4), 0, EPSILON);
// EXPECT_NEAR(tau(5), 0, EPSILON);
// }
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "controller_test");
ROS_INFO("Launching node controller_test.");
int ret = RUN_ALL_TESTS();
ros::shutdown();
return ret;
}
<commit_msg>Update with new SetControlMode<commit_after>#include "ros/ros.h"
#include <gtest/gtest.h>
#include <Eigen/Dense>
#include <eigen_conversions/eigen_msg.h>
#include "geometry_msgs/Wrench.h"
#include "geometry_msgs/Pose.h"
#include "uranus_dp/State.h"
#include "uranus_dp/SetControlMode.h"
#include "../control_mode_enum.h"
class OpenLoopControllerTest : public ::testing::Test {
public:
OpenLoopControllerTest()
{
pub = nh.advertise<geometry_msgs::Wrench>("open_loop_setpoint", 1);
sub = nh.subscribe("control_input", 5, &OpenLoopControllerTest::Callback, this);
client = nh.serviceClient<uranus_dp::SetControlMode>("set_control_mode");
message_received = false;
}
void SetUp()
{
while (!IsNodeReady())
{
ros::spinOnce();
}
}
void PublishSetpoint(double X, double Y, double Z, double K, double M, double N)
{
geometry_msgs::Wrench msg;
msg.force.x = X;
msg.force.y = Y;
msg.force.z = Z;
msg.torque.x = K;
msg.torque.y = M;
msg.torque.z = N;
pub.publish(msg);
}
void WaitForMessage()
{
while (!message_received)
{
ros::spinOnce();
}
}
ros::ServiceClient client; // Should be private?
Eigen::Matrix<double,6,1> tau;
static const double EPSILON = 1e-6; // Max absolute error
private:
ros::NodeHandle nh;
ros::Publisher pub;
ros::Subscriber sub;
bool message_received;
void Callback(const geometry_msgs::Wrench& msg)
{
tf::wrenchMsgToEigen(msg, tau);
message_received = true;
}
bool IsNodeReady()
{
return (pub.getNumSubscribers() > 0) && (sub.getNumPublishers() > 0);
}
};
/*
* Make sure we receive any messages at all.
*/
TEST_F(OpenLoopControllerTest, CheckResponsiveness)
{
uranus_dp::SetControlMode srv;
srv.request.mode = ControlModes::OPEN_LOOP;
if (!client.call(srv))
{
ROS_ERROR("Failed to call service toggle_control_mode. New mode open loop not activated.");
}
PublishSetpoint(1,2,3,4,5,6);
WaitForMessage();
EXPECT_TRUE(true);
}
/*
* Make sure open loop outputs the same as the input.
*/
TEST_F(OpenLoopControllerTest, DirectFeedthrough)
{
PublishSetpoint(-9.966, -7.907, 7.626, -6.023, 1.506, 2.805);
WaitForMessage();
EXPECT_NEAR(tau(0), -9.966, EPSILON);
EXPECT_NEAR(tau(1), -7.907, EPSILON);
EXPECT_NEAR(tau(2), 7.626, EPSILON);
EXPECT_NEAR(tau(3), -6.023, EPSILON);
EXPECT_NEAR(tau(4), 1.506, EPSILON);
EXPECT_NEAR(tau(5), 2.805, EPSILON);
}
/*
* Input zero speed and nonzero pose. Input same pose state and pose setpoint. Expect zero output.
*/
// TEST_F(OpenLoopControllerTest, ZeroErrorZeroOutput)
// {
// uranus_dp::ToggleControlMode srv;
// if (!modeClient.call(srv))
// {
// ROS_ERROR_STREAM("Failed to call service toggle_control_mode. New mode not activated.");
// }
// Eigen::Vector3d p(1,2,3);
// Eigen::Quaterniond q(4,5,6,7);
// q.normalize();
// Eigen::Vector3d v(0,0,0);
// Eigen::Vector3d omega(0,0,0);
// PublishState(p, q, v, omega);
// PublishStationkeeperSetpoint(p, q);
// WaitForMessage();
// EXPECT_NEAR(tau(0), 0, EPSILON);
// EXPECT_NEAR(tau(1), 0, EPSILON);
// EXPECT_NEAR(tau(2), 0, EPSILON);
// EXPECT_NEAR(tau(3), 0, EPSILON);
// EXPECT_NEAR(tau(4), 0, EPSILON);
// EXPECT_NEAR(tau(5), 0, EPSILON);
// }
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "controller_test");
ROS_INFO("Launching node controller_test.");
int ret = RUN_ALL_TESTS();
ros::shutdown();
return ret;
}
<|endoftext|>
|
<commit_before>#include "../common/init.h"
#include "../common/timer.h"
#include <iostream>
#include <vector>
#include "character-select.h"
#include "util/debug.h"
#include "util/load_exception.h"
#include "util/token_exception.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
enum Keys{
Up=0,
Down,
Left,
Right,
Esc,
Enter,
};
class Logic: public Util::Logic {
public:
Logic(InputMap<Keys> & input, CharacterSelect & select):
is_done(false),
input(input),
select(select){
}
bool is_done;
InputMap<Keys> & input;
CharacterSelect & select;
bool done(){
return is_done;
}
void run(){
std::vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
for (std::vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
const InputMap<Keys>::InputEvent & event = *it;
if (event.enabled){
if (event.out == Esc){
is_done = true;
}
/* NOTE Assumes only one cursor */
if (event.out == Up){
select.getList()->up(0);
}
if (event.out == Down){
select.getList()->down(0);
}
if (event.out == Left){
select.getList()->left(0);
}
if (event.out == Right){
select.getList()->right(0);
}
if (event.out == Enter){
}
}
}
select.act();
}
double ticks(double system){
return system;
}
};
class Draw: public Util::Draw {
public:
Draw(CharacterSelect & select):
select(select){
}
CharacterSelect & select;
void draw(const Graphics::Bitmap & buffer){
buffer.clear();
select.draw(buffer);
buffer.BlitToScreen();
}
};
int main(int argc, char ** argv){
if (argc > 1){
Screen::realInit();
Common::startTimers();
Global::setDebug(0);
std::string file = argv[1];
InputManager manager;
Graphics::Bitmap screen(Graphics::getScreenBuffer());
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);
Keyboard::pushRepeatState(true);
InputMap<Keys> input;
input.set(Keyboard::Key_ESC, 0, true, Esc);
input.set(Keyboard::Key_ENTER, 0, true, Enter);
input.set(Keyboard::Key_UP, 0, true, Up);
input.set(Keyboard::Key_DOWN, 0, true, Down);
input.set(Keyboard::Key_LEFT, 0, true, Left);
input.set(Keyboard::Key_RIGHT, 0, true, Right);
try {
CharacterSelect select(file);
Logic logic(input, select);
Draw draw(select);
Util::standardLoop(logic, draw);
} catch (const LoadException & ex){
Global::debug(0) << "Problem loading file [" << file << "]. Reason: " << ex.getTrace() << std::endl;
} catch (const TokenException & ex){
Global::debug(0) << "Problem parsing file [" << file << "]. Reason: " << ex.getTrace() << std::endl;
}
Screen::realFinish();
} else {
std::cout << "Usage: ./" << argv[0] << " select-screen.txt" << std::endl;
}
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif<commit_msg>quit sdl in the atexit callback<commit_after>#include "../common/init.h"
#include "../common/timer.h"
#include <iostream>
#include <vector>
#include "character-select.h"
#include "util/debug.h"
#include "util/load_exception.h"
#include "util/token_exception.h"
#include "util/stretch-bitmap.h"
#include "util/input/input.h"
#include "util/input/input-manager.h"
enum Keys{
Up=0,
Down,
Left,
Right,
Esc,
Enter,
};
class Logic: public Util::Logic {
public:
Logic(InputMap<Keys> & input, CharacterSelect & select):
is_done(false),
input(input),
select(select){
}
bool is_done;
InputMap<Keys> & input;
CharacterSelect & select;
bool done(){
return is_done;
}
void run(){
std::vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
for (std::vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
const InputMap<Keys>::InputEvent & event = *it;
if (event.enabled){
if (event.out == Esc){
is_done = true;
}
/* NOTE Assumes only one cursor */
if (event.out == Up){
select.getList()->up(0);
}
if (event.out == Down){
select.getList()->down(0);
}
if (event.out == Left){
select.getList()->left(0);
}
if (event.out == Right){
select.getList()->right(0);
}
if (event.out == Enter){
}
}
}
select.act();
}
double ticks(double system){
return system;
}
};
class Draw: public Util::Draw {
public:
Draw(CharacterSelect & select):
select(select){
}
CharacterSelect & select;
void draw(const Graphics::Bitmap & buffer){
buffer.clear();
select.draw(buffer);
buffer.BlitToScreen();
}
};
int main(int argc, char ** argv){
if (argc > 1){
Screen::realInit();
atexit(Screen::realFinish);
Common::startTimers();
Global::setDebug(0);
std::string file = argv[1];
InputManager manager;
Graphics::Bitmap screen(Graphics::getScreenBuffer());
Util::Parameter<Graphics::Bitmap*> use(Graphics::screenParameter, &screen);
Keyboard::pushRepeatState(true);
InputMap<Keys> input;
input.set(Keyboard::Key_ESC, 0, true, Esc);
input.set(Keyboard::Key_ENTER, 0, true, Enter);
input.set(Keyboard::Key_UP, 0, true, Up);
input.set(Keyboard::Key_DOWN, 0, true, Down);
input.set(Keyboard::Key_LEFT, 0, true, Left);
input.set(Keyboard::Key_RIGHT, 0, true, Right);
try {
CharacterSelect select(file);
Logic logic(input, select);
Draw draw(select);
Util::standardLoop(logic, draw);
} catch (const LoadException & ex){
Global::debug(0) << "Problem loading file [" << file << "]. Reason: " << ex.getTrace() << std::endl;
} catch (const TokenException & ex){
Global::debug(0) << "Problem parsing file [" << file << "]. Reason: " << ex.getTrace() << std::endl;
}
} else {
std::cout << "Usage: ./" << argv[0] << " select-screen.txt" << std::endl;
}
return 0;
}
#ifdef USE_ALLEGRO
END_OF_MAIN()
#endif
<|endoftext|>
|
<commit_before>#include "display.h"
#include "space.h"
#include "container.h"
#include "tree.h"
#include "application.h"
#include "window.h"
#include "helpers.h"
extern kwm_screen KWMScreen;
extern kwm_focus KWMFocus;
extern kwm_tiling KWMTiling;
extern kwm_thread KWMThread;
extern kwm_toggles KWMToggles;
void DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)
{
pthread_mutex_lock(&KWMThread.Lock);
if (Flags & kCGDisplayAddFlag)
{
// Display has been added
DEBUG("New display detected! DisplayID: " << Display << " Index: " << KWMScreen.ActiveCount)
RefreshActiveDisplays();
}
else if (Flags & kCGDisplayRemoveFlag)
{
// Display has been removed
if(CGDisplayIsAsleep(Display))
{
DEBUG("Display " << Display << " is asleep!")
}
else
{
DEBUG("Display has been removed! DisplayID: " << Display)
std::map<int, space_info>::iterator It;
for(It = KWMTiling.DisplayMap[Display].Space.begin(); It != KWMTiling.DisplayMap[Display].Space.end(); ++It)
DestroyNodeTree(It->second.RootNode);
if(KWMTiling.DisplayMap[Display].Identifier)
CFRelease(KWMTiling.DisplayMap[Display].Identifier);
KWMTiling.DisplayMap.erase(Display);
}
RefreshActiveDisplays();
}
pthread_mutex_unlock(&KWMThread.Lock);
}
screen_info CreateDefaultScreenInfo(int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
screen_info Screen;
Screen.Identifier = NULL;
Screen.ID = ScreenIndex;
Screen.ActiveSpace = -1;
Screen.OldWindowListCount = -1;
Screen.X = DisplayRect.origin.x;
Screen.Y = DisplayRect.origin.y;
Screen.Width = DisplayRect.size.width;
Screen.Height = DisplayRect.size.height;
Screen.Settings.Offset = KWMScreen.DefaultOffset;
Screen.Settings.Mode = SpaceModeDefault;
return Screen;
}
void UpdateExistingScreenInfo(screen_info *Screen, int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
Screen->ID = ScreenIndex;
Screen->X = DisplayRect.origin.x;
Screen->Y = DisplayRect.origin.y;
Screen->Width = DisplayRect.size.width;
Screen->Height = DisplayRect.size.height;
Screen->Settings.Offset = KWMScreen.DefaultOffset;
Screen->Settings.Mode = SpaceModeDefault;
}
void GetActiveDisplays()
{
KWMScreen.Displays = (CGDirectDisplayID*) malloc(sizeof(CGDirectDisplayID) * KWMScreen.MaxCount);
CGGetActiveDisplayList(KWMScreen.MaxCount, KWMScreen.Displays, &KWMScreen.ActiveCount);
for(std::size_t DisplayIndex = 0; DisplayIndex < KWMScreen.ActiveCount; ++DisplayIndex)
{
unsigned int DisplayID = KWMScreen.Displays[DisplayIndex];
KWMTiling.DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);;
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
KWMScreen.Current = GetDisplayOfMousePointer();
KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current);
ShouldActiveSpaceBeManaged();
CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);
}
void RefreshActiveDisplays()
{
if(KWMScreen.Displays)
free(KWMScreen.Displays);
KWMScreen.Displays = (CGDirectDisplayID*) malloc(sizeof(CGDirectDisplayID) * KWMScreen.MaxCount);
CGGetActiveDisplayList(KWMScreen.MaxCount, KWMScreen.Displays, &KWMScreen.ActiveCount);
for(std::size_t DisplayIndex = 0; DisplayIndex < KWMScreen.ActiveCount; ++DisplayIndex)
{
unsigned int DisplayID = KWMScreen.Displays[DisplayIndex];
std::map<unsigned int, screen_info>::iterator It = KWMTiling.DisplayMap.find(DisplayID);
if(It != KWMTiling.DisplayMap.end())
UpdateExistingScreenInfo(&KWMTiling.DisplayMap[DisplayID], DisplayID, DisplayIndex);
else
KWMTiling.DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
screen_info *NewScreen = GetDisplayOfMousePointer();
if(NewScreen)
GiveFocusToScreen(NewScreen->ID, NULL, false, true);
}
screen_info *GetDisplayFromScreenID(unsigned int ID)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Screen->ID == ID)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfMousePointer()
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
CGPoint Cursor = GetCursorPos();
screen_info *Screen = &It->second;
if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&
Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfWindow(window_info *Window)
{
if(Window)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width &&
Window->Y >= Screen->Y && Window->Y <= Screen->Y + Screen->Height)
return Screen;
}
return GetDisplayOfMousePointer();
}
return NULL;
}
std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
std::vector<window_info*> ScreenWindowLst;
for(std::size_t WindowIndex = 0; WindowIndex < KWMTiling.WindowLst.size(); ++WindowIndex)
{
window_info *Window = &KWMTiling.WindowLst[WindowIndex];
if(!IsApplicationFloating(&KWMTiling.WindowLst[WindowIndex]) &&
!IsWindowFloating(KWMTiling.WindowLst[WindowIndex].WID, NULL))
{
if(Screen == GetDisplayOfWindow(Window))
ScreenWindowLst.push_back(Window);
}
}
return ScreenWindowLst;
}
void SetDefaultPaddingOfDisplay(container_offset Offset)
{
KWMScreen.DefaultOffset.PaddingTop = Offset.PaddingTop;
KWMScreen.DefaultOffset.PaddingBottom = Offset.PaddingBottom;
KWMScreen.DefaultOffset.PaddingLeft = Offset.PaddingLeft;
KWMScreen.DefaultOffset.PaddingRight = Offset.PaddingRight;
}
void SetDefaultGapOfDisplay(container_offset Offset)
{
KWMScreen.DefaultOffset.VerticalGap = Offset.VerticalGap;
KWMScreen.DefaultOffset.HorizontalGap = Offset.HorizontalGap;
}
void ChangePaddingOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = GetActiveSpaceOfScreen(Screen);
if(Side == "all")
{
if(Space->Settings.Offset.PaddingLeft + Offset >= 0)
Space->Settings.Offset.PaddingLeft += Offset;
if(Space->Settings.Offset.PaddingRight + Offset >= 0)
Space->Settings.Offset.PaddingRight += Offset;
if(Space->Settings.Offset.PaddingTop + Offset >= 0)
Space->Settings.Offset.PaddingTop += Offset;
if(Space->Settings.Offset.PaddingBottom + Offset >= 0)
Space->Settings.Offset.PaddingBottom += Offset;
}
else if(Side == "left")
{
if(Space->Settings.Offset.PaddingLeft + Offset >= 0)
Space->Settings.Offset.PaddingLeft += Offset;
}
else if(Side == "right")
{
if(Space->Settings.Offset.PaddingRight + Offset >= 0)
Space->Settings.Offset.PaddingRight += Offset;
}
else if(Side == "top")
{
if(Space->Settings.Offset.PaddingTop + Offset >= 0)
Space->Settings.Offset.PaddingTop += Offset;
}
else if(Side == "bottom")
{
if(Space->Settings.Offset.PaddingBottom + Offset >= 0)
Space->Settings.Offset.PaddingBottom += Offset;
}
if(Space->RootNode)
{
if(Space->Settings.Mode == SpaceModeBSP)
{
SetRootNodeContainer(Screen, Space->RootNode);
CreateNodeContainers(Screen, Space->RootNode, true);
}
else if(Space->Settings.Mode == SpaceModeMonocle)
{
link_node *Link = Space->RootNode->List;
while(Link)
{
SetLinkNodeContainer(Screen, Link);
Link = Link->Next;
}
}
ApplyTreeNodeContainer(Space->RootNode);
}
}
void ChangeGapOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = GetActiveSpaceOfScreen(Screen);
if(Side == "all")
{
if(Space->Settings.Offset.VerticalGap + Offset >= 0)
Space->Settings.Offset.VerticalGap += Offset;
if(Space->Settings.Offset.HorizontalGap + Offset >= 0)
Space->Settings.Offset.HorizontalGap += Offset;
}
else if(Side == "vertical")
{
if(Space->Settings.Offset.VerticalGap + Offset >= 0)
Space->Settings.Offset.VerticalGap += Offset;
}
else if(Side == "horizontal")
{
if(Space->Settings.Offset.HorizontalGap + Offset >= 0)
Space->Settings.Offset.HorizontalGap += Offset;
}
if(Space->RootNode && Space->Settings.Mode == SpaceModeBSP)
{
CreateNodeContainers(Screen, Space->RootNode, true);
ApplyTreeNodeContainer(Space->RootNode);
}
}
int GetIndexOfNextScreen()
{
return KWMScreen.Current->ID + 1 >= KWMScreen.ActiveCount ? 0 : KWMScreen.Current->ID + 1;
}
int GetIndexOfPrevScreen()
{
return KWMScreen.Current->ID == 0 ? KWMScreen.ActiveCount - 1 : KWMScreen.Current->ID - 1;
}
void GiveFocusToScreen(unsigned int ScreenIndex, tree_node *FocusNode, bool Mouse, bool UpdateFocus)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
if(Screen && Screen != KWMScreen.Current)
{
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current = Screen;
Screen->ActiveSpace = GetActiveSpaceOfDisplay(Screen);
ShouldActiveSpaceBeManaged();
space_info *Space = GetActiveSpaceOfScreen(Screen);
DEBUG("GiveFocusToScreen() " << ScreenIndex << \
": Space transition ended " << KWMScreen.PrevSpace << \
" -> " << Screen->ActiveSpace)
if(UpdateFocus)
{
if(Space->Initialized && FocusNode)
{
DEBUG("Populated Screen 'Window -f Focus'")
UpdateActiveWindowList(Screen);
FilterWindowList(Screen);
SetWindowFocusByNode(FocusNode);
MoveCursorToCenterOfFocusedWindow();
}
else if(Space->Initialized && Space->RootNode)
{
DEBUG("Populated Screen Key/Mouse Focus")
UpdateActiveWindowList(Screen);
FilterWindowList(Screen);
bool WindowBelowCursor = IsAnyWindowBelowCursor();
if(Mouse && !WindowBelowCursor)
ClearFocusedWindow();
else if(Mouse && WindowBelowCursor)
FocusWindowBelowCursor();
if(!Mouse)
{
if(Space->FocusedWindowID == 0)
{
void *FocusNode = NULL;
GetFirstLeafNode(Space->RootNode, (void**)&FocusNode);
if(Space->Settings.Mode == SpaceModeBSP)
Space->FocusedWindowID = ((tree_node*)FocusNode)->WindowID;
else if(Space->Settings.Mode == SpaceModeMonocle)
Space->FocusedWindowID = ((link_node*)FocusNode)->WindowID;
}
FocusWindowByID(Space->FocusedWindowID);
MoveCursorToCenterOfFocusedWindow();
}
}
else
{
if(!Space->Initialized ||
Space->Settings.Mode == SpaceModeFloating ||
!Space->RootNode)
{
DEBUG("Uninitialized Screen")
ClearFocusedWindow();
if(Space->Settings.Mode != SpaceModeFloating)
{
if(!Mouse)
CGWarpMouseCursorPosition(CGPointMake(Screen->X + (Screen->Width / 2),
Screen->Y + (Screen->Height / 2)));
if(!Space->RootNode)
{
CGPoint ClickPos = GetCursorPos();
CGEventRef ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
}
}
}
}
}
}
}
void CaptureApplicationToScreen(int ScreenID, std::string Application)
{
std::map<std::string, int>::iterator It = KWMTiling.CapturedAppLst.find(Application);
if(It == KWMTiling.CapturedAppLst.end())
{
KWMTiling.CapturedAppLst[Application] = ScreenID;
DEBUG("CaptureApplicationToScreen() " << ScreenID << " " << Application)
}
}
void MoveWindowToDisplay(window_info *Window, int Shift, bool Relative, bool UpdateFocus)
{
int NewScreenIndex = -1;
if(Relative)
NewScreenIndex = Shift == 1 ? GetIndexOfNextScreen() : GetIndexOfPrevScreen();
else
NewScreenIndex = Shift;
screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);
if(NewScreen)
AddWindowToTreeOfUnfocusedMonitor(NewScreen, Window, UpdateFocus);
}
container_offset CreateDefaultScreenOffset()
{
container_offset Offset = { 40, 20, 20, 20, 10, 10 };
return Offset;
}
void UpdateActiveScreen()
{
screen_info *Screen = GetDisplayOfMousePointer();
if(KWMScreen.Current != Screen)
{
DEBUG("UpdateActiveScreen() Active Display Changed")
ClearMarkedWindow();
GiveFocusToScreen(Screen->ID, NULL, true, true);
}
}
space_settings *GetSpaceSettingsForDisplay(unsigned int ScreenID)
{
std::map<unsigned int, space_settings>::iterator It = KWMTiling.DisplaySettings.find(ScreenID);
if(It != KWMTiling.DisplaySettings.end())
return &It->second;
else
return NULL;
}
<commit_msg>fix indentation<commit_after>#include "display.h"
#include "space.h"
#include "container.h"
#include "tree.h"
#include "application.h"
#include "window.h"
#include "helpers.h"
extern kwm_screen KWMScreen;
extern kwm_focus KWMFocus;
extern kwm_tiling KWMTiling;
extern kwm_thread KWMThread;
extern kwm_toggles KWMToggles;
void DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)
{
pthread_mutex_lock(&KWMThread.Lock);
if (Flags & kCGDisplayAddFlag)
{
// Display has been added
DEBUG("New display detected! DisplayID: " << Display << " Index: " << KWMScreen.ActiveCount)
RefreshActiveDisplays();
}
else if (Flags & kCGDisplayRemoveFlag)
{
// Display has been removed
if(CGDisplayIsAsleep(Display))
{
DEBUG("Display " << Display << " is asleep!")
}
else
{
DEBUG("Display has been removed! DisplayID: " << Display)
std::map<int, space_info>::iterator It;
for(It = KWMTiling.DisplayMap[Display].Space.begin(); It != KWMTiling.DisplayMap[Display].Space.end(); ++It)
DestroyNodeTree(It->second.RootNode);
if(KWMTiling.DisplayMap[Display].Identifier)
CFRelease(KWMTiling.DisplayMap[Display].Identifier);
KWMTiling.DisplayMap.erase(Display);
}
RefreshActiveDisplays();
}
pthread_mutex_unlock(&KWMThread.Lock);
}
screen_info CreateDefaultScreenInfo(int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
screen_info Screen;
Screen.Identifier = NULL;
Screen.ID = ScreenIndex;
Screen.ActiveSpace = -1;
Screen.OldWindowListCount = -1;
Screen.X = DisplayRect.origin.x;
Screen.Y = DisplayRect.origin.y;
Screen.Width = DisplayRect.size.width;
Screen.Height = DisplayRect.size.height;
Screen.Settings.Offset = KWMScreen.DefaultOffset;
Screen.Settings.Mode = SpaceModeDefault;
return Screen;
}
void UpdateExistingScreenInfo(screen_info *Screen, int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
Screen->ID = ScreenIndex;
Screen->X = DisplayRect.origin.x;
Screen->Y = DisplayRect.origin.y;
Screen->Width = DisplayRect.size.width;
Screen->Height = DisplayRect.size.height;
Screen->Settings.Offset = KWMScreen.DefaultOffset;
Screen->Settings.Mode = SpaceModeDefault;
}
void GetActiveDisplays()
{
KWMScreen.Displays = (CGDirectDisplayID*) malloc(sizeof(CGDirectDisplayID) * KWMScreen.MaxCount);
CGGetActiveDisplayList(KWMScreen.MaxCount, KWMScreen.Displays, &KWMScreen.ActiveCount);
for(std::size_t DisplayIndex = 0; DisplayIndex < KWMScreen.ActiveCount; ++DisplayIndex)
{
unsigned int DisplayID = KWMScreen.Displays[DisplayIndex];
KWMTiling.DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);;
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
KWMScreen.Current = GetDisplayOfMousePointer();
KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current);
ShouldActiveSpaceBeManaged();
CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);
}
void RefreshActiveDisplays()
{
if(KWMScreen.Displays)
free(KWMScreen.Displays);
KWMScreen.Displays = (CGDirectDisplayID*) malloc(sizeof(CGDirectDisplayID) * KWMScreen.MaxCount);
CGGetActiveDisplayList(KWMScreen.MaxCount, KWMScreen.Displays, &KWMScreen.ActiveCount);
for(std::size_t DisplayIndex = 0; DisplayIndex < KWMScreen.ActiveCount; ++DisplayIndex)
{
unsigned int DisplayID = KWMScreen.Displays[DisplayIndex];
std::map<unsigned int, screen_info>::iterator It = KWMTiling.DisplayMap.find(DisplayID);
if(It != KWMTiling.DisplayMap.end())
UpdateExistingScreenInfo(&KWMTiling.DisplayMap[DisplayID], DisplayID, DisplayIndex);
else
KWMTiling.DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
screen_info *NewScreen = GetDisplayOfMousePointer();
if(NewScreen)
GiveFocusToScreen(NewScreen->ID, NULL, false, true);
}
screen_info *GetDisplayFromScreenID(unsigned int ID)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Screen->ID == ID)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfMousePointer()
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
CGPoint Cursor = GetCursorPos();
screen_info *Screen = &It->second;
if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&
Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfWindow(window_info *Window)
{
if(Window)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width &&
Window->Y >= Screen->Y && Window->Y <= Screen->Y + Screen->Height)
return Screen;
}
return GetDisplayOfMousePointer();
}
return NULL;
}
std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
std::vector<window_info*> ScreenWindowLst;
for(std::size_t WindowIndex = 0; WindowIndex < KWMTiling.WindowLst.size(); ++WindowIndex)
{
window_info *Window = &KWMTiling.WindowLst[WindowIndex];
if(!IsApplicationFloating(&KWMTiling.WindowLst[WindowIndex]) &&
!IsWindowFloating(KWMTiling.WindowLst[WindowIndex].WID, NULL))
{
if(Screen == GetDisplayOfWindow(Window))
ScreenWindowLst.push_back(Window);
}
}
return ScreenWindowLst;
}
void SetDefaultPaddingOfDisplay(container_offset Offset)
{
KWMScreen.DefaultOffset.PaddingTop = Offset.PaddingTop;
KWMScreen.DefaultOffset.PaddingBottom = Offset.PaddingBottom;
KWMScreen.DefaultOffset.PaddingLeft = Offset.PaddingLeft;
KWMScreen.DefaultOffset.PaddingRight = Offset.PaddingRight;
}
void SetDefaultGapOfDisplay(container_offset Offset)
{
KWMScreen.DefaultOffset.VerticalGap = Offset.VerticalGap;
KWMScreen.DefaultOffset.HorizontalGap = Offset.HorizontalGap;
}
void ChangePaddingOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = GetActiveSpaceOfScreen(Screen);
if(Side == "all")
{
if(Space->Settings.Offset.PaddingLeft + Offset >= 0)
Space->Settings.Offset.PaddingLeft += Offset;
if(Space->Settings.Offset.PaddingRight + Offset >= 0)
Space->Settings.Offset.PaddingRight += Offset;
if(Space->Settings.Offset.PaddingTop + Offset >= 0)
Space->Settings.Offset.PaddingTop += Offset;
if(Space->Settings.Offset.PaddingBottom + Offset >= 0)
Space->Settings.Offset.PaddingBottom += Offset;
}
else if(Side == "left")
{
if(Space->Settings.Offset.PaddingLeft + Offset >= 0)
Space->Settings.Offset.PaddingLeft += Offset;
}
else if(Side == "right")
{
if(Space->Settings.Offset.PaddingRight + Offset >= 0)
Space->Settings.Offset.PaddingRight += Offset;
}
else if(Side == "top")
{
if(Space->Settings.Offset.PaddingTop + Offset >= 0)
Space->Settings.Offset.PaddingTop += Offset;
}
else if(Side == "bottom")
{
if(Space->Settings.Offset.PaddingBottom + Offset >= 0)
Space->Settings.Offset.PaddingBottom += Offset;
}
if(Space->RootNode)
{
if(Space->Settings.Mode == SpaceModeBSP)
{
SetRootNodeContainer(Screen, Space->RootNode);
CreateNodeContainers(Screen, Space->RootNode, true);
}
else if(Space->Settings.Mode == SpaceModeMonocle)
{
link_node *Link = Space->RootNode->List;
while(Link)
{
SetLinkNodeContainer(Screen, Link);
Link = Link->Next;
}
}
ApplyTreeNodeContainer(Space->RootNode);
}
}
void ChangeGapOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = GetActiveSpaceOfScreen(Screen);
if(Side == "all")
{
if(Space->Settings.Offset.VerticalGap + Offset >= 0)
Space->Settings.Offset.VerticalGap += Offset;
if(Space->Settings.Offset.HorizontalGap + Offset >= 0)
Space->Settings.Offset.HorizontalGap += Offset;
}
else if(Side == "vertical")
{
if(Space->Settings.Offset.VerticalGap + Offset >= 0)
Space->Settings.Offset.VerticalGap += Offset;
}
else if(Side == "horizontal")
{
if(Space->Settings.Offset.HorizontalGap + Offset >= 0)
Space->Settings.Offset.HorizontalGap += Offset;
}
if(Space->RootNode && Space->Settings.Mode == SpaceModeBSP)
{
CreateNodeContainers(Screen, Space->RootNode, true);
ApplyTreeNodeContainer(Space->RootNode);
}
}
int GetIndexOfNextScreen()
{
return KWMScreen.Current->ID + 1 >= KWMScreen.ActiveCount ? 0 : KWMScreen.Current->ID + 1;
}
int GetIndexOfPrevScreen()
{
return KWMScreen.Current->ID == 0 ? KWMScreen.ActiveCount - 1 : KWMScreen.Current->ID - 1;
}
void GiveFocusToScreen(unsigned int ScreenIndex, tree_node *FocusNode, bool Mouse, bool UpdateFocus)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
if(Screen && Screen != KWMScreen.Current)
{
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current = Screen;
Screen->ActiveSpace = GetActiveSpaceOfDisplay(Screen);
ShouldActiveSpaceBeManaged();
space_info *Space = GetActiveSpaceOfScreen(Screen);
DEBUG("GiveFocusToScreen() " << ScreenIndex << \
": Space transition ended " << KWMScreen.PrevSpace << \
" -> " << Screen->ActiveSpace)
if(UpdateFocus)
{
if(Space->Initialized && FocusNode)
{
DEBUG("Populated Screen 'Window -f Focus'")
UpdateActiveWindowList(Screen);
FilterWindowList(Screen);
SetWindowFocusByNode(FocusNode);
MoveCursorToCenterOfFocusedWindow();
}
else if(Space->Initialized && Space->RootNode)
{
DEBUG("Populated Screen Key/Mouse Focus")
UpdateActiveWindowList(Screen);
FilterWindowList(Screen);
bool WindowBelowCursor = IsAnyWindowBelowCursor();
if(Mouse && !WindowBelowCursor)
ClearFocusedWindow();
else if(Mouse && WindowBelowCursor)
FocusWindowBelowCursor();
if(!Mouse)
{
if(Space->FocusedWindowID == 0)
{
void *FocusNode = NULL;
GetFirstLeafNode(Space->RootNode, (void**)&FocusNode);
if(Space->Settings.Mode == SpaceModeBSP)
Space->FocusedWindowID = ((tree_node*)FocusNode)->WindowID;
else if(Space->Settings.Mode == SpaceModeMonocle)
Space->FocusedWindowID = ((link_node*)FocusNode)->WindowID;
}
FocusWindowByID(Space->FocusedWindowID);
MoveCursorToCenterOfFocusedWindow();
}
}
else
{
if(!Space->Initialized ||
Space->Settings.Mode == SpaceModeFloating ||
!Space->RootNode)
{
DEBUG("Uninitialized Screen")
ClearFocusedWindow();
if(!Mouse)
CGWarpMouseCursorPosition(CGPointMake(Screen->X + (Screen->Width / 2), Screen->Y + (Screen->Height / 2)));
if(Space->Settings.Mode != SpaceModeFloating && !Space->RootNode)
{
CGPoint ClickPos = GetCursorPos();
CGEventRef ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
}
}
}
}
}
}
void CaptureApplicationToScreen(int ScreenID, std::string Application)
{
std::map<std::string, int>::iterator It = KWMTiling.CapturedAppLst.find(Application);
if(It == KWMTiling.CapturedAppLst.end())
{
KWMTiling.CapturedAppLst[Application] = ScreenID;
DEBUG("CaptureApplicationToScreen() " << ScreenID << " " << Application)
}
}
void MoveWindowToDisplay(window_info *Window, int Shift, bool Relative, bool UpdateFocus)
{
int NewScreenIndex = -1;
if(Relative)
NewScreenIndex = Shift == 1 ? GetIndexOfNextScreen() : GetIndexOfPrevScreen();
else
NewScreenIndex = Shift;
screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);
if(NewScreen)
AddWindowToTreeOfUnfocusedMonitor(NewScreen, Window, UpdateFocus);
}
container_offset CreateDefaultScreenOffset()
{
container_offset Offset = { 40, 20, 20, 20, 10, 10 };
return Offset;
}
void UpdateActiveScreen()
{
screen_info *Screen = GetDisplayOfMousePointer();
if(KWMScreen.Current != Screen)
{
DEBUG("UpdateActiveScreen() Active Display Changed")
ClearMarkedWindow();
GiveFocusToScreen(Screen->ID, NULL, true, true);
}
}
space_settings *GetSpaceSettingsForDisplay(unsigned int ScreenID)
{
std::map<unsigned int, space_settings>::iterator It = KWMTiling.DisplaySettings.find(ScreenID);
if(It != KWMTiling.DisplaySettings.end())
return &It->second;
else
return NULL;
}
<|endoftext|>
|
<commit_before>#include "kwm.h"
extern uint32_t MaxDisplayCount;
extern uint32_t ActiveDisplaysCount;
extern CGDirectDisplayID ActiveDisplays[];
extern screen_info *Screen;
extern std::map<unsigned int, screen_info> DisplayMap;
extern std::vector<window_info> WindowLst;
extern window_info *FocusedWindow;
extern int DefaultPaddingLeft, DefaultPaddingRight;
extern int DefaultPaddingTop, DefaultPaddingBottom;
extern int DefaultGapVertical, DefaultGapHorizontal;
extern pthread_mutex_t BackgroundLock;
void DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)
{
pthread_mutex_lock(&BackgroundLock);
if (Flags & kCGDisplayAddFlag)
{
// Display has been added
DEBUG("New display detected! DisplayID: " << Display << " Index: " << ActiveDisplaysCount)
RefreshActiveDisplays();
}
else if (Flags & kCGDisplayRemoveFlag)
{
// Display has been removed
DEBUG("Display has been removed! DisplayID: " << Display)
std::map<int, space_info>::iterator It;
for(It = DisplayMap[Display].Space.begin(); It != DisplayMap[Display].Space.end(); ++It)
DestroyNodeTree(It->second.RootNode);
DisplayMap.erase(Display);
RefreshActiveDisplays();
}
pthread_mutex_unlock(&BackgroundLock);
}
screen_info CreateDefaultScreenInfo(int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
screen_info Screen;
Screen.ID = ScreenIndex;
Screen.ForceContainerUpdate = false;
Screen.ActiveSpace = 0;
Screen.OldWindowListCount = -1;
Screen.X = DisplayRect.origin.x;
Screen.Y = DisplayRect.origin.y;
Screen.Width = DisplayRect.size.width;
Screen.Height = DisplayRect.size.height;
Screen.PaddingTop = DefaultPaddingTop;
Screen.PaddingLeft = DefaultPaddingLeft;
Screen.PaddingRight = DefaultPaddingRight;
Screen.PaddingBottom = DefaultPaddingBottom;
Screen.VerticalGap = DefaultGapVertical;
Screen.HorizontalGap = DefaultGapHorizontal;
return Screen;
}
void UpdateExistingScreenInfo(screen_info *Screen, int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
Screen->ID = ScreenIndex;
Screen->X = DisplayRect.origin.x;
Screen->Y = DisplayRect.origin.y;
Screen->Width = DisplayRect.size.width;
Screen->Height = DisplayRect.size.height;
Screen->PaddingTop = DefaultPaddingTop;
Screen->PaddingLeft = DefaultPaddingLeft;
Screen->PaddingRight = DefaultPaddingRight;
Screen->PaddingBottom = DefaultPaddingBottom;
Screen->VerticalGap = DefaultGapVertical;
Screen->HorizontalGap = DefaultGapHorizontal;
Screen->ForceContainerUpdate = true;
}
void GetActiveDisplays()
{
CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
{
unsigned int DisplayID = ActiveDisplays[DisplayIndex];
DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);;
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
Screen = GetDisplayOfMousePointer();
CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);
}
void RefreshActiveDisplays()
{
CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
{
unsigned int DisplayID = ActiveDisplays[DisplayIndex];
std::map<unsigned int, screen_info>::iterator It;
if(It != DisplayMap.end())
UpdateExistingScreenInfo(&DisplayMap[DisplayID], DisplayID, DisplayIndex);
else
DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
Screen = GetDisplayOfMousePointer();
}
screen_info *GetDisplayFromScreenID(int ID)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Screen->ID == ID)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfMousePointer()
{
std::map<unsigned int, screen_info>::iterator It;
for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
{
CGPoint Cursor = GetCursorPos();
screen_info *Screen = &It->second;
if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&
Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfWindow(window_info *Window)
{
if(Window)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
return Screen;
}
}
return NULL;
}
std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
std::vector<window_info*> ScreenWindowLst;
for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
{
window_info *Window = &WindowLst[WindowIndex];
if(!IsApplicationFloating(&WindowLst[WindowIndex]))
{
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
ScreenWindowLst.push_back(Window);
}
}
return ScreenWindowLst;
}
std::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
std::vector<int> ScreenWindowIDLst;
for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
{
window_info *Window = &WindowLst[WindowIndex];
if(!IsApplicationFloating(&WindowLst[WindowIndex]))
{
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
ScreenWindowIDLst.push_back(Window->WID);
}
}
return ScreenWindowIDLst;
}
void SetDefaultPaddingOfDisplay(const std::string &Side, int Offset)
{
if(Side == "left")
DefaultPaddingLeft = Offset;
else if(Side == "right")
DefaultPaddingRight = Offset;
else if(Side == "top")
DefaultPaddingTop = Offset;
else if(Side == "bottom")
DefaultPaddingBottom = Offset;
}
void SetDefaultGapOfDisplay(const std::string &Side, int Offset)
{
if(Side == "vertical")
DefaultGapVertical = Offset;
else if(Side == "horizontal")
DefaultGapHorizontal = Offset;
}
void ChangePaddingOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = &Screen->Space[Screen->ActiveSpace];
if(Side == "left")
{
if(Space->PaddingLeft + Offset >= 0)
Space->PaddingLeft += Offset;
}
else if(Side == "right")
{
if(Space->PaddingRight + Offset >= 0)
Space->PaddingRight += Offset;
}
else if(Side == "top")
{
if(Space->PaddingTop + Offset >= 0)
Space->PaddingTop += Offset;
}
else if(Side == "bottom")
{
if(Space->PaddingBottom + Offset >= 0)
Space->PaddingBottom += Offset;
}
SetRootNodeContainer(Screen, Space->RootNode);
CreateNodeContainers(Screen, Space->RootNode, true);
ApplyNodeContainer(Space->RootNode);
}
void ChangeGapOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = &Screen->Space[Screen->ActiveSpace];
if(Side == "vertical")
{
if(Space->VerticalGap + Offset >= 0)
Space->VerticalGap += Offset;
}
else if(Side == "horizontal")
{
if(Space->HorizontalGap + Offset >= 0)
Space->HorizontalGap += Offset;
}
CreateNodeContainers(Screen, Space->RootNode, true);
ApplyNodeContainer(Space->RootNode);
}
void CycleFocusedWindowDisplay(int Shift, bool Relative)
{
screen_info *Screen = GetDisplayOfWindow(FocusedWindow);
int NewScreenIndex = -1;
if(Relative)
{
if(Shift == 1)
NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;
else if(Shift == -1)
NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;
}
else
{
NewScreenIndex = Shift;
}
if(NewScreenIndex != Screen->ID)
{
screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);
AddWindowToTreeOfUnfocusedMonitor(NewScreen);
}
}
<commit_msg>fixed #35 - trying to adjust padding/gaps of space with only floating windows<commit_after>#include "kwm.h"
extern uint32_t MaxDisplayCount;
extern uint32_t ActiveDisplaysCount;
extern CGDirectDisplayID ActiveDisplays[];
extern screen_info *Screen;
extern std::map<unsigned int, screen_info> DisplayMap;
extern std::vector<window_info> WindowLst;
extern window_info *FocusedWindow;
extern int DefaultPaddingLeft, DefaultPaddingRight;
extern int DefaultPaddingTop, DefaultPaddingBottom;
extern int DefaultGapVertical, DefaultGapHorizontal;
extern pthread_mutex_t BackgroundLock;
void DisplayReconfigurationCallBack(CGDirectDisplayID Display, CGDisplayChangeSummaryFlags Flags, void *UserInfo)
{
pthread_mutex_lock(&BackgroundLock);
if (Flags & kCGDisplayAddFlag)
{
// Display has been added
DEBUG("New display detected! DisplayID: " << Display << " Index: " << ActiveDisplaysCount)
RefreshActiveDisplays();
}
else if (Flags & kCGDisplayRemoveFlag)
{
// Display has been removed
DEBUG("Display has been removed! DisplayID: " << Display)
std::map<int, space_info>::iterator It;
for(It = DisplayMap[Display].Space.begin(); It != DisplayMap[Display].Space.end(); ++It)
DestroyNodeTree(It->second.RootNode);
DisplayMap.erase(Display);
RefreshActiveDisplays();
}
pthread_mutex_unlock(&BackgroundLock);
}
screen_info CreateDefaultScreenInfo(int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
screen_info Screen;
Screen.ID = ScreenIndex;
Screen.ForceContainerUpdate = false;
Screen.ActiveSpace = 0;
Screen.OldWindowListCount = -1;
Screen.X = DisplayRect.origin.x;
Screen.Y = DisplayRect.origin.y;
Screen.Width = DisplayRect.size.width;
Screen.Height = DisplayRect.size.height;
Screen.PaddingTop = DefaultPaddingTop;
Screen.PaddingLeft = DefaultPaddingLeft;
Screen.PaddingRight = DefaultPaddingRight;
Screen.PaddingBottom = DefaultPaddingBottom;
Screen.VerticalGap = DefaultGapVertical;
Screen.HorizontalGap = DefaultGapHorizontal;
return Screen;
}
void UpdateExistingScreenInfo(screen_info *Screen, int DisplayIndex, int ScreenIndex)
{
CGRect DisplayRect = CGDisplayBounds(DisplayIndex);
Screen->ID = ScreenIndex;
Screen->X = DisplayRect.origin.x;
Screen->Y = DisplayRect.origin.y;
Screen->Width = DisplayRect.size.width;
Screen->Height = DisplayRect.size.height;
Screen->PaddingTop = DefaultPaddingTop;
Screen->PaddingLeft = DefaultPaddingLeft;
Screen->PaddingRight = DefaultPaddingRight;
Screen->PaddingBottom = DefaultPaddingBottom;
Screen->VerticalGap = DefaultGapVertical;
Screen->HorizontalGap = DefaultGapHorizontal;
Screen->ForceContainerUpdate = true;
}
void GetActiveDisplays()
{
CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
{
unsigned int DisplayID = ActiveDisplays[DisplayIndex];
DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);;
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
Screen = GetDisplayOfMousePointer();
CGDisplayRegisterReconfigurationCallback(DisplayReconfigurationCallBack, NULL);
}
void RefreshActiveDisplays()
{
CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
{
unsigned int DisplayID = ActiveDisplays[DisplayIndex];
std::map<unsigned int, screen_info>::iterator It;
if(It != DisplayMap.end())
UpdateExistingScreenInfo(&DisplayMap[DisplayID], DisplayID, DisplayIndex);
else
DisplayMap[DisplayID] = CreateDefaultScreenInfo(DisplayID, DisplayIndex);
DEBUG("DisplayID " << DisplayID << " has index " << DisplayIndex)
}
Screen = GetDisplayOfMousePointer();
}
screen_info *GetDisplayFromScreenID(int ID)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Screen->ID == ID)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfMousePointer()
{
std::map<unsigned int, screen_info>::iterator It;
for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
{
CGPoint Cursor = GetCursorPos();
screen_info *Screen = &It->second;
if(Cursor.x >= Screen->X && Cursor.x <= Screen->X + Screen->Width &&
Cursor.y >= Screen->Y && Cursor.y <= Screen->Y + Screen->Height)
return Screen;
}
return NULL;
}
screen_info *GetDisplayOfWindow(window_info *Window)
{
if(Window)
{
std::map<unsigned int, screen_info>::iterator It;
for(It = DisplayMap.begin(); It != DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
return Screen;
}
}
return NULL;
}
std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
std::vector<window_info*> ScreenWindowLst;
for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
{
window_info *Window = &WindowLst[WindowIndex];
if(!IsApplicationFloating(&WindowLst[WindowIndex]))
{
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
ScreenWindowLst.push_back(Window);
}
}
return ScreenWindowLst;
}
std::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)
{
screen_info *Screen = GetDisplayFromScreenID(ScreenIndex);
std::vector<int> ScreenWindowIDLst;
for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
{
window_info *Window = &WindowLst[WindowIndex];
if(!IsApplicationFloating(&WindowLst[WindowIndex]))
{
if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
ScreenWindowIDLst.push_back(Window->WID);
}
}
return ScreenWindowIDLst;
}
void SetDefaultPaddingOfDisplay(const std::string &Side, int Offset)
{
if(Side == "left")
DefaultPaddingLeft = Offset;
else if(Side == "right")
DefaultPaddingRight = Offset;
else if(Side == "top")
DefaultPaddingTop = Offset;
else if(Side == "bottom")
DefaultPaddingBottom = Offset;
}
void SetDefaultGapOfDisplay(const std::string &Side, int Offset)
{
if(Side == "vertical")
DefaultGapVertical = Offset;
else if(Side == "horizontal")
DefaultGapHorizontal = Offset;
}
void ChangePaddingOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = &Screen->Space[Screen->ActiveSpace];
if(Side == "left")
{
if(Space->PaddingLeft + Offset >= 0)
Space->PaddingLeft += Offset;
}
else if(Side == "right")
{
if(Space->PaddingRight + Offset >= 0)
Space->PaddingRight += Offset;
}
else if(Side == "top")
{
if(Space->PaddingTop + Offset >= 0)
Space->PaddingTop += Offset;
}
else if(Side == "bottom")
{
if(Space->PaddingBottom + Offset >= 0)
Space->PaddingBottom += Offset;
}
if(Space->RootNode)
{
SetRootNodeContainer(Screen, Space->RootNode);
CreateNodeContainers(Screen, Space->RootNode, true);
ApplyNodeContainer(Space->RootNode);
}
}
void ChangeGapOfDisplay(const std::string &Side, int Offset)
{
screen_info *Screen = GetDisplayOfMousePointer();
space_info *Space = &Screen->Space[Screen->ActiveSpace];
if(Side == "vertical")
{
if(Space->VerticalGap + Offset >= 0)
Space->VerticalGap += Offset;
}
else if(Side == "horizontal")
{
if(Space->HorizontalGap + Offset >= 0)
Space->HorizontalGap += Offset;
}
if(Space->RootNode)
{
CreateNodeContainers(Screen, Space->RootNode, true);
ApplyNodeContainer(Space->RootNode);
}
}
void CycleFocusedWindowDisplay(int Shift, bool Relative)
{
screen_info *Screen = GetDisplayOfWindow(FocusedWindow);
int NewScreenIndex = -1;
if(Relative)
{
if(Shift == 1)
NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;
else if(Shift == -1)
NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;
}
else
{
NewScreenIndex = Shift;
}
if(NewScreenIndex != Screen->ID)
{
screen_info *NewScreen = GetDisplayFromScreenID(NewScreenIndex);
AddWindowToTreeOfUnfocusedMonitor(NewScreen);
}
}
<|endoftext|>
|
<commit_before>/// Causal Dynamical Triangulations in C++ using CGAL
///
/// Copyright (c) 2016 Adam Getchell
///
/// Checks that the MoveManager RAII class handles resources properly.
/// @file MoveManagerTest.cpp
/// @brief Tests for the MoveManager RAII class
/// @author Adam Getchell
#include <tuple>
#include <vector>
#include <utility>
#include <algorithm>
#include "gmock/gmock.h"
#include "MoveManager.h"
#include "S3ErgodicMoves.h"
using namespace testing; // NOLINT
class MoveManagerTest : public Test {
public:
MoveManagerTest() : universe_(std::move(make_triangulation(6400, 17))),
movable_simplex_types_(classify_simplices(universe_)),
movable_edge_types_(classify_edges(universe_)),
attempted_moves_(std::make_tuple(0, 0, 0, 0, 0)),
number_of_vertices_(universe_->number_of_vertices()) {}
virtual void SetUp() {
// Print ctor-initialized values
std::cout << "(3,1) simplices: "
<< std::get<0>(movable_simplex_types_).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(movable_simplex_types_).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(movable_simplex_types_).size() << std::endl;
std::cout << "Timelike edges: "
<< movable_edge_types_.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< movable_edge_types_.second << std::endl;
std::cout << "Vertices: "
<< number_of_vertices_ << std::endl;
}
std::unique_ptr<Delaunay> universe_;
///< Unique pointer to the Delaunay triangulation
std::tuple<std::vector<Cell_handle>,
std::vector<Cell_handle>,
std::vector<Cell_handle>> movable_simplex_types_;
///< Movable (3,1), (2,2) and (1,3) simplices.
std::pair<std::vector<Edge_tuple>, uintmax_t> movable_edge_types_;
///< Movable timelike and spacelike edges.
Move_tuple attempted_moves_;
///< A count of all attempted moves
std::uintmax_t number_of_vertices_;
///< Vertices in Delaunay triangulation
};
TEST_F(MoveManagerTest, DelaunayDeepCopyCtor) {
// Print info on move/copy operation exception safety
std::cout << std::boolalpha
<< "Delaunay alias is copy-assignable? "
<< std::is_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow copy-assignable? "
<< std::is_nothrow_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<Delaunay>::value << '\n'
<< "unique_ptr<Delaunay> is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<std::unique_ptr<Delaunay>>::value
<< std::endl;
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe is invalid.";
// Make a copy using Delaunay copy-ctor
auto tempDT = Delaunay(*this->universe_);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Delaunay copy is invalid.";
EXPECT_THAT(number_of_vertices_, Eq(tempDT_ptr->number_of_vertices()))
<< "Delaunay copy doesn't have the same number of vertices.";
EXPECT_THAT(this->universe_->number_of_finite_edges(),
Eq(tempDT_ptr->number_of_finite_edges()))
<< "Delaunay copy doesn't have the same number of edges.";
EXPECT_THAT(this->universe_->number_of_finite_facets(),
Eq(tempDT_ptr->number_of_finite_facets()))
<< "Delaunay copy doesn't have the same number of facets.";
EXPECT_THAT(this->universe_->number_of_finite_cells(),
Eq(tempDT_ptr->number_of_finite_cells()))
<< "Delaunay copy doesn't have the same number of cells.";
// Calculate copied simplex types
auto tempDT_simplex_types = classify_simplices(tempDT_ptr);
EXPECT_THAT(std::get<0>(this->movable_simplex_types_).size(),
Eq(std::get<0>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (3,1) simplices.";
EXPECT_THAT(std::get<1>(this->movable_simplex_types_).size(),
Eq(std::get<1>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (2,2) simplices.";
EXPECT_THAT(std::get<2>(this->movable_simplex_types_).size(),
Eq(std::get<2>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (1,3) simplices.";
// Calculate copied edge types
auto tempDT_edge_types = classify_edges(tempDT_ptr);
EXPECT_THAT(this->movable_edge_types_.first.size(),
Eq(tempDT_edge_types.first.size()))
<< "Delaunay copy doesn't have the same number of timelike edges.";
EXPECT_THAT(this->movable_edge_types_.second, Eq(tempDT_edge_types.second))
<< "Delaunay copy doesn't have the same number of spacelike edges.";
}
TEST_F(MoveManagerTest, MakeA23MoveOnACopyAndSwap) {
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe_ is invalid.";
// Make a copy using Delaunay copy-ctor
auto tempDT = Delaunay(*this->universe_);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Copied universe is invalid.";
auto simplex_types = classify_simplices(tempDT_ptr);
tempDT_ptr = std::move(make_23_move(tempDT_ptr,
simplex_types,
attempted_moves_));
std::cout << "Attempted (2,3) moves = " << std::get<0>(attempted_moves_)
<< std::endl;
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Copied universe invalid after make_23_move().";
std::swap(this->universe_, tempDT_ptr);
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "universe_ invalid after swap with copied universe.";
// Re-populate with current data
auto new_movable_simplex_types = classify_simplices(this->universe_);
auto new_movable_edge_types = classify_edges(this->universe_);
// Print new values
std::cout << "New values: " << std::endl;
std::cout << "(3,1) simplices: "
<< std::get<0>(new_movable_simplex_types).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(new_movable_simplex_types).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(new_movable_simplex_types).size() << std::endl;
std::cout << "Timelike edges: "
<< new_movable_edge_types.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< new_movable_edge_types.second << std::endl;
std::cout << "Vertices: "
<< this->universe_->number_of_vertices() << std::endl;
EXPECT_THAT(std::get<0>(attempted_moves_), Ge(1))
<< "make_23_move() didn't record an attempted move.";
EXPECT_THAT(std::get<1>(new_movable_simplex_types).size(),
Eq(std::get<1>(movable_simplex_types_).size()+1))
<< "make_23_move() didn't add one and only one (2,2) simplex.";
EXPECT_THAT(std::get<0>(new_movable_simplex_types).size(),
Eq(std::get<0>(movable_simplex_types_).size()))
<< "make_23_move() changed (3,1) simplices.";
EXPECT_THAT(std::get<2>(new_movable_simplex_types).size(),
Eq(std::get<2>(movable_simplex_types_).size()))
<< "make_23_move() changed (1,3) simplices.";
EXPECT_THAT(new_movable_edge_types.first.size(),
Eq(movable_edge_types_.first.size()+1))
<< "make_23_move() didn't add one and only one timelike edge.";
EXPECT_THAT(new_movable_edge_types.second, Eq(movable_edge_types_.second))
<< "make_23_move() changed the number of spacelike edges.";
EXPECT_THAT(this->universe_->number_of_vertices(),
Eq(number_of_vertices_))
<< "make_23_move() changed the number of vertices.";
}
TEST_F(MoveManagerTest, DISABLED_MakeA23MoveManager) {
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe_ is invalid.";
PachnerMove p(universe_,
move_type::TWO_THREE,
movable_simplex_types_,
movable_edge_types_);
std::cout << "Attempted (2,3) moves = " << std::get<0>(p.attempted_moves_)
<< std::endl;
// Move info from MoveManager
universe_ = std::move(p.universe_);
std::get<0>(attempted_moves_) += std::get<0>(p.attempted_moves_);
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "MoveManager(TWO_THREE) invalidated universe_.";
// Re-populate with current data
auto new_movable_simplex_types = classify_simplices(this->universe_);
auto new_movable_edge_types = classify_edges(this->universe_);
// Print new values
std::cout << "New values: " << std::endl;
std::cout << "(3,1) simplices: "
<< std::get<0>(new_movable_simplex_types).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(new_movable_simplex_types).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(new_movable_simplex_types).size() << std::endl;
std::cout << "Timelike edges: "
<< new_movable_edge_types.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< new_movable_edge_types.second << std::endl;
std::cout << "Vertices: "
<< this->universe_->number_of_vertices() << std::endl;
EXPECT_THAT(std::get<0>(attempted_moves_), Ge(1))
<< "MoveManager(TWO_THREE) didn't record an attempted move.";
EXPECT_THAT(std::get<1>(new_movable_simplex_types).size(),
Eq(std::get<1>(movable_simplex_types_).size()+1))
<< "MoveManager(TWO_THREE) didn't add one and only one (2,2) simplex.";
EXPECT_THAT(std::get<0>(new_movable_simplex_types).size(),
Eq(std::get<0>(movable_simplex_types_).size()))
<< "MoveManager(TWO_THREE) changed (3,1) simplices.";
EXPECT_THAT(std::get<2>(new_movable_simplex_types).size(),
Eq(std::get<2>(movable_simplex_types_).size()))
<< "MoveManager(TWO_THREE) changed (1,3) simplices.";
EXPECT_THAT(new_movable_edge_types.first.size(),
Eq(movable_edge_types_.first.size()+1))
<< "MoveManager(TWO_THREE) didn't add one and only one timelike edge.";
EXPECT_THAT(new_movable_edge_types.second, Eq(movable_edge_types_.second))
<< "MoveManager(TWO_THREE) changed the number of spacelike edges.";
EXPECT_THAT(this->universe_->number_of_vertices(),
Eq(number_of_vertices_))
<< "MoveManager(TWO_THREE) changed the number of vertices.";
}
<commit_msg>Ensure correct initialization of MoveManagerTest class<commit_after>/// Causal Dynamical Triangulations in C++ using CGAL
///
/// Copyright (c) 2016 Adam Getchell
///
/// Checks that the MoveManager RAII class handles resources properly.
/// @file MoveManagerTest.cpp
/// @brief Tests for the MoveManager RAII class
/// @author Adam Getchell
#include <tuple>
#include <vector>
#include <utility>
#include <algorithm>
#include "gmock/gmock.h"
#include "MoveManager.h"
#include "S3ErgodicMoves.h"
using namespace testing; // NOLINT
class MoveManagerTest : public Test {
public:
MoveManagerTest() : universe_(std::move(make_triangulation(6400, 17))),
movable_simplex_types_(classify_simplices(universe_)),
movable_edge_types_(classify_edges(universe_)),
attempted_moves_(std::make_tuple(0, 0, 0, 0, 0)),
number_of_vertices_(universe_->number_of_vertices()) {}
virtual void SetUp() {
// Print ctor-initialized values
std::cout << "(3,1) simplices: "
<< std::get<0>(movable_simplex_types_).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(movable_simplex_types_).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(movable_simplex_types_).size() << std::endl;
std::cout << "Timelike edges: "
<< movable_edge_types_.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< movable_edge_types_.second << std::endl;
std::cout << "Vertices: "
<< number_of_vertices_ << std::endl;
}
Delaunay triangulation;
///< Delaunay triangulation
std::unique_ptr<Delaunay>
universe_ = std::make_unique<Delaunay>(triangulation);
///< Unique pointer to the Delaunay triangulation
std::tuple<std::vector<Cell_handle>,
std::vector<Cell_handle>,
std::vector<Cell_handle>> movable_simplex_types_;
///< Movable (3,1), (2,2) and (1,3) simplices.
std::pair<std::vector<Edge_tuple>, uintmax_t> movable_edge_types_;
///< Movable timelike and spacelike edges.
Move_tuple attempted_moves_;
///< A count of all attempted moves
std::uintmax_t number_of_vertices_;
///< Vertices in Delaunay triangulation
};
TEST_F(MoveManagerTest, DelaunayDeepCopyCtor) {
// Print info on move/copy operation exception safety
std::cout << std::boolalpha
<< "Delaunay alias is copy-assignable? "
<< std::is_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow copy-assignable? "
<< std::is_nothrow_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<Delaunay>::value << '\n'
<< "unique_ptr<Delaunay> is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<std::unique_ptr<Delaunay>>::value
<< std::endl;
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe is invalid.";
// Make a copy using Delaunay copy-ctor
auto tempDT = Delaunay(*this->universe_);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Delaunay copy is invalid.";
EXPECT_THAT(number_of_vertices_, Eq(tempDT_ptr->number_of_vertices()))
<< "Delaunay copy doesn't have the same number of vertices.";
EXPECT_THAT(this->universe_->number_of_finite_edges(),
Eq(tempDT_ptr->number_of_finite_edges()))
<< "Delaunay copy doesn't have the same number of edges.";
EXPECT_THAT(this->universe_->number_of_finite_facets(),
Eq(tempDT_ptr->number_of_finite_facets()))
<< "Delaunay copy doesn't have the same number of facets.";
EXPECT_THAT(this->universe_->number_of_finite_cells(),
Eq(tempDT_ptr->number_of_finite_cells()))
<< "Delaunay copy doesn't have the same number of cells.";
// Calculate copied simplex types
auto tempDT_simplex_types = classify_simplices(tempDT_ptr);
EXPECT_THAT(std::get<0>(this->movable_simplex_types_).size(),
Eq(std::get<0>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (3,1) simplices.";
EXPECT_THAT(std::get<1>(this->movable_simplex_types_).size(),
Eq(std::get<1>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (2,2) simplices.";
EXPECT_THAT(std::get<2>(this->movable_simplex_types_).size(),
Eq(std::get<2>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (1,3) simplices.";
// Calculate copied edge types
auto tempDT_edge_types = classify_edges(tempDT_ptr);
EXPECT_THAT(this->movable_edge_types_.first.size(),
Eq(tempDT_edge_types.first.size()))
<< "Delaunay copy doesn't have the same number of timelike edges.";
EXPECT_THAT(this->movable_edge_types_.second, Eq(tempDT_edge_types.second))
<< "Delaunay copy doesn't have the same number of spacelike edges.";
}
TEST_F(MoveManagerTest, MakeA23MoveOnACopyAndSwap) {
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe_ is invalid.";
// Make a copy using Delaunay copy-ctor
auto tempDT = Delaunay(*this->universe_);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Copied universe is invalid.";
auto simplex_types = classify_simplices(tempDT_ptr);
tempDT_ptr = std::move(make_23_move(tempDT_ptr,
simplex_types,
attempted_moves_));
std::cout << "Attempted (2,3) moves = " << std::get<0>(attempted_moves_)
<< std::endl;
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Copied universe invalid after make_23_move().";
std::swap(this->universe_, tempDT_ptr);
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "universe_ invalid after swap with copied universe.";
// Re-populate with current data
auto new_movable_simplex_types = classify_simplices(this->universe_);
auto new_movable_edge_types = classify_edges(this->universe_);
// Print new values
std::cout << "New values: " << std::endl;
std::cout << "(3,1) simplices: "
<< std::get<0>(new_movable_simplex_types).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(new_movable_simplex_types).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(new_movable_simplex_types).size() << std::endl;
std::cout << "Timelike edges: "
<< new_movable_edge_types.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< new_movable_edge_types.second << std::endl;
std::cout << "Vertices: "
<< this->universe_->number_of_vertices() << std::endl;
EXPECT_THAT(std::get<0>(attempted_moves_), Ge(1))
<< "make_23_move() didn't record an attempted move.";
EXPECT_THAT(std::get<1>(new_movable_simplex_types).size(),
Eq(std::get<1>(movable_simplex_types_).size()+1))
<< "make_23_move() didn't add one and only one (2,2) simplex.";
EXPECT_THAT(std::get<0>(new_movable_simplex_types).size(),
Eq(std::get<0>(movable_simplex_types_).size()))
<< "make_23_move() changed (3,1) simplices.";
EXPECT_THAT(std::get<2>(new_movable_simplex_types).size(),
Eq(std::get<2>(movable_simplex_types_).size()))
<< "make_23_move() changed (1,3) simplices.";
EXPECT_THAT(new_movable_edge_types.first.size(),
Eq(movable_edge_types_.first.size()+1))
<< "make_23_move() didn't add one and only one timelike edge.";
EXPECT_THAT(new_movable_edge_types.second, Eq(movable_edge_types_.second))
<< "make_23_move() changed the number of spacelike edges.";
EXPECT_THAT(this->universe_->number_of_vertices(),
Eq(number_of_vertices_))
<< "make_23_move() changed the number of vertices.";
}
TEST_F(MoveManagerTest, DISABLED_MakeA23MoveManager) {
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe_ is invalid.";
PachnerMove p(universe_,
move_type::TWO_THREE,
movable_simplex_types_,
movable_edge_types_);
std::cout << "Attempted (2,3) moves = " << std::get<0>(p.attempted_moves_)
<< std::endl;
// Move info from MoveManager
universe_ = std::move(p.universe_);
std::get<0>(attempted_moves_) += std::get<0>(p.attempted_moves_);
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "MoveManager(TWO_THREE) invalidated universe_.";
// Re-populate with current data
auto new_movable_simplex_types = classify_simplices(this->universe_);
auto new_movable_edge_types = classify_edges(this->universe_);
// Print new values
std::cout << "New values: " << std::endl;
std::cout << "(3,1) simplices: "
<< std::get<0>(new_movable_simplex_types).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(new_movable_simplex_types).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(new_movable_simplex_types).size() << std::endl;
std::cout << "Timelike edges: "
<< new_movable_edge_types.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< new_movable_edge_types.second << std::endl;
std::cout << "Vertices: "
<< this->universe_->number_of_vertices() << std::endl;
EXPECT_THAT(std::get<0>(attempted_moves_), Ge(1))
<< "MoveManager(TWO_THREE) didn't record an attempted move.";
EXPECT_THAT(std::get<1>(new_movable_simplex_types).size(),
Eq(std::get<1>(movable_simplex_types_).size()+1))
<< "MoveManager(TWO_THREE) didn't add one and only one (2,2) simplex.";
EXPECT_THAT(std::get<0>(new_movable_simplex_types).size(),
Eq(std::get<0>(movable_simplex_types_).size()))
<< "MoveManager(TWO_THREE) changed (3,1) simplices.";
EXPECT_THAT(std::get<2>(new_movable_simplex_types).size(),
Eq(std::get<2>(movable_simplex_types_).size()))
<< "MoveManager(TWO_THREE) changed (1,3) simplices.";
EXPECT_THAT(new_movable_edge_types.first.size(),
Eq(movable_edge_types_.first.size()+1))
<< "MoveManager(TWO_THREE) didn't add one and only one timelike edge.";
EXPECT_THAT(new_movable_edge_types.second, Eq(movable_edge_types_.second))
<< "MoveManager(TWO_THREE) changed the number of spacelike edges.";
EXPECT_THAT(this->universe_->number_of_vertices(),
Eq(number_of_vertices_))
<< "MoveManager(TWO_THREE) changed the number of vertices.";
}
<|endoftext|>
|
<commit_before>/// Causal Dynamical Triangulations in C++ using CGAL
///
/// Copyright (c) 2016 Adam Getchell
///
/// Checks that the PachnerMove RAII class handles resources properly.
/// @file PachnerMoveTest.cpp
/// @brief Tests for the PachnerMove RAII class
/// @author Adam Getchell
#include "gmock/gmock.h"
#include "PachnerMove.h"
#include "S3Triangulation.h"
using namespace testing; // NOLINT
TEST(PachnerMoveTest, DeepCopyCtor) {
// This is a std::unique_ptr<Delaunay>
auto universe = std::move(make_triangulation(6400, 17));
auto tempDT = Delaunay(*universe);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
// Print info on move/copy operation exception safety
std::cout << std::boolalpha
<< "Delaunay alias is copy-assignable? "
<< std::is_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow copy-assignable? "
<< std::is_nothrow_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<Delaunay>::value << '\n'
<< "unique_ptr<Delaunay> is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<std::unique_ptr<Delaunay>>::value
<< std::endl;
EXPECT_THAT(universe->number_of_vertices(),
Eq(tempDT_ptr->number_of_vertices()))
<< "Delaunay copy doesn't have the same number of vertices.";
EXPECT_THAT(universe->number_of_finite_edges(),
Eq(tempDT_ptr->number_of_finite_edges()))
<< "Delaunay copy doesn't have the same number of edges.";
EXPECT_THAT(universe->number_of_finite_facets(),
Eq(tempDT_ptr->number_of_finite_facets()))
<< "Delaunay copy doesn't have the same number of facets.";
EXPECT_THAT(universe->number_of_finite_cells(),
Eq(tempDT_ptr->number_of_finite_cells()))
<< "Delaunay copy doesn't have the same number of cells.";
auto simplex_types = classify_simplices(universe);
auto tempDT_simplex_types = classify_simplices(tempDT_ptr);
EXPECT_THAT(std::get<0>(simplex_types).size(),
Eq(std::get<0>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (3,1) simplices.";
EXPECT_THAT(std::get<1>(simplex_types).size(),
Eq(std::get<1>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (2,2) simplices.";
EXPECT_THAT(std::get<2>(simplex_types).size(),
Eq(std::get<2>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (1,3) simplices.";
auto edge_types = classify_edges(universe);
auto tempDT_edge_types = classify_edges(tempDT_ptr);
EXPECT_THAT(edge_types.first.size(), Eq(tempDT_edge_types.first.size()))
<< "Delaunay copy doesn't have the same number of timelike edges.";
EXPECT_THAT(edge_types.second, Eq(tempDT_edge_types.second))
<< "Delaunay copy doesn't have the same number of spacelike edges.";
}
TEST(PachnerMoveTest, MakeA23Move) {
// Make a foliated triangulation
auto universe = std::move(make_triangulation(6400, 17));
auto simplex_types = classify_simplices(universe);
auto edge_types = classify_edges(universe);
auto number_of_vertices_before = universe->number_of_vertices();
auto N3_31_before = std::get<0>(simplex_types).size();
auto N3_22_before = std::get<1>(simplex_types).size();
auto N3_13_before = std::get<2>(simplex_types).size();
auto V2_before = edge_types.first.size();
// Print initial values
std::cout << "Number of vertices before = " << number_of_vertices_before
<< std::endl;
std::cout << "Number of (3,1) simplices before = " << N3_31_before
<< std::endl;
std::cout << "Number of (2,2) simplices before = " << N3_22_before
<< std::endl;
std::cout << "Number of (1,3) simplices before = " << N3_13_before
<< std::endl;
std::cout << "Number of timelike edges before = " << V2_before
<< std::endl;
// Make move using PachnerMove
PachnerMove p(universe, move_type::TWO_THREE, simplex_types, edge_types);
std::cout << "Attempted (2,3) moves = " << std::get<0>(p.attempted_moves_)
<< std::endl;
// Did we remove a (2,2) Cell_handle?
EXPECT_THAT(std::get<1>(p.movable_simplex_types_).size(), Le(N3_22_before-1))
<< "make_23_move didn't remove a (2,2) simplex vector element.";
EXPECT_THAT(std::get<0>(p.movable_simplex_types_).size(), Eq(N3_31_before))
<< "make_23_move removed a (3,1) simplex vector element.";
EXPECT_THAT(std::get<2>(p.movable_simplex_types_).size(), Eq(N3_13_before))
<< "make_23_move removed a (1,3) simplex vector element.";
// Now look at changes
simplex_types = classify_simplices(p.universe_);
auto N3_31_after = std::get<0>(simplex_types).size();
auto N3_22_after = std::get<1>(simplex_types).size();
auto N3_13_after = std::get<2>(simplex_types).size();
// We expect the triangulation to be valid, but not necessarily Delaunay
EXPECT_TRUE(p.universe_->tds().is_valid())
<< "Triangulation is invalid.";
EXPECT_THAT(p.universe_->dimension(), Eq(3))
<< "Triangulation has wrong dimensionality.";
EXPECT_TRUE(fix_timeslices(p.universe_))
<< "Some simplices do not span exactly 1 timeslice.";
EXPECT_THAT(p.universe_->number_of_vertices(), Eq(number_of_vertices_before))
<< "The number of vertices changed.";
EXPECT_THAT(N3_31_after, Eq(N3_31_before))
<< "(3,1) simplices changed.";
EXPECT_THAT(N3_22_after, Eq(N3_22_before+1))
<< "(2,2) simplices did not increase by 1.";
EXPECT_THAT(N3_13_after, Eq(N3_13_before))
<< "(1,3) simplices changed.";
}
<commit_msg>Test copy, move & swap<commit_after>/// Causal Dynamical Triangulations in C++ using CGAL
///
/// Copyright (c) 2016 Adam Getchell
///
/// Checks that the PachnerMove RAII class handles resources properly.
/// @file PachnerMoveTest.cpp
/// @brief Tests for the PachnerMove RAII class
/// @author Adam Getchell
#include <tuple>
#include <vector>
#include <utility>
#include <algorithm>
#include "gmock/gmock.h"
#include "PachnerMove.h"
#include "S3ErgodicMoves.h"
using namespace testing; // NOLINT
class PachnerMoveTest : public Test {
public:
PachnerMoveTest() : universe_(std::move(make_triangulation(6400, 17))),
movable_simplex_types_(classify_simplices(universe_)),
movable_edge_types_(classify_edges(universe_)),
attempted_moves_(std::make_tuple(0, 0, 0, 0, 0)) {
// Print ctor-initialized values
std::cout << "(3,1) simplices: "
<< std::get<0>(movable_simplex_types_).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(movable_simplex_types_).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(movable_simplex_types_).size() << std::endl;
std::cout << "Timelike edges: "
<< movable_edge_types_.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< movable_edge_types_.second << std::endl;
std::cout << "Vertices: "
<< this->universe_->number_of_vertices() << std::endl;
} // Ctor
std::unique_ptr<Delaunay> universe_;
///< Unique pointer to the Delaunay triangulation
move_tuple attempted_moves_;
///< A count of all attempted moves
std::tuple<std::vector<Cell_handle>,
std::vector<Cell_handle>,
std::vector<Cell_handle>> movable_simplex_types_;
///< Movable (3,1), (2,2) and (1,3) simplices.
std::pair<std::vector<Edge_tuple>, unsigned> movable_edge_types_;
///< Movable timelike and spacelike edges.
};
TEST_F(PachnerMoveTest, DeepCopyCtor) {
// Print info on move/copy operation exception safety
std::cout << std::boolalpha
<< "Delaunay alias is copy-assignable? "
<< std::is_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow copy-assignable? "
<< std::is_nothrow_copy_assignable<Delaunay>::value << '\n'
<< "Delaunay alias is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<Delaunay>::value << '\n'
<< "unique_ptr<Delaunay> is nothrow move-assignable? "
<< std::is_nothrow_move_assignable<std::unique_ptr<Delaunay>>::value
<< std::endl;
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe is invalid.";
// Make a copy using Delaunay copy-ctor
auto tempDT = Delaunay(*this->universe_);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Delaunay copy is invalid.";
EXPECT_THAT(this->universe_->number_of_vertices(),
Eq(tempDT_ptr->number_of_vertices()))
<< "Delaunay copy doesn't have the same number of vertices.";
EXPECT_THAT(this->universe_->number_of_finite_edges(),
Eq(tempDT_ptr->number_of_finite_edges()))
<< "Delaunay copy doesn't have the same number of edges.";
EXPECT_THAT(this->universe_->number_of_finite_facets(),
Eq(tempDT_ptr->number_of_finite_facets()))
<< "Delaunay copy doesn't have the same number of facets.";
EXPECT_THAT(this->universe_->number_of_finite_cells(),
Eq(tempDT_ptr->number_of_finite_cells()))
<< "Delaunay copy doesn't have the same number of cells.";
// Calculate copied simplex types
auto tempDT_simplex_types = classify_simplices(tempDT_ptr);
EXPECT_THAT(std::get<0>(this->movable_simplex_types_).size(),
Eq(std::get<0>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (3,1) simplices.";
EXPECT_THAT(std::get<1>(this->movable_simplex_types_).size(),
Eq(std::get<1>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (2,2) simplices.";
EXPECT_THAT(std::get<2>(this->movable_simplex_types_).size(),
Eq(std::get<2>(tempDT_simplex_types).size()))
<< "Delaunay copy doesn't have the same number of (1,3) simplices.";
// Calculate copied edge types
auto tempDT_edge_types = classify_edges(tempDT_ptr);
EXPECT_THAT(this->movable_edge_types_.first.size(),
Eq(tempDT_edge_types.first.size()))
<< "Delaunay copy doesn't have the same number of timelike edges.";
EXPECT_THAT(this->movable_edge_types_.second, Eq(tempDT_edge_types.second))
<< "Delaunay copy doesn't have the same number of spacelike edges.";
}
TEST_F(PachnerMoveTest, MakeA23MoveOnACopy) {
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "Constructed universe_ is invalid.";
// Make a copy using Delaunay copy-ctor
auto tempDT = Delaunay(*this->universe_);
auto tempDT_ptr = std::make_unique<Delaunay>(tempDT);
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Copied universe is invalid.";
auto simplex_types = classify_simplices(tempDT_ptr);
tempDT_ptr = std::move(make_23_move(tempDT_ptr,
simplex_types,
attempted_moves_));
std::cout << "Attempted (2,3) moves = " << std::get<0>(attempted_moves_)
<< std::endl;
EXPECT_TRUE(tempDT_ptr->tds().is_valid())
<< "Copied universe invalid after make_23_move().";
std::swap(this->universe_, tempDT_ptr);
EXPECT_TRUE(this->universe_->tds().is_valid())
<< "universe_ invalid after swap with copied universe.";
// Re-populate with current data
auto new_movable_simplex_types = classify_simplices(this->universe_);
auto new_movable_edge_types = classify_edges(this->universe_);
// Print new values
std::cout << "(3,1) simplices: "
<< std::get<0>(new_movable_simplex_types).size() << std::endl;
std::cout << "(2,2) simplices: "
<< std::get<1>(new_movable_simplex_types).size() << std::endl;
std::cout << "(1,3) simplices: "
<< std::get<2>(new_movable_simplex_types).size() << std::endl;
std::cout << "Timelike edges: "
<< new_movable_edge_types.first.size() << std::endl;
std::cout << "Spacelike edges: "
<< new_movable_edge_types.second << std::endl;
std::cout << "Vertices: "
<< this->universe_->number_of_vertices() << std::endl;
// Did we add a (2,2) Cell_handle?
EXPECT_THAT(std::get<1>(new_movable_simplex_types).size(),
Eq(std::get<1>(movable_simplex_types_).size()+1))
<< "make_23_move didn't add a (2,2) simplex vector element.";
// Did we add a Timelike edge?
EXPECT_THAT(new_movable_edge_types.first.size(),
Eq(movable_edge_types_.first.size()+1))
<< "make_23_move didn't add a timelike edge.";
// // Did we record an attempted move?
// EXPECT_THAT(std::get<0>(attempted_moves) +
// std::get<1>(simplex_types).size(), Eq(N3_22_before))
// << "Attempted (2,3) moves not recorded correctly.";
//
// EXPECT_THAT(std::get<0>(simplex_types).size(), Eq(N3_31_before))
// << "make_23_move removed a (3,1) simplex vector element.";
//
// EXPECT_THAT(std::get<2>(simplex_types).size(), Eq(N3_13_before))
// << "make_23_move removed a (1,3) simplex vector element.";
}
// TEST(PachnerMoveTest, MakeA23Move) {
// // Make a foliated triangulation
// auto universe = std::move(make_triangulation(6400, 17));
// auto simplex_types = classify_simplices(universe);
// auto edge_types = classify_edges(universe);
// auto number_of_vertices_before = universe->number_of_vertices();
// auto N3_31_before = std::get<0>(simplex_types).size();
// auto N3_22_before = std::get<1>(simplex_types).size();
// auto N3_13_before = std::get<2>(simplex_types).size();
// auto V2_before = edge_types.first.size();
//
// // Print initial values
// std::cout << "Number of vertices before = " << number_of_vertices_before
// << std::endl;
// std::cout << "Number of (3,1) simplices before = " << N3_31_before
// << std::endl;
// std::cout << "Number of (2,2) simplices before = " << N3_22_before
// << std::endl;
// std::cout << "Number of (1,3) simplices before = " << N3_13_before
// << std::endl;
// std::cout << "Number of timelike edges before = " << V2_before
// << std::endl;
//
// // Make move using PachnerMove
// PachnerMove p(universe, move_type::TWO_THREE, simplex_types, edge_types);
//
// std::cout << "Attempted (2,3) moves = " << std::get<0>(p.attempted_moves_)
// << std::endl;
//
// // Did we remove a (2,2) Cell_handle?
// EXPECT_THAT(std::get<1>(p.movable_simplex_types_).size(), Le(N3_22_before-1))
// << "make_23_move didn't remove a (2,2) simplex vector element.";
//
// EXPECT_THAT(std::get<0>(p.movable_simplex_types_).size(), Eq(N3_31_before))
// << "make_23_move removed a (3,1) simplex vector element.";
//
// EXPECT_THAT(std::get<2>(p.movable_simplex_types_).size(), Eq(N3_13_before))
// << "make_23_move removed a (1,3) simplex vector element.";
//
// // Now look at changes
// simplex_types = classify_simplices(p.universe_);
// auto N3_31_after = std::get<0>(simplex_types).size();
// auto N3_22_after = std::get<1>(simplex_types).size();
// auto N3_13_after = std::get<2>(simplex_types).size();
//
// // We expect the triangulation to be valid, but not necessarily Delaunay
// EXPECT_TRUE(p.universe_->tds().is_valid())
// << "Triangulation is invalid.";
//
// EXPECT_THAT(p.universe_->dimension(), Eq(3))
// << "Triangulation has wrong dimensionality.";
//
// EXPECT_TRUE(fix_timeslices(p.universe_))
// << "Some simplices do not span exactly 1 timeslice.";
//
// EXPECT_THAT(p.universe_->number_of_vertices(), Eq(number_of_vertices_before))
// << "The number of vertices changed.";
//
// EXPECT_THAT(N3_31_after, Eq(N3_31_before))
// << "(3,1) simplices changed.";
//
// EXPECT_THAT(N3_22_after, Eq(N3_22_before+1))
// << "(2,2) simplices did not increase by 1.";
//
// EXPECT_THAT(N3_13_after, Eq(N3_13_before))
// << "(1,3) simplices changed.";
// }
<|endoftext|>
|
<commit_before>//===---------- llvm/unittest/Support/Casting.cpp - Casting tests --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Debug.h"
//#define DEBUG_CAST_OPERATORS
#include "llvm/Support/Casting.h"
#include "gtest/gtest.h"
#include <cstdlib>
namespace llvm {
// set up two example classes
// with conversion facility
//
struct bar {
bar() {}
//struct foo *baz();
private:
bar(const bar &);
};
struct foo {
void ext() const;
/* static bool classof(const bar *X) {
cerr << "Classof: " << X << "\n";
return true;
}*/
};
template <> struct isa_impl<foo,bar> {
static inline bool doit(const bar &Val) {
dbgs() << "Classof: " << &Val << "\n";
return true;
}
};
/*foo *bar::baz() {
return cast<foo>(this);
}*/
bar *fub();
} // End llvm namespace
using namespace llvm;
namespace {
const foo *null_foo = NULL;
extern bar &B1;
extern const bar *B2;
// test various configurations of const
const bar &B3 = B1;
const bar *const B4 = B2;
TEST(CastingTest, isa) {
EXPECT_TRUE(isa<foo>(B1));
EXPECT_TRUE(isa<foo>(B2));
EXPECT_TRUE(isa<foo>(B3));
EXPECT_TRUE(isa<foo>(B4));
}
TEST(CastingTest, cast) {
foo &F1 = cast<foo>(B1);
EXPECT_NE(&F1, null_foo);
const foo *F3 = cast<foo>(B2);
EXPECT_NE(F3, null_foo);
const foo *F4 = cast<foo>(B2);
EXPECT_NE(F4, null_foo);
const foo &F5 = cast<foo>(B3);
EXPECT_NE(&F5, null_foo);
const foo *F6 = cast<foo>(B4);
EXPECT_NE(F6, null_foo);
foo *F7 = cast<foo>(fub());
EXPECT_EQ(F7, null_foo);
/* foo *F8 = B1.baz();
EXPECT_NE(F8, null_foo);*/
}
TEST(CastingTest, cast_or_null) {
const foo *F11 = cast_or_null<foo>(B2);
EXPECT_NE(F11, null_foo);
const foo *F12 = cast_or_null<foo>(B2);
EXPECT_NE(F12, null_foo);
const foo *F13 = cast_or_null<foo>(B4);
EXPECT_NE(F13, null_foo);
const foo *F14 = cast_or_null<foo>(fub()); // Shouldn't print.
EXPECT_EQ(F14, null_foo);
}
// These lines are errors...
//foo *F20 = cast<foo>(B2); // Yields const foo*
//foo &F21 = cast<foo>(B3); // Yields const foo&
//foo *F22 = cast<foo>(B4); // Yields const foo*
//foo &F23 = cast_or_null<foo>(B1);
//const foo &F24 = cast_or_null<foo>(B3);
bar B;
bar &B1 = B;
const bar *B2 = &B;
} // anonymous namespace
bar *llvm::fub() { return 0; }
<commit_msg>tidy up<commit_after>//===---------- llvm/unittest/Support/Casting.cpp - Casting tests ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"
#include <cstdlib>
namespace llvm {
// set up two example classes
// with conversion facility
//
struct bar {
bar() {}
//struct foo *baz();
private:
bar(const bar &);
};
struct foo {
void ext() const;
/* static bool classof(const bar *X) {
cerr << "Classof: " << X << "\n";
return true;
}*/
};
template <> struct isa_impl<foo,bar> {
static inline bool doit(const bar &Val) {
dbgs() << "Classof: " << &Val << "\n";
return true;
}
};
/*foo *bar::baz() {
return cast<foo>(this);
}*/
bar *fub();
} // End llvm namespace
using namespace llvm;
namespace {
const foo *null_foo = NULL;
extern bar &B1;
extern const bar *B2;
// test various configurations of const
const bar &B3 = B1;
const bar *const B4 = B2;
TEST(CastingTest, isa) {
EXPECT_TRUE(isa<foo>(B1));
EXPECT_TRUE(isa<foo>(B2));
EXPECT_TRUE(isa<foo>(B3));
EXPECT_TRUE(isa<foo>(B4));
}
TEST(CastingTest, cast) {
foo &F1 = cast<foo>(B1);
EXPECT_NE(&F1, null_foo);
const foo *F3 = cast<foo>(B2);
EXPECT_NE(F3, null_foo);
const foo *F4 = cast<foo>(B2);
EXPECT_NE(F4, null_foo);
const foo &F5 = cast<foo>(B3);
EXPECT_NE(&F5, null_foo);
const foo *F6 = cast<foo>(B4);
EXPECT_NE(F6, null_foo);
foo *F7 = cast<foo>(fub());
EXPECT_EQ(F7, null_foo);
/* foo *F8 = B1.baz();
EXPECT_NE(F8, null_foo);*/
}
TEST(CastingTest, cast_or_null) {
const foo *F11 = cast_or_null<foo>(B2);
EXPECT_NE(F11, null_foo);
const foo *F12 = cast_or_null<foo>(B2);
EXPECT_NE(F12, null_foo);
const foo *F13 = cast_or_null<foo>(B4);
EXPECT_NE(F13, null_foo);
const foo *F14 = cast_or_null<foo>(fub()); // Shouldn't print.
EXPECT_EQ(F14, null_foo);
}
// These lines are errors...
//foo *F20 = cast<foo>(B2); // Yields const foo*
//foo &F21 = cast<foo>(B3); // Yields const foo&
//foo *F22 = cast<foo>(B4); // Yields const foo*
//foo &F23 = cast_or_null<foo>(B1);
//const foo &F24 = cast_or_null<foo>(B3);
bar B;
bar &B1 = B;
const bar *B2 = &B;
} // anonymous namespace
bar *llvm::fub() { return 0; }
<|endoftext|>
|
<commit_before>/* FREEVERB - a reverberator
This reverb instrument is based on Freeverb, by Jezar
(http://www.dreampoint.co.uk/~jzracc/freeverb.htm).
p0 = output start time
p1 = input start time
p2 = input duration
p3 = amplitude multiplier
p4 = room size (0-1.07143 ... don't ask)
p5 = pre-delay time (time between dry signal and onset of reverb)
p6 = ring-down duration
p7 = damp (0-100%)
p8 = dry signal level (0-100%)
p9 = wet signal level (0-100%)
p10 = stereo width of reverb (0-100%)
p3 (amplitude), p4 (room size), p5 (pre-delay), p7 (damp), p8 (dry),
p9 (wet) and p10 (stereo width) can receive dynamic updates from a table
or real-time control source.
If an old-style gen table 1 is present, its values will be multiplied
by the p3 amplitude multiplier, even if the latter is dynamic.
The amplitude multiplier is applied to the input sound *before*
it enters the reverberator.
If you enter a room size greater than the maximum, you'll get the
maximum amount -- which is probably an infinite reverb time.
Input can be mono or stereo; output can be mono or stereo.
Be careful with the dry and wet levels -- it's easy to get extreme
clipping!
John Gibson <johngibson@virginia.edu>, 2 Feb 2001; rev for v4, 7/11/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <math.h>
#include <Instrument.h>
#include "FREEVERB.h"
#include <rt.h>
#include <rtdefs.h>
FREEVERB :: FREEVERB() : Instrument()
{
in = NULL;
branch = 0;
warn_roomsize = true;
warn_predelay = true;
warn_damp = true;
warn_dry = true;
warn_wet = true;
warn_width = true;
}
FREEVERB :: ~FREEVERB()
{
delete [] in;
delete rvb;
}
int FREEVERB :: init(double p[], int n_args)
{
float outskip = p[0];
float inskip = p[1];
float dur = p[2];
roomsize = p[4];
predelay_time = p[5];
ringdur = p[6];
damp = p[7];
dry = p[8];
wet = p[9];
width = p[10];
// Keep reverb comb feedback <= 1.0
max_roomsize = (1.0 - offsetroom) / scaleroom;
if (roomsize < 0.0)
return die("FREEVERB", "Room size must be between 0 and %g.",
max_roomsize);
if (roomsize > max_roomsize) {
roomsize = max_roomsize;
advise("FREEVERB", "Room size cannot be greater than %g. Adjusting...",
max_roomsize);
}
int predelay_samps = (int) ((predelay_time * SR) + 0.5);
if (predelay_samps > max_predelay_samps)
return die("FREEVERB", "Pre-delay must be between 0 and %g seconds.",
(float) max_predelay_samps / SR);
if (damp < 0.0 || damp > 100.0)
return die("FREEVERB", "Damp must be between 0 and 100%%.");
if (dry < 0.0 || dry > 100.0)
return die("FREEVERB", "Dry signal level must be between 0 and 100%%.");
if (wet < 0.0 || wet > 100.0)
return die("FREEVERB", "Wet signal level must be between 0 and 100%%.");
if (width < 0.0 || width > 100.0)
return die("FREEVERB", "Width must be between 0 and 100%%.");
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
if (rtsetoutput(outskip, dur + ringdur, this) == -1)
return DONT_SCHEDULE;
insamps = (int) (dur * SR);
if (inputChannels() > 2)
return die("FREEVERB", "Can't have more than 2 input channels.");
if (outputChannels() > 2)
return die("FREEVERB", "Can't have more than 2 output channels.");
rvb = new revmodel();
rvb->setroomsize(roomsize);
rvb->setpredelay(predelay_samps);
rvb->setdamp(damp * 0.01);
rvb->setdry(dry * 0.01);
rvb->setwet(wet * 0.01);
rvb->setwidth(width * 0.01);
amparray = floc(1);
if (amparray) {
int lenamp = fsize(1);
tableset(SR, dur, lenamp, amptabs);
}
return nSamps();
}
int FREEVERB :: configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
inline void FREEVERB :: updateRvb(double p[])
{
if (p[4] != roomsize) {
roomsize = p[4];
if (roomsize < 0.0 || roomsize > max_roomsize) {
if (warn_roomsize) {
warn("FREEVERB", "Room size must be between 0 and %g. Adjusting...",
max_roomsize);
warn_roomsize = false;
}
roomsize = roomsize < 0.0 ? 0.0 : max_roomsize;
}
rvb->setroomsize(roomsize);
}
if (p[5] != predelay_time) {
predelay_time = p[5];
int predelay_samps = (int) ((predelay_time * SR) + 0.5);
if (predelay_samps > max_predelay_samps) {
if (warn_predelay) {
warn("FREEVERB", "Pre-delay must be between 0 and %g seconds. "
"Adjusting...", (float) max_predelay_samps / SR);
warn_predelay = false;
}
predelay_samps = max_predelay_samps;
}
rvb->setpredelay(predelay_samps);
}
if (p[7] != damp) {
damp = p[7];
if (damp < 0.0 || damp > 100.0) {
if (warn_damp) {
warn("FREEVERB", "Damp must be between 0 and 100%%. Adjusting...");
warn_damp = false;
}
damp = damp < 0.0 ? 0.0 : 100.0;
}
rvb->setdamp(damp * 0.01);
}
if (p[8] != dry) {
dry = p[8];
if (dry < 0.0 || dry > 100.0) {
if (warn_dry) {
warn("FREEVERB", "Dry signal level must be between 0 and 100%%. "
"Adjusting...");
warn_dry = false;
}
dry = dry < 0.0 ? 0.0 : 100.0;
}
rvb->setdry(dry * 0.01);
}
if (p[9] != wet) {
wet = p[9];
if (wet < 0.0 || wet > 100.0) {
if (warn_wet) {
warn("FREEVERB", "Wet signal level must be between 0 and 100%%. "
"Adjusting...");
warn_wet = false;
}
wet = wet < 0.0 ? 0.0 : 100.0;
}
rvb->setwet(wet * 0.01);
}
if (p[10] != width) {
width = p[10];
if (width < 0.0 || width > 100.0) {
if (warn_width) {
warn("FREEVERB", "Width must be between 0 and 100%%. Adjusting...");
warn_width = false;
}
width = width < 0.0 ? 0.0 : 100.0;
}
rvb->setwidth(width * 0.01);
}
// printf("rmsz=%f, predel=%f, damp=%f, dry=%f, wet=%f, width=%f\n", roomsize, predelay_time, damp, dry, wet, width);
}
int FREEVERB :: run()
{
float *inL, *inR, *outL, *outR;
inL = in;
inR = inputChannels() > 1 ? in + 1 : in;
outL = outbuf;
outR = outputChannels() > 1 ? outbuf + 1 : outbuf;
int samps = framesToRun() * inputChannels();
if (currentFrame() < insamps)
rtgetin(in, this, samps);
// Scale input signal by amplitude multiplier and setline curve.
for (int i = 0; i < samps; i += inputChannels()) {
if (--branch <= 0) {
double p[11];
update(p, 11, kRoomSize | kPreDelay | kDamp | kDry | kWet | kWidth);
if (currentFrame() < insamps) { // amp is pre-effect
amp = update(3, insamps);
if (amparray)
amp *= tablei(currentFrame(), amparray, amptabs);
}
updateRvb(p);
branch = getSkip();
}
if (currentFrame() < insamps) { // still taking input from file
in[i] *= amp;
if (inputChannels() == 2)
in[i + 1] *= amp;
}
else { // in ringdown phase
in[i] = 0.0;
if (inputChannels() == 2)
in[i + 1] = 0.0;
}
increment();
}
// Hand off to Freeverb to do the actual work.
rvb->processreplace(inL, inR, outL, outR, chunksamps, inputChannels(),
outputChannels());
return framesToRun();
}
Instrument *makeFREEVERB()
{
FREEVERB *inst;
inst = new FREEVERB();
inst->set_bus_config("FREEVERB");
return inst;
}
void rtprofile()
{
RT_INTRO("FREEVERB", makeFREEVERB);
}
<commit_msg>Removed all direct uses of 'chunksamps' member from derived Instrument classes.<commit_after>/* FREEVERB - a reverberator
This reverb instrument is based on Freeverb, by Jezar
(http://www.dreampoint.co.uk/~jzracc/freeverb.htm).
p0 = output start time
p1 = input start time
p2 = input duration
p3 = amplitude multiplier
p4 = room size (0-1.07143 ... don't ask)
p5 = pre-delay time (time between dry signal and onset of reverb)
p6 = ring-down duration
p7 = damp (0-100%)
p8 = dry signal level (0-100%)
p9 = wet signal level (0-100%)
p10 = stereo width of reverb (0-100%)
p3 (amplitude), p4 (room size), p5 (pre-delay), p7 (damp), p8 (dry),
p9 (wet) and p10 (stereo width) can receive dynamic updates from a table
or real-time control source.
If an old-style gen table 1 is present, its values will be multiplied
by the p3 amplitude multiplier, even if the latter is dynamic.
The amplitude multiplier is applied to the input sound *before*
it enters the reverberator.
If you enter a room size greater than the maximum, you'll get the
maximum amount -- which is probably an infinite reverb time.
Input can be mono or stereo; output can be mono or stereo.
Be careful with the dry and wet levels -- it's easy to get extreme
clipping!
John Gibson <johngibson@virginia.edu>, 2 Feb 2001; rev for v4, 7/11/04
*/
#include <stdio.h>
#include <stdlib.h>
#include <ugens.h>
#include <math.h>
#include <Instrument.h>
#include "FREEVERB.h"
#include <rt.h>
#include <rtdefs.h>
FREEVERB :: FREEVERB() : Instrument()
{
in = NULL;
branch = 0;
warn_roomsize = true;
warn_predelay = true;
warn_damp = true;
warn_dry = true;
warn_wet = true;
warn_width = true;
}
FREEVERB :: ~FREEVERB()
{
delete [] in;
delete rvb;
}
int FREEVERB :: init(double p[], int n_args)
{
float outskip = p[0];
float inskip = p[1];
float dur = p[2];
roomsize = p[4];
predelay_time = p[5];
ringdur = p[6];
damp = p[7];
dry = p[8];
wet = p[9];
width = p[10];
// Keep reverb comb feedback <= 1.0
max_roomsize = (1.0 - offsetroom) / scaleroom;
if (roomsize < 0.0)
return die("FREEVERB", "Room size must be between 0 and %g.",
max_roomsize);
if (roomsize > max_roomsize) {
roomsize = max_roomsize;
advise("FREEVERB", "Room size cannot be greater than %g. Adjusting...",
max_roomsize);
}
int predelay_samps = (int) ((predelay_time * SR) + 0.5);
if (predelay_samps > max_predelay_samps)
return die("FREEVERB", "Pre-delay must be between 0 and %g seconds.",
(float) max_predelay_samps / SR);
if (damp < 0.0 || damp > 100.0)
return die("FREEVERB", "Damp must be between 0 and 100%%.");
if (dry < 0.0 || dry > 100.0)
return die("FREEVERB", "Dry signal level must be between 0 and 100%%.");
if (wet < 0.0 || wet > 100.0)
return die("FREEVERB", "Wet signal level must be between 0 and 100%%.");
if (width < 0.0 || width > 100.0)
return die("FREEVERB", "Width must be between 0 and 100%%.");
if (rtsetinput(inskip, this) == -1)
return DONT_SCHEDULE;
if (rtsetoutput(outskip, dur + ringdur, this) == -1)
return DONT_SCHEDULE;
insamps = (int) (dur * SR);
if (inputChannels() > 2)
return die("FREEVERB", "Can't have more than 2 input channels.");
if (outputChannels() > 2)
return die("FREEVERB", "Can't have more than 2 output channels.");
rvb = new revmodel();
rvb->setroomsize(roomsize);
rvb->setpredelay(predelay_samps);
rvb->setdamp(damp * 0.01);
rvb->setdry(dry * 0.01);
rvb->setwet(wet * 0.01);
rvb->setwidth(width * 0.01);
amparray = floc(1);
if (amparray) {
int lenamp = fsize(1);
tableset(SR, dur, lenamp, amptabs);
}
return nSamps();
}
int FREEVERB :: configure()
{
in = new float [RTBUFSAMPS * inputChannels()];
return in ? 0 : -1;
}
inline void FREEVERB :: updateRvb(double p[])
{
if (p[4] != roomsize) {
roomsize = p[4];
if (roomsize < 0.0 || roomsize > max_roomsize) {
if (warn_roomsize) {
warn("FREEVERB", "Room size must be between 0 and %g. Adjusting...",
max_roomsize);
warn_roomsize = false;
}
roomsize = roomsize < 0.0 ? 0.0 : max_roomsize;
}
rvb->setroomsize(roomsize);
}
if (p[5] != predelay_time) {
predelay_time = p[5];
int predelay_samps = (int) ((predelay_time * SR) + 0.5);
if (predelay_samps > max_predelay_samps) {
if (warn_predelay) {
warn("FREEVERB", "Pre-delay must be between 0 and %g seconds. "
"Adjusting...", (float) max_predelay_samps / SR);
warn_predelay = false;
}
predelay_samps = max_predelay_samps;
}
rvb->setpredelay(predelay_samps);
}
if (p[7] != damp) {
damp = p[7];
if (damp < 0.0 || damp > 100.0) {
if (warn_damp) {
warn("FREEVERB", "Damp must be between 0 and 100%%. Adjusting...");
warn_damp = false;
}
damp = damp < 0.0 ? 0.0 : 100.0;
}
rvb->setdamp(damp * 0.01);
}
if (p[8] != dry) {
dry = p[8];
if (dry < 0.0 || dry > 100.0) {
if (warn_dry) {
warn("FREEVERB", "Dry signal level must be between 0 and 100%%. "
"Adjusting...");
warn_dry = false;
}
dry = dry < 0.0 ? 0.0 : 100.0;
}
rvb->setdry(dry * 0.01);
}
if (p[9] != wet) {
wet = p[9];
if (wet < 0.0 || wet > 100.0) {
if (warn_wet) {
warn("FREEVERB", "Wet signal level must be between 0 and 100%%. "
"Adjusting...");
warn_wet = false;
}
wet = wet < 0.0 ? 0.0 : 100.0;
}
rvb->setwet(wet * 0.01);
}
if (p[10] != width) {
width = p[10];
if (width < 0.0 || width > 100.0) {
if (warn_width) {
warn("FREEVERB", "Width must be between 0 and 100%%. Adjusting...");
warn_width = false;
}
width = width < 0.0 ? 0.0 : 100.0;
}
rvb->setwidth(width * 0.01);
}
// printf("rmsz=%f, predel=%f, damp=%f, dry=%f, wet=%f, width=%f\n", roomsize, predelay_time, damp, dry, wet, width);
}
int FREEVERB :: run()
{
float *inL, *inR, *outL, *outR;
inL = in;
inR = inputChannels() > 1 ? in + 1 : in;
outL = outbuf;
outR = outputChannels() > 1 ? outbuf + 1 : outbuf;
int samps = framesToRun() * inputChannels();
if (currentFrame() < insamps)
rtgetin(in, this, samps);
// Scale input signal by amplitude multiplier and setline curve.
for (int i = 0; i < samps; i += inputChannels()) {
if (--branch <= 0) {
double p[11];
update(p, 11, kRoomSize | kPreDelay | kDamp | kDry | kWet | kWidth);
if (currentFrame() < insamps) { // amp is pre-effect
amp = update(3, insamps);
if (amparray)
amp *= tablei(currentFrame(), amparray, amptabs);
}
updateRvb(p);
branch = getSkip();
}
if (currentFrame() < insamps) { // still taking input from file
in[i] *= amp;
if (inputChannels() == 2)
in[i + 1] *= amp;
}
else { // in ringdown phase
in[i] = 0.0;
if (inputChannels() == 2)
in[i + 1] = 0.0;
}
increment();
}
// Hand off to Freeverb to do the actual work.
rvb->processreplace(inL, inR, outL, outR, framesToRun(), inputChannels(),
outputChannels());
return framesToRun();
}
Instrument *makeFREEVERB()
{
FREEVERB *inst;
inst = new FREEVERB();
inst->set_bus_config("FREEVERB");
return inst;
}
void rtprofile()
{
RT_INTRO("FREEVERB", makeFREEVERB);
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#include "config.h"
#include <memory>
#include <dune/stuff/common/memory.hh>
#include <dune/hdd/playground/linearelliptic/discreteproblem.hh>
#include <dune/hdd/playground/linearelliptic/discretizations/swipdg.hh>
template< class GridImp >
class LinearellipticExampleSWIPDG
{
public:
typedef GridImp GridType;
typedef Dune::HDD::LinearElliptic::DiscreteProblem< GridType > DiscreteProblemType;
typedef typename DiscreteProblemType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = DiscreteProblemType::dimRange;
typedef Dune::HDD::LinearElliptic::Discretizations::SWIPDG< GridType, Dune::Stuff::Grid::ChooseLayer::leaf,
RangeFieldType, dimRange, 1 > DiscretizationType;
static std::string static_id()
{
return "linearelliptic.swipdg";
}
static void write_config_file(const std::string filename = static_id() + ".cfg")
{
DiscreteProblemType::write_config(filename, static_id());
}
void initialize(const std::vector< std::string > arguments)
{
using namespace Dune;
if (!discrete_problem_) {
discrete_problem_ = Stuff::Common::make_unique< DiscreteProblemType >(static_id(), arguments);
const bool debug_logging = discrete_problem_->debug_logging();
auto& info = DSC_LOG_INFO;
auto& debug = DSC_LOG_DEBUG;
discretization_ = Stuff::Common::make_unique< DiscretizationType >(discrete_problem_->grid_provider(),
discrete_problem_->boundary_info(),
discrete_problem_->problem());
info << "initializing discretization";
if (debug_logging)
info << ":" << std::endl;
else
info << "... " << std::flush;
Dune::Timer timer;
discretization_->init(debug, " ");
if (!debug_logging)
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} else
DSC_LOG_INFO << "initialize has already been called" << std::endl;
} // ... initialize(...)
const DiscreteProblemType& discrete_problem() const
{
return *discrete_problem_;
}
const DiscretizationType& discretization() const
{
return *discretization_;
}
DiscretizationType* discretization_and_return_ptr() const
{
return new DiscretizationType(*discretization_);
}
private:
std::unique_ptr< DiscreteProblemType > discrete_problem_;
std::unique_ptr< DiscretizationType > discretization_;
}; // class LinearellipticExampleSWIPDG
namespace Dune {
// forward grid declaratios
template< int dim, int dimworld, typename _ctype >
class SGrid;
template< int dim >
class YaspGrid;
} // namespace Dune
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 1, 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 2, 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 3, 3 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 3 > >;
#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
<commit_msg>[examples.linearelliptic.swipdg] removed config.h include<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#define DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
#include <memory>
#include <dune/stuff/common/memory.hh>
#include <dune/hdd/playground/linearelliptic/discreteproblem.hh>
#include <dune/hdd/playground/linearelliptic/discretizations/swipdg.hh>
template< class GridImp >
class LinearellipticExampleSWIPDG
{
public:
typedef GridImp GridType;
typedef Dune::HDD::LinearElliptic::DiscreteProblem< GridType > DiscreteProblemType;
typedef typename DiscreteProblemType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = DiscreteProblemType::dimRange;
typedef Dune::HDD::LinearElliptic::Discretizations::SWIPDG< GridType, Dune::Stuff::Grid::ChooseLayer::leaf,
RangeFieldType, dimRange, 1 > DiscretizationType;
static std::string static_id()
{
return "linearelliptic.swipdg";
}
static void write_config_file(const std::string filename = static_id() + ".cfg")
{
DiscreteProblemType::write_config(filename, static_id());
}
void initialize(const std::vector< std::string > arguments)
{
using namespace Dune;
if (!discrete_problem_) {
discrete_problem_ = Stuff::Common::make_unique< DiscreteProblemType >(static_id(), arguments);
const bool debug_logging = discrete_problem_->debug_logging();
auto& info = DSC_LOG_INFO;
auto& debug = DSC_LOG_DEBUG;
discretization_ = Stuff::Common::make_unique< DiscretizationType >(discrete_problem_->grid_provider(),
discrete_problem_->boundary_info(),
discrete_problem_->problem());
info << "initializing discretization";
if (debug_logging)
info << ":" << std::endl;
else
info << "... " << std::flush;
Dune::Timer timer;
discretization_->init(debug, " ");
if (!debug_logging)
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} else
DSC_LOG_INFO << "initialize has already been called" << std::endl;
} // ... initialize(...)
const DiscreteProblemType& discrete_problem() const
{
return *discrete_problem_;
}
const DiscretizationType& discretization() const
{
return *discretization_;
}
DiscretizationType* discretization_and_return_ptr() const
{
return new DiscretizationType(*discretization_);
}
private:
std::unique_ptr< DiscreteProblemType > discrete_problem_;
std::unique_ptr< DiscretizationType > discretization_;
}; // class LinearellipticExampleSWIPDG
namespace Dune {
// forward grid declaratios
template< int dim, int dimworld, typename _ctype >
class SGrid;
template< int dim >
class YaspGrid;
} // namespace Dune
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 1, 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 2, 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::SGrid< 3, 3 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 1 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 2 > >;
extern template class LinearellipticExampleSWIPDG< Dune::YaspGrid< 3 > >;
#endif // DUNE_HDD_EXAMPLES_LINEARELLIPTIC_SWIPDG_HH
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Code contributed to the webinos project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2012 Torsec -Computer and network security group-
* Politecnico di Torino
*
******************************************************************************/
#include "AuthorizationsSet.h"
#include "../../debug.h"
string ontology_vector[PURPOSES_NUMBER] = {
"http://www.w3.org/2002/01/P3Pv1/current",
"http://www.w3.org/2002/01/P3Pv1/admin",
"http://www.w3.org/2002/01/P3Pv1/develop",
"http://www.w3.org/2002/01/P3Pv1/tailoring",
"http://www.w3.org/2002/01/P3Pv1/pseudo-analysis",
"http://www.w3.org/2002/01/P3Pv1/pseudo-decision",
"http://www.w3.org/2002/01/P3Pv1/individual-analysis",
"http://www.w3.org/2002/01/P3Pv1/individual-decision",
"http://www.w3.org/2002/01/P3Pv1/contact",
"http://www.w3.org/2002/01/P3Pv1/historical",
"http://www.w3.org/2002/01/P3Pv1/telemarketing",
"http://www.w3.org/2002/01/P3Pv11/account",
"http://www.w3.org/2002/01/P3Pv11/arts",
"http://www.w3.org/2002/01/P3Pv11/browsing",
"http://www.w3.org/2002/01/P3Pv11/charity",
"http://www.w3.org/2002/01/P3Pv11/communicate",
"http://www.w3.org/2002/01/P3Pv11/custom",
"http://www.w3.org/2002/01/P3Pv11/delivery",
"http://www.w3.org/2002/01/P3Pv11/downloads",
"http://www.w3.org/2002/01/P3Pv11/education",
"http://www.w3.org/2002/01/P3Pv11/feedback",
"http://www.w3.org/2002/01/P3Pv11/finmgt",
"http://www.w3.org/2002/01/P3Pv11/gambling",
"http://www.w3.org/2002/01/P3Pv11/gaming",
"http://www.w3.org/2002/01/P3Pv11/government",
"http://www.w3.org/2002/01/P3Pv11/health",
"http://www.w3.org/2002/01/P3Pv11/login",
"http://www.w3.org/2002/01/P3Pv11/marketing",
"http://www.w3.org/2002/01/P3Pv11/news",
"http://www.w3.org/2002/01/P3Pv11/payment",
"http://www.w3.org/2002/01/P3Pv11/sales",
"http://www.w3.org/2002/01/P3Pv11/search",
"http://www.w3.org/2002/01/P3Pv11/state",
"http://www.w3.org/2002/01/P3Pv11/surveys",
"http://www.primelife.eu/purposes/unspecified"
};
AuthorizationsSet::AuthorizationsSet(TiXmlElement* authorizationsset){
// AuthzUseForPurpose Tags
for(TiXmlElement * child = (TiXmlElement*)authorizationsset->FirstChild("AuthzUseForPurpose"); child;
child = (TiXmlElement*)child->NextSibling("AuthzUseForPurpose")) {
LOGD("AuthorizationsSet constructor, AuthzUseForPurpose %s found", ((TiXmlElement*)child->FirstChild("Purpose"))->GetText());
authzuseforpurpose.push_back(((TiXmlElement*)child->FirstChild("Purpose"))->GetText());
}
}
AuthorizationsSet::~AuthorizationsSet(){
}
bool AuthorizationsSet::evaluate(Request * req){
LOGD("Evaluating AuthorizationsSet");
bool purpose_satisfied[PURPOSES_NUMBER];
vector<bool> purpose = req->getPurposeAttrs();
unsigned int i = 0;
for(vector<bool>::iterator it = purpose.begin(); it!= purpose.end(); it++){
// Purpose requested
if (*it == true){
purpose_satisfied[i] = false;
LOGD("AuthorizationsSet: purpose %d is true", i);
for(unsigned int j=0; j<authzuseforpurpose.size(); j++){
LOGD("AuthorizationsSet: checking authzuseforpurpose %d, %s", j, authzuseforpurpose[j].c_str());
if (ontology_vector[i].compare(authzuseforpurpose[j]) == 0){
// Purpose requested and satisfied
purpose_satisfied[i] = true;
break;
}
}
}
// Purpose not requested
else {
LOGD("AuthorizationsSet: purpose %d is false", i);
purpose_satisfied[i] = true;
}
i++;
}
for (i=0; i < PURPOSES_NUMBER; i++){
if (purpose_satisfied[i] == false)
// A purpose is not satisfied
return false;
}
// All purposes are satisfied
return true;
}
<commit_msg>Fixed AuthzUseForPurpose parsing<commit_after>/*******************************************************************************
* Code contributed to the webinos project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2012 Torsec -Computer and network security group-
* Politecnico di Torino
*
******************************************************************************/
#include "AuthorizationsSet.h"
#include "../../debug.h"
string ontology_vector[PURPOSES_NUMBER] = {
"http://www.w3.org/2002/01/P3Pv1/current",
"http://www.w3.org/2002/01/P3Pv1/admin",
"http://www.w3.org/2002/01/P3Pv1/develop",
"http://www.w3.org/2002/01/P3Pv1/tailoring",
"http://www.w3.org/2002/01/P3Pv1/pseudo-analysis",
"http://www.w3.org/2002/01/P3Pv1/pseudo-decision",
"http://www.w3.org/2002/01/P3Pv1/individual-analysis",
"http://www.w3.org/2002/01/P3Pv1/individual-decision",
"http://www.w3.org/2002/01/P3Pv1/contact",
"http://www.w3.org/2002/01/P3Pv1/historical",
"http://www.w3.org/2002/01/P3Pv1/telemarketing",
"http://www.w3.org/2002/01/P3Pv11/account",
"http://www.w3.org/2002/01/P3Pv11/arts",
"http://www.w3.org/2002/01/P3Pv11/browsing",
"http://www.w3.org/2002/01/P3Pv11/charity",
"http://www.w3.org/2002/01/P3Pv11/communicate",
"http://www.w3.org/2002/01/P3Pv11/custom",
"http://www.w3.org/2002/01/P3Pv11/delivery",
"http://www.w3.org/2002/01/P3Pv11/downloads",
"http://www.w3.org/2002/01/P3Pv11/education",
"http://www.w3.org/2002/01/P3Pv11/feedback",
"http://www.w3.org/2002/01/P3Pv11/finmgt",
"http://www.w3.org/2002/01/P3Pv11/gambling",
"http://www.w3.org/2002/01/P3Pv11/gaming",
"http://www.w3.org/2002/01/P3Pv11/government",
"http://www.w3.org/2002/01/P3Pv11/health",
"http://www.w3.org/2002/01/P3Pv11/login",
"http://www.w3.org/2002/01/P3Pv11/marketing",
"http://www.w3.org/2002/01/P3Pv11/news",
"http://www.w3.org/2002/01/P3Pv11/payment",
"http://www.w3.org/2002/01/P3Pv11/sales",
"http://www.w3.org/2002/01/P3Pv11/search",
"http://www.w3.org/2002/01/P3Pv11/state",
"http://www.w3.org/2002/01/P3Pv11/surveys",
"http://www.primelife.eu/purposes/unspecified"
};
AuthorizationsSet::AuthorizationsSet(TiXmlElement* authorizationsset){
TiXmlElement * child;
// AuthzUseForPurpose Tag
if (authorizationsset->FirstChild("AuthzUseForPurpose")) {
LOGD("AuthorizationsSet constructor, AuthzUseForPurpose found");
child = (TiXmlElement*)authorizationsset->FirstChild("AuthzUseForPurpose");
for(child = (TiXmlElement*)child->FirstChild("Purpose"); child;
child = (TiXmlElement*)child->NextSibling("Purpose")) {
LOGD("Purpose %s found", child->GetText());
authzuseforpurpose.push_back(child->GetText());
}
}
else{
LOGD("AuthorizationsSet constructor, AuthzUseForPurpose not found");
}
}
AuthorizationsSet::~AuthorizationsSet(){
}
bool AuthorizationsSet::evaluate(Request * req){
LOGD("Evaluating AuthorizationsSet");
bool purpose_satisfied[PURPOSES_NUMBER];
vector<bool> purpose = req->getPurposeAttrs();
unsigned int i = 0;
for(vector<bool>::iterator it = purpose.begin(); it!= purpose.end(); it++){
// Purpose requested
if (*it == true){
purpose_satisfied[i] = false;
LOGD("AuthorizationsSet: purpose %d is true", i);
for(unsigned int j=0; j<authzuseforpurpose.size(); j++){
LOGD("AuthorizationsSet: checking authzuseforpurpose %d, %s", j, authzuseforpurpose[j].c_str());
if (ontology_vector[i].compare(authzuseforpurpose[j]) == 0){
// Purpose requested and satisfied
purpose_satisfied[i] = true;
break;
}
}
}
// Purpose not requested
else {
LOGD("AuthorizationsSet: purpose %d is false", i);
purpose_satisfied[i] = true;
}
i++;
}
for (i=0; i < PURPOSES_NUMBER; i++){
if (purpose_satisfied[i] == false)
// A purpose is not satisfied
return false;
}
// All purposes are satisfied
return true;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenwireStringSupport.h"
#include <decaf/lang/Integer.h>
#include <activemq/exceptions/ActiveMQException.h>
using namespace activemq;
using namespace activemq::exceptions;
using namespace activemq::wireformat;
using namespace activemq::wireformat::openwire;
using namespace activemq::wireformat::openwire::utils;
using namespace decaf::io;
using namespace decaf::lang;
////////////////////////////////////////////////////////////////////////////////
std::string OpenwireStringSupport::readString( decaf::io::DataInputStream& dataIn )
throw ( decaf::io::IOException ) {
try {
short utflen = dataIn.readShort();
if( utflen > -1 ) {
// Let the stream get us all that data.
std::vector<unsigned char> value;
value.resize( utflen );
dataIn.readFully( value );
std::vector<unsigned char> byteArr;
byteArr.resize( utflen );
int count = 0;
for( unsigned int i = 0; i < value.size(); ++i ) {
unsigned int z = (unsigned char) value[i];
if( (z >= 0x0001) && (z <= 0x007F) ) {
byteArr[count++] = (unsigned char)z;
} else if( (z >= 0x00C0) && (z <= 0x00DF) ) {
unsigned int y = (unsigned char) value[++i];
byteArr[count++] = (unsigned char)((z-192)*64 + (y-128));
} else if ((z >= 0x00E0) && (z <= 0x00EF) ) {
unsigned int y = (unsigned char) value[++i];
unsigned int x = (unsigned char) value[++i];
byteArr[count++] = (unsigned char)((z-224)*4096 + (y-128)*64 + (x-128));
} else if( (z >= 0x00F0) && (z <= 0x00F7) ) {
unsigned int y = (unsigned char) value[++i];
unsigned int x = (unsigned char) value[++i];
unsigned int w = (unsigned char) value[++i];
byteArr[count++] = (unsigned char)((z-240)*262144 + (y-128)*4096 + (x-128)*64 + (w-128));
} else if( (z >= 0x00F8) && (z <= 0x00FB) ) {
unsigned int y = (unsigned char) value[++i];
unsigned int x = (unsigned char) value[++i];
unsigned int w = (unsigned char) value[++i];
unsigned int v = (unsigned char) value[++i];
byteArr[count++] = (unsigned char)((z-248)*16777216 + (y-128)*262144 + (x-128)*4096 + (w-128)*64 + (v-128));
} else if( (z >= 0x00FC) && (z <= 0x00FD) ) {
unsigned int y = (unsigned char) value[++i];
unsigned int x = (unsigned char) value[++i];
unsigned int w = (unsigned char) value[++i];
unsigned int v = (unsigned char) value[++i];
unsigned int u = (unsigned char) value[++i];
byteArr[count++] = (unsigned char)((z-252)*1073741824 + (y-128)*16777216 + (x-128)*262144 + (w-128)*4096 + (v-128)*64 + (u-128));
}
}
// C++ strings need a NULL terminator
byteArr.push_back( '\0' );
// Let the Compiler give us a string.
return reinterpret_cast<const char*>( &byteArr[0] );
}
return "";
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireStringSupport::writeString( decaf::io::DataOutputStream& dataOut,
const std::string* str )
throw ( decaf::io::IOException ) {
try {
if( str != NULL ) {
if( str->size() > 65536 ) {
throw IOException(
__FILE__,
__LINE__,
( std::string( "OpenwireStringSupport::writeString - Cannot marshall " ) +
"string longer than: 65536 characters, supplied string was: " +
Integer::toString( (int)str->size() ) + " characters long." ).c_str() );
}
unsigned short utflen = 0;
unsigned int c, count = 0;
std::string::const_iterator iter = str->begin();
for(; iter != str->end(); ++iter ) {
c = (unsigned char) *iter;
if( (c >= 0x0001) && (c <= 0x007F) ) {
utflen++;
} else if( c > 0x07FF ) {
utflen += 3;
} else {
utflen += 2;
}
}
dataOut.writeUnsignedShort( utflen );
std::vector<unsigned char> byteArr;
byteArr.resize( utflen );
for( iter = str->begin(); iter != str->end(); ++iter ) {
c = (unsigned char) *iter;
if( (c >= 0x0001) && (c <= 0x007F) ) {
byteArr[count++] = (unsigned char)c;
} else if( c <= 0x07FF ) {
byteArr[count++] = (unsigned char)( 192 + (c / 64));
byteArr[count++] = (unsigned char)( 128 + (c % 64));
} else {
byteArr[count++] = (unsigned char)( 224 + (c / 4096));
byteArr[count++] = (unsigned char)( 192 + ((c / 64) % 64));
byteArr[count++] = (unsigned char)( 128 + (c % 64));
}
}
dataOut.write( byteArr );
} else {
dataOut.writeShort( (short)-1 );
}
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
<commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-232<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenwireStringSupport.h"
#include <decaf/lang/Integer.h>
#include <activemq/exceptions/ActiveMQException.h>
using namespace activemq;
using namespace activemq::exceptions;
using namespace activemq::wireformat;
using namespace activemq::wireformat::openwire;
using namespace activemq::wireformat::openwire::utils;
using namespace decaf::io;
using namespace decaf::lang;
////////////////////////////////////////////////////////////////////////////////
std::string OpenwireStringSupport::readString( decaf::io::DataInputStream& dataIn )
throw ( decaf::io::IOException ) {
try {
short utflen = dataIn.readShort();
if( utflen > -1 )
{
// Let the stream get us all that data.
std::vector<unsigned char> value;
value.resize( utflen );
dataIn.readFully( value );
unsigned char c = 0;
int count = 0;
// x counts the number of 2-byte UTF8 sequences decoded
int x = 0;
while( count+x < utflen )
{
c = value[count+x];
switch( c >> 4 )
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 1-byte UTF8 encoding: 0xxxxxxx
value[count] = c;
count++;
break;
case 12:
case 13:
// 2-byte UTF8 encoding: 110X XXxx 10xx xxxx
// Bits set at 'X' means we have encountered a UTF8 encoded value
// greater than 255, which is not supported.
if( c & 0x1C ) {
throw IOException(
__FILE__,
__LINE__,
"OpenwireStringSupport::readString - Encoding not supported" );
}
// Place the decoded UTF8 character back into the value array
value[count] = ((c & 0x1F) << 6) | (value[count+x+1] & 0x3F);
count++;
x++;
break;
case 14:
default:
{
// 3-byte UTF8 encoding: 1110 xxxx 10xx xxxx 10xx xxxx
throw IOException(
__FILE__,
__LINE__,
"OpenwireStringSupport::readString - Encoding not supported" );
}
}
}
// Let the Compiler give us a string.
return std::string(reinterpret_cast<const char*>(&value[0]), count);
}
return "";
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireStringSupport::writeString( decaf::io::DataOutputStream& dataOut,
const std::string* str )
throw ( decaf::io::IOException ) {
try {
if( str != NULL ) {
if( str->size() > 65536 ) {
throw IOException(
__FILE__,
__LINE__,
( std::string( "OpenwireStringSupport::writeString - Cannot marshall " ) +
"string longer than: 65536 characters, supplied string was: " +
Integer::toString( (int)str->size() ) + " characters long." ).c_str() );
}
unsigned short utflen = 0;
int count = 0;
unsigned char c;
std::string::const_iterator iter = str->begin();
for(; iter != str->end(); ++iter ) {
c = *iter;
if( c < 0x80 ) {
utflen++;
} else {
utflen += 2;
}
}
dataOut.writeUnsignedShort( utflen );
std::vector<unsigned char> byteArr;
byteArr.resize( utflen );
for( iter = str->begin(); iter != str->end(); ++iter ) {
c = *iter;
if( c < 0x80 ) {
byteArr[count++] = (unsigned char)c;
} else {
byteArr[count++] = (unsigned char)( 0xC0 | ( (c >> 6) & 0x1F) );
byteArr[count++] = (unsigned char)( 0x80 | ( (c >> 0) & 0x3F) );
}
}
dataOut.write( byteArr );
} else {
dataOut.writeShort( (short)-1 );
}
}
AMQ_CATCH_RETHROW( decaf::io::IOException )
AMQ_CATCH_EXCEPTION_CONVERT( Exception, decaf::io::IOException )
AMQ_CATCHALL_THROW( decaf::io::IOException )
}
<|endoftext|>
|
<commit_before>#include "wide_graph_with_pool.h"
#include "../src/transwarp.h"
#include <iostream>
#include <fstream>
#include <random>
#include <numeric>
#include <stack>
#include <list>
namespace tw = transwarp;
namespace {
using data_t = std::shared_ptr<std::vector<double>>;
data_t transform(data_t data) {
std::uniform_real_distribution<double> dist(0.5, 1.5);
std::mt19937 gen{static_cast<unsigned int>((*data)[0] * 1000.)};
for (auto& v : *data) {
v *= dist(gen);
}
return data;
}
data_t copy_transform(data_t data) {
std::uniform_real_distribution<double> dist(0.5, 1.5);
auto copy = std::make_shared<std::vector<double>>(*data);
std::mt19937 gen{static_cast<unsigned int>((*data)[0] * 1000.)};
for (auto& v : *copy) {
v *= dist(gen);
}
return copy;
}
double mean(data_t data) {
return std::accumulate(data->begin(), data->end(), 0.) / static_cast<double>(data->size());
}
struct graph {
std::shared_ptr<tw::task<data_t>> input;
std::shared_ptr<tw::task<double>> final;
};
std::shared_ptr<graph> make_graph() {
auto input = tw::make_value_task(std::make_shared<std::vector<double>>());
std::vector<std::shared_ptr<tw::task<data_t>>> parents;
for (int i=0; i<8; ++i) {
auto t = tw::make_task(tw::consume, copy_transform, input)->then(tw::consume, transform);
parents.emplace_back(t);
}
auto final = tw::make_task(tw::consume, [](const std::vector<data_t>& parents) {
double res = 0;
for (const auto p : parents) {
res += mean(p);
}
return res / static_cast<double>(parents.size());
}, parents);
return std::make_shared<graph>(graph{input, final});
}
// One possible implementation of a graph pool
class graph_pool {
public:
explicit
graph_pool(std::size_t initial_size) {
for (std::size_t i=0; i<initial_size; ++i) {
ready_.push(make_graph());
}
}
std::shared_ptr<graph> next_graph() {
reclaim_finished_graphs();
double_pool_size();
auto g = ready_.top(); ready_.pop();
running_.push_back(g);
return g;
}
private:
void reclaim_finished_graphs() {
if (ready_.empty()) {
for (auto it = running_.begin(); it != running_.end();) {
if ((*it)->final->has_result()) {
ready_.push(*it);
it = running_.erase(it);
} else {
++it;
}
}
}
}
void double_pool_size() {
if (ready_.empty()) {
const auto pool_size = running_.size() + ready_.size();
for (std::size_t i=0; i<pool_size; ++i) {
ready_.push(make_graph());
}
}
}
std::stack<std::shared_ptr<graph>> ready_;
std::list<std::shared_ptr<graph>> running_;
};
}
namespace examples {
// This example demonstrates the scheduling of an extra wide graph.
// Increase iterations and size and observe your CPU load.
// New data is scheduled as soon as possible by virtue of a graph pool.
void wide_graph_with_pool(std::ostream& os, std::size_t iterations, std::size_t size) {
tw::parallel exec{8}; // thread pool with 8 threads
// Output graph for visualization
const auto graph = make_graph()->final->get_graph();
std::ofstream("wide_graph_with_pool.dot") << tw::to_string(graph);
// This is to generate random data
std::uniform_int_distribution<std::size_t> dist(size, size * 10);
std::mt19937 gen{1};
// Pool of graphs with 16 initial graphs
graph_pool pool{16};
std::vector<std::shared_future<double>> futures;
for (std::size_t i=0; i<iterations; ++i) {
auto data = std::make_shared<std::vector<double>>(dist(gen), 1); // New data arrive
auto g = pool.next_graph(); // Get the next available graph
g->input->set_value(data);
g->final->schedule_all(exec); // Schedule the graph
futures.push_back(g->final->get_future()); // Collect the future
}
// Wait and print results
for (auto& future : futures) {
os << future.get() << std::endl;
}
}
}
#ifndef UNITTEST
int main() {
std::cout << "Running example: wide_graph_with_pool ..." << std::endl;
examples::wide_graph_with_pool(std::cout);
}
#endif
<commit_msg>reuse transform function<commit_after>#include "wide_graph_with_pool.h"
#include "../src/transwarp.h"
#include <iostream>
#include <fstream>
#include <random>
#include <numeric>
#include <stack>
#include <list>
namespace tw = transwarp;
namespace {
using data_t = std::shared_ptr<std::vector<double>>;
data_t transform(data_t data) {
std::uniform_real_distribution<double> dist(0.5, 1.5);
std::mt19937 gen{static_cast<unsigned int>((*data)[0] * 1000.)};
for (auto& v : *data) {
v *= dist(gen);
}
return data;
}
data_t copy_transform(data_t data) {
auto copy = std::make_shared<std::vector<double>>(*data);
return transform(copy);
}
double mean(data_t data) {
return std::accumulate(data->begin(), data->end(), 0.) / static_cast<double>(data->size());
}
struct graph {
std::shared_ptr<tw::task<data_t>> input;
std::shared_ptr<tw::task<double>> final;
};
std::shared_ptr<graph> make_graph() {
auto input = tw::make_value_task(std::make_shared<std::vector<double>>());
std::vector<std::shared_ptr<tw::task<data_t>>> parents;
for (int i=0; i<8; ++i) {
auto t = tw::make_task(tw::consume, copy_transform, input)->then(tw::consume, transform);
parents.emplace_back(t);
}
auto final = tw::make_task(tw::consume, [](const std::vector<data_t>& parents) {
double res = 0;
for (const auto p : parents) {
res += mean(p);
}
return res / static_cast<double>(parents.size());
}, parents);
return std::make_shared<graph>(graph{input, final});
}
// One possible implementation of a graph pool
class graph_pool {
public:
explicit
graph_pool(std::size_t initial_size) {
for (std::size_t i=0; i<initial_size; ++i) {
ready_.push(make_graph());
}
}
std::shared_ptr<graph> next_graph() {
reclaim_finished_graphs();
double_pool_size();
auto g = ready_.top(); ready_.pop();
running_.push_back(g);
return g;
}
private:
void reclaim_finished_graphs() {
if (ready_.empty()) {
for (auto it = running_.begin(); it != running_.end();) {
if ((*it)->final->has_result()) {
ready_.push(*it);
it = running_.erase(it);
} else {
++it;
}
}
}
}
void double_pool_size() {
if (ready_.empty()) {
const auto pool_size = running_.size() + ready_.size();
for (std::size_t i=0; i<pool_size; ++i) {
ready_.push(make_graph());
}
}
}
std::stack<std::shared_ptr<graph>> ready_;
std::list<std::shared_ptr<graph>> running_;
};
}
namespace examples {
// This example demonstrates the scheduling of an extra wide graph.
// Increase iterations and size and observe your CPU load.
// New data is scheduled as soon as possible by virtue of a graph pool.
void wide_graph_with_pool(std::ostream& os, std::size_t iterations, std::size_t size) {
tw::parallel exec{8}; // thread pool with 8 threads
// Output graph for visualization
const auto graph = make_graph()->final->get_graph();
std::ofstream("wide_graph_with_pool.dot") << tw::to_string(graph);
// This is to generate random data
std::uniform_int_distribution<std::size_t> dist(size, size * 10);
std::mt19937 gen{1};
// Pool of graphs with 16 initial graphs
graph_pool pool{16};
std::vector<std::shared_future<double>> futures;
for (std::size_t i=0; i<iterations; ++i) {
auto data = std::make_shared<std::vector<double>>(dist(gen), 1); // New data arrive
auto g = pool.next_graph(); // Get the next available graph
g->input->set_value(data);
g->final->schedule_all(exec); // Schedule the graph
futures.push_back(g->final->get_future()); // Collect the future
}
// Wait and print results
for (auto& future : futures) {
os << future.get() << std::endl;
}
}
}
#ifndef UNITTEST
int main() {
std::cout << "Running example: wide_graph_with_pool ..." << std::endl;
examples::wide_graph_with_pool(std::cout);
}
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "imapparser.h"
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <ctype.h>
using namespace Akonadi;
class ImapParser::Private {
public:
QByteArray tagBuffer;
QByteArray dataBuffer;
int parenthesesCount;
int literalSize;
bool continuation;
// returns true if readBuffer contains a literal start and sets
// parser state accordingly
bool checkLiteralStart( const QByteArray &readBuffer, int pos = 0 )
{
if ( readBuffer.trimmed().endsWith( '}' ) ) {
const int begin = readBuffer.lastIndexOf( '{' );
const int end = readBuffer.lastIndexOf( '}' );
// new literal in previous literal data block
if ( begin < pos )
return false;
// TODO error handling
literalSize = readBuffer.mid( begin + 1, end - begin - 1 ).toInt();
// empty literal
if ( literalSize == 0 )
return false;
continuation = true;
return true;
}
return false;
}
};
int ImapParser::parseParenthesizedList( const QByteArray & data, QList<QByteArray> &result, int start )
{
result.clear();
if ( start >= data.length() )
return data.length();
int begin = data.indexOf( '(', start );
if ( begin < 0 )
return start;
int count = 0;
int sublistbegin = start;
for ( int i = begin + 1; i < data.length(); ++i ) {
if ( data[i] == '(' ) {
++count;
if ( count == 1 )
sublistbegin = i;
continue;
}
if ( data[i] == ')' ) {
if ( count <= 0 )
return i + 1;
if ( count == 1 )
result.append( data.mid( sublistbegin, i - sublistbegin + 1 ) );
--count;
continue;
}
if ( data[i] == ' ' )
continue;
if ( count == 0 ) {
QByteArray ba;
i = parseString( data, ba, i ) - 1; // compensate the increment
result.append( ba );
}
}
return data.length();
}
int ImapParser::parseString( const QByteArray & data, QByteArray & result, int start )
{
int begin = stripLeadingSpaces( data, start );
result.clear();
if ( begin >= data.length() )
return data.length();
// literal string
// TODO: error handling
if ( data[begin] == '{' ) {
int end = data.indexOf( '}', begin );
Q_ASSERT( end > begin );
int size = data.mid( begin + 1, end - begin - 1 ).toInt();
// strip CRLF
begin = end + 1;
if ( begin < data.length() && data[begin] == '\r' )
++begin;
if ( begin < data.length() && data[begin] == '\n' )
++begin;
end = begin + size;
result = data.mid( begin, end - begin );
return end;
}
// quoted string
return parseQuotedString( data, result, begin );
}
int ImapParser::parseQuotedString( const QByteArray & data, QByteArray &result, int start )
{
int begin = stripLeadingSpaces( data, start );
int end = begin;
result.clear();
if ( begin >= data.length() )
return data.length();
// quoted string
if ( data[begin] == '"' ) {
++begin;
for ( int i = begin; i < data.length(); ++i ) {
if ( data[i] == '\\' ) {
++i;
continue;
}
if ( data[i] == '"' ) {
result = data.mid( begin, i - begin );
end = i + 1; // skip the '"'
break;
}
}
}
// unquoted string
else {
bool reachedInputEnd = true;
for ( int i = begin; i < data.length(); ++i ) {
if ( data[i] == ' ' || data[i] == '(' || data[i] == ')' || data[i] == '\n' || data[i] == '\r' ) {
end = i;
reachedInputEnd = false;
break;
}
}
if ( reachedInputEnd )
end = data.length();
result = data.mid( begin, end - begin );
// transform unquoted NIL
if ( result == "NIL" )
result.clear();
}
// strip quotes
// FIXME: this can be done more efficiently
while ( result.contains( "\\\"" ) )
result.replace( "\\\"", "\"" );
while ( result.contains( "\\\\" ) )
result.replace( "\\\\", "\\" );
return end;
}
int ImapParser::stripLeadingSpaces( const QByteArray & data, int start )
{
for ( int i = start; i < data.length(); ++i ) {
if ( data[i] != ' ' )
return i;
}
return data.length();
}
int ImapParser::parenthesesBalance( const QByteArray & data, int start )
{
int count = 0;
bool insideQuote = false;
for ( int i = start; i < data.length(); ++i ) {
if ( data[i] == '"' ) {
insideQuote = !insideQuote;
continue;
}
if ( data[i] == '\\' && insideQuote ) {
++i;
continue;
}
if ( data[i] == '(' && !insideQuote ) {
++count;
continue;
}
if ( data[i] == ')' && !insideQuote ) {
--count;
continue;
}
}
return count;
}
QByteArray ImapParser::join(const QList< QByteArray > & list, const QByteArray & separator)
{
if ( list.isEmpty() )
return QByteArray();
QByteArray result = list.first();
QList<QByteArray>::ConstIterator it = list.constBegin();
++it;
for ( ; it != list.constEnd(); ++it )
result += separator + (*it);
return result;
}
QByteArray ImapParser::join(const QSet< QByteArray > & set, const QByteArray & separator)
{
QList< QByteArray > list = QList< QByteArray >::fromSet( set );
return ImapParser::join( list, separator );
}
int ImapParser::parseString(const QByteArray & data, QString & result, int start)
{
QByteArray tmp;
int end = parseString( data, tmp, start );
result = QString::fromUtf8( tmp );
return end;
}
int ImapParser::parseNumber(const QByteArray & data, int & result, bool * ok, int start)
{
if ( ok )
*ok = false;
int pos = stripLeadingSpaces( data, start );
if ( pos >= data.length() )
return data.length();
QByteArray tmp;
for (; pos < data.length(); ++pos ) {
if ( !isdigit( data.at( pos ) ) )
break;
tmp += data.at( pos );
}
result = tmp.toInt( ok );
return pos;
}
QByteArray ImapParser::quote(const QByteArray & data)
{
QByteArray result( "\"" );
result.reserve( data.length() + 2 );
for ( int i = 0; i < data.length(); ++i ) {
if ( data.at( i ) == '"' || data.at( i ) == '\\' )
result += '\\';
result += data.at( i );
}
result += '"';
return result;
}
int ImapParser::parseSequenceSet(const QByteArray & data, ImapSet & result, int start)
{
int begin = stripLeadingSpaces( data, start );
int value = -1, lower = -1, upper = -1;
for ( int i = begin; i < data.length(); ++i ) {
if ( data[i] == '*' ) {
value = 0;
} else if ( data[i] == ':' ) {
lower = value;
} else if ( isdigit( data[i] ) ) {
bool ok = false;
i = parseNumber( data, value, &ok, i );
Q_ASSERT( ok ); // TODO handle error
--i;
} else {
upper = value;
if ( lower < 0 )
lower = value;
result.add( ImapInterval( lower, upper ) );
lower = -1;
upper = -1;
value = -1;
if ( data[i] != ',' )
return i;
}
}
// take care of left-overs at input end
upper = value;
if ( lower < 0 )
lower = value;
if ( lower >= 0 && upper >= 0 )
result.add( ImapInterval( lower, upper ) );
return data.length();
}
int ImapParser::parseDateTime(const QByteArray & data, QDateTime & dateTime, int start)
{
// Syntax:
// date-time = DQUOTE date-day-fixed "-" date-month "-" date-year
// SP time SP zone DQUOTE
// date-day-fixed = (SP DIGIT) / 2DIGIT
// ; Fixed-format version of date-day
// date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
// "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
// date-year = 4DIGIT
// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
// ; Hours minutes seconds
// zone = ("+" / "-") 4DIGIT
// ; Signed four-digit value of hhmm representing
// ; hours and minutes east of Greenwich (that is,
// ; the amount that the given time differs from
// ; Universal Time). Subtracting the timezone
// ; from the given time will give the UT form.
// ; The Universal Time zone is "+0000".
// Example : "28-May-2006 01:03:35 +0200"
// Position: 0123456789012345678901234567
// 1 2
int pos = stripLeadingSpaces( data, start );
if ( data.length() <= pos )
return pos;
bool quoted = false;
if ( data[pos] == '"' ) {
quoted = true;
++pos;
}
if ( data.length() <= pos + 26 )
return start;
bool ok = true;
const int day = ( data[pos] == ' ' ? data[pos + 1] - '0' // single digit day
: data.mid( pos, 2 ).toInt( &ok ) );
if ( !ok ) return start;
pos += 3;
const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" );
int month = shortMonthNames.indexOf( data.mid( pos, 3 ).toLower() );
if ( month == -1 ) return start;
month = month / 3 + 1;
pos += 4;
const int year = data.mid( pos, 4 ).toInt( &ok );
if ( !ok ) return start;
pos += 5;
const int hours = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 3;
const int minutes = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 3;
const int seconds = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 4;
const int tzhh = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 2;
const int tzmm = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
int tzsecs = tzhh*60*60 + tzmm*60;
if ( data[pos - 3] == '-' ) tzsecs = -tzsecs;
const QDate date( year, month, day );
const QTime time( hours, minutes, seconds );
dateTime = QDateTime( date, time, Qt::UTC );
if ( !dateTime.isValid() ) return start;
dateTime = dateTime.addSecs( -tzsecs );
pos += 2;
if ( data.length() <= pos || !quoted )
return pos;
if ( data[pos] == '"' )
++pos;
return pos;
}
ImapParser::ImapParser() :
d ( new Private )
{
reset();
}
ImapParser::~ ImapParser()
{
delete d;
}
bool ImapParser::parseNextLine(const QByteArray &readBuffer)
{
d->continuation = false;
// first line, get the tag
if ( d->tagBuffer.isEmpty() ) {
const int startOfData = ImapParser::parseString( readBuffer, d->tagBuffer );
if ( startOfData < readBuffer.length() && startOfData >= 0 )
d->dataBuffer = readBuffer.mid( startOfData + 1 );
} else {
d->dataBuffer += readBuffer;
}
// literal read in progress
if ( d->literalSize > 0 ) {
d->literalSize -= readBuffer.size();
// still not everything read
if ( d->literalSize > 0 )
return false;
// check the remaining (non-literal) part for parentheses
if ( d->literalSize < 0 ) {
// the following looks strange but works since literalSize can be negative here
d->parenthesesCount = ImapParser::parenthesesBalance( readBuffer, readBuffer.length() + d->literalSize );
// check if another literal read was started
if ( d->checkLiteralStart( readBuffer, readBuffer.length() + d->literalSize ) )
return false;
}
// literal string finished but still open parentheses
if ( d->parenthesesCount > 0 )
return false;
} else {
// open parentheses
d->parenthesesCount += ImapParser::parenthesesBalance( readBuffer );
// start new literal read
if ( d->checkLiteralStart( readBuffer ) )
return false;
// still open parentheses
if ( d->parenthesesCount > 0 )
return false;
// just a normal response, fall through
}
return true;
}
QByteArray ImapParser::tag() const
{
return d->tagBuffer;
}
QByteArray ImapParser::data() const
{
return d->dataBuffer;
}
void ImapParser::reset()
{
d->dataBuffer.clear();
d->tagBuffer.clear();
d->parenthesesCount = 0;
d->literalSize = 0;
d->continuation = false;
}
bool ImapParser::continuationStarted() const
{
return d->continuation;
}
int ImapParser::continuationSize() const
{
return d->literalSize;
}<commit_msg>Don't serialize each item part three times in ItemAppendJob and a few other smaller optmizations pointed out by callgrind.<commit_after>/*
Copyright (c) 2006 - 2007 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "imapparser.h"
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <ctype.h>
using namespace Akonadi;
class ImapParser::Private {
public:
QByteArray tagBuffer;
QByteArray dataBuffer;
int parenthesesCount;
int literalSize;
bool continuation;
// returns true if readBuffer contains a literal start and sets
// parser state accordingly
bool checkLiteralStart( const QByteArray &readBuffer, int pos = 0 )
{
if ( readBuffer.trimmed().endsWith( '}' ) ) {
const int begin = readBuffer.lastIndexOf( '{' );
const int end = readBuffer.lastIndexOf( '}' );
// new literal in previous literal data block
if ( begin < pos )
return false;
// TODO error handling
literalSize = readBuffer.mid( begin + 1, end - begin - 1 ).toInt();
// empty literal
if ( literalSize == 0 )
return false;
continuation = true;
return true;
}
return false;
}
};
int ImapParser::parseParenthesizedList( const QByteArray & data, QList<QByteArray> &result, int start )
{
result.clear();
if ( start >= data.length() )
return data.length();
int begin = data.indexOf( '(', start );
if ( begin < 0 )
return start;
int count = 0;
int sublistbegin = start;
for ( int i = begin + 1; i < data.length(); ++i ) {
if ( data[i] == '(' ) {
++count;
if ( count == 1 )
sublistbegin = i;
continue;
}
if ( data[i] == ')' ) {
if ( count <= 0 )
return i + 1;
if ( count == 1 )
result.append( data.mid( sublistbegin, i - sublistbegin + 1 ) );
--count;
continue;
}
if ( data[i] == ' ' )
continue;
if ( count == 0 ) {
QByteArray ba;
i = parseString( data, ba, i ) - 1; // compensate the increment
result.append( ba );
}
}
return data.length();
}
int ImapParser::parseString( const QByteArray & data, QByteArray & result, int start )
{
int begin = stripLeadingSpaces( data, start );
result.clear();
if ( begin >= data.length() )
return data.length();
// literal string
// TODO: error handling
if ( data[begin] == '{' ) {
int end = data.indexOf( '}', begin );
Q_ASSERT( end > begin );
int size = data.mid( begin + 1, end - begin - 1 ).toInt();
// strip CRLF
begin = end + 1;
if ( begin < data.length() && data[begin] == '\r' )
++begin;
if ( begin < data.length() && data[begin] == '\n' )
++begin;
end = begin + size;
result = data.mid( begin, end - begin );
return end;
}
// quoted string
return parseQuotedString( data, result, begin );
}
int ImapParser::parseQuotedString( const QByteArray & data, QByteArray &result, int start )
{
int begin = stripLeadingSpaces( data, start );
int end = begin;
result.clear();
if ( begin >= data.length() )
return data.length();
// quoted string
if ( data[begin] == '"' ) {
++begin;
for ( int i = begin; i < data.length(); ++i ) {
if ( data[i] == '\\' ) {
++i;
continue;
}
if ( data[i] == '"' ) {
result = data.mid( begin, i - begin );
end = i + 1; // skip the '"'
break;
}
}
}
// unquoted string
else {
bool reachedInputEnd = true;
for ( int i = begin; i < data.length(); ++i ) {
if ( data[i] == ' ' || data[i] == '(' || data[i] == ')' || data[i] == '\n' || data[i] == '\r' ) {
end = i;
reachedInputEnd = false;
break;
}
}
if ( reachedInputEnd )
end = data.length();
result = data.mid( begin, end - begin );
// transform unquoted NIL
if ( result == "NIL" )
result.clear();
}
// strip quotes
// FIXME: this can be done more efficiently
while ( result.contains( "\\\"" ) )
result.replace( "\\\"", "\"" );
while ( result.contains( "\\\\" ) )
result.replace( "\\\\", "\\" );
return end;
}
int ImapParser::stripLeadingSpaces( const QByteArray & data, int start )
{
for ( int i = start; i < data.length(); ++i ) {
if ( data[i] != ' ' )
return i;
}
return data.length();
}
int ImapParser::parenthesesBalance( const QByteArray & data, int start )
{
int count = 0;
bool insideQuote = false;
for ( int i = start; i < data.length(); ++i ) {
if ( data[i] == '"' ) {
insideQuote = !insideQuote;
continue;
}
if ( data[i] == '\\' && insideQuote ) {
++i;
continue;
}
if ( data[i] == '(' && !insideQuote ) {
++count;
continue;
}
if ( data[i] == ')' && !insideQuote ) {
--count;
continue;
}
}
return count;
}
QByteArray ImapParser::join(const QList< QByteArray > & list, const QByteArray & separator)
{
if ( list.isEmpty() )
return QByteArray();
QByteArray result = list.first();
QList<QByteArray>::ConstIterator it = list.constBegin();
++it;
for ( ; it != list.constEnd(); ++it )
result += separator + (*it);
return result;
}
QByteArray ImapParser::join(const QSet< QByteArray > & set, const QByteArray & separator)
{
QList< QByteArray > list = QList< QByteArray >::fromSet( set );
return ImapParser::join( list, separator );
}
int ImapParser::parseString(const QByteArray & data, QString & result, int start)
{
QByteArray tmp;
int end = parseString( data, tmp, start );
result = QString::fromUtf8( tmp );
return end;
}
int ImapParser::parseNumber(const QByteArray & data, int & result, bool * ok, int start)
{
if ( ok )
*ok = false;
int pos = stripLeadingSpaces( data, start );
if ( pos >= data.length() )
return data.length();
int begin = pos;
for (; pos < data.length(); ++pos ) {
if ( !isdigit( data.at( pos ) ) )
break;
}
QByteArray tmp = data.mid( begin, pos - begin );
result = tmp.toInt( ok );
return pos;
}
QByteArray ImapParser::quote(const QByteArray & data)
{
QByteArray result( "\"" );
result.reserve( data.length() + 2 );
for ( int i = 0; i < data.length(); ++i ) {
if ( data.at( i ) == '"' || data.at( i ) == '\\' )
result += '\\';
result += data.at( i );
}
result += '"';
return result;
}
int ImapParser::parseSequenceSet(const QByteArray & data, ImapSet & result, int start)
{
int begin = stripLeadingSpaces( data, start );
int value = -1, lower = -1, upper = -1;
for ( int i = begin; i < data.length(); ++i ) {
if ( data[i] == '*' ) {
value = 0;
} else if ( data[i] == ':' ) {
lower = value;
} else if ( isdigit( data[i] ) ) {
bool ok = false;
i = parseNumber( data, value, &ok, i );
Q_ASSERT( ok ); // TODO handle error
--i;
} else {
upper = value;
if ( lower < 0 )
lower = value;
result.add( ImapInterval( lower, upper ) );
lower = -1;
upper = -1;
value = -1;
if ( data[i] != ',' )
return i;
}
}
// take care of left-overs at input end
upper = value;
if ( lower < 0 )
lower = value;
if ( lower >= 0 && upper >= 0 )
result.add( ImapInterval( lower, upper ) );
return data.length();
}
int ImapParser::parseDateTime(const QByteArray & data, QDateTime & dateTime, int start)
{
// Syntax:
// date-time = DQUOTE date-day-fixed "-" date-month "-" date-year
// SP time SP zone DQUOTE
// date-day-fixed = (SP DIGIT) / 2DIGIT
// ; Fixed-format version of date-day
// date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
// "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
// date-year = 4DIGIT
// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
// ; Hours minutes seconds
// zone = ("+" / "-") 4DIGIT
// ; Signed four-digit value of hhmm representing
// ; hours and minutes east of Greenwich (that is,
// ; the amount that the given time differs from
// ; Universal Time). Subtracting the timezone
// ; from the given time will give the UT form.
// ; The Universal Time zone is "+0000".
// Example : "28-May-2006 01:03:35 +0200"
// Position: 0123456789012345678901234567
// 1 2
int pos = stripLeadingSpaces( data, start );
if ( data.length() <= pos )
return pos;
bool quoted = false;
if ( data[pos] == '"' ) {
quoted = true;
++pos;
}
if ( data.length() <= pos + 26 )
return start;
bool ok = true;
const int day = ( data[pos] == ' ' ? data[pos + 1] - '0' // single digit day
: data.mid( pos, 2 ).toInt( &ok ) );
if ( !ok ) return start;
pos += 3;
const QByteArray shortMonthNames( "janfebmaraprmayjunjulaugsepoctnovdec" );
int month = shortMonthNames.indexOf( data.mid( pos, 3 ).toLower() );
if ( month == -1 ) return start;
month = month / 3 + 1;
pos += 4;
const int year = data.mid( pos, 4 ).toInt( &ok );
if ( !ok ) return start;
pos += 5;
const int hours = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 3;
const int minutes = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 3;
const int seconds = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 4;
const int tzhh = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
pos += 2;
const int tzmm = data.mid( pos, 2 ).toInt( &ok );
if ( !ok ) return start;
int tzsecs = tzhh*60*60 + tzmm*60;
if ( data[pos - 3] == '-' ) tzsecs = -tzsecs;
const QDate date( year, month, day );
const QTime time( hours, minutes, seconds );
dateTime = QDateTime( date, time, Qt::UTC );
if ( !dateTime.isValid() ) return start;
dateTime = dateTime.addSecs( -tzsecs );
pos += 2;
if ( data.length() <= pos || !quoted )
return pos;
if ( data[pos] == '"' )
++pos;
return pos;
}
ImapParser::ImapParser() :
d ( new Private )
{
reset();
}
ImapParser::~ ImapParser()
{
delete d;
}
bool ImapParser::parseNextLine(const QByteArray &readBuffer)
{
d->continuation = false;
// first line, get the tag
if ( d->tagBuffer.isEmpty() ) {
const int startOfData = ImapParser::parseString( readBuffer, d->tagBuffer );
if ( startOfData < readBuffer.length() && startOfData >= 0 )
d->dataBuffer = readBuffer.mid( startOfData + 1 );
} else {
d->dataBuffer += readBuffer;
}
// literal read in progress
if ( d->literalSize > 0 ) {
d->literalSize -= readBuffer.size();
// still not everything read
if ( d->literalSize > 0 )
return false;
// check the remaining (non-literal) part for parentheses
if ( d->literalSize < 0 ) {
// the following looks strange but works since literalSize can be negative here
d->parenthesesCount = ImapParser::parenthesesBalance( readBuffer, readBuffer.length() + d->literalSize );
// check if another literal read was started
if ( d->checkLiteralStart( readBuffer, readBuffer.length() + d->literalSize ) )
return false;
}
// literal string finished but still open parentheses
if ( d->parenthesesCount > 0 )
return false;
} else {
// open parentheses
d->parenthesesCount += ImapParser::parenthesesBalance( readBuffer );
// start new literal read
if ( d->checkLiteralStart( readBuffer ) )
return false;
// still open parentheses
if ( d->parenthesesCount > 0 )
return false;
// just a normal response, fall through
}
return true;
}
QByteArray ImapParser::tag() const
{
return d->tagBuffer;
}
QByteArray ImapParser::data() const
{
return d->dataBuffer;
}
void ImapParser::reset()
{
d->dataBuffer.clear();
d->tagBuffer.clear();
d->parenthesesCount = 0;
d->literalSize = 0;
d->continuation = false;
}
bool ImapParser::continuationStarted() const
{
return d->continuation;
}
int ImapParser::continuationSize() const
{
return d->literalSize;
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
*/
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/common/time.h>
class OpenNIGrabFrame
{
public:
OpenNIGrabFrame () : no_frame(true) {}
void
cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
if (no_frame)
{
std::string output_dir;
if (output_dir.empty ())
output_dir = ".";
std::stringstream ss;
ss << output_dir << "/frame_" << boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::local_time());
std::string file = ss.str ();
//w.writeASCII<pcl::PointXYZRGB> (file + "_ascii.pcd", *cloud);
//w.writeBinary<pcl::PointXYZRGB> (file + "_binary.pcd", *cloud);
w.writeBinaryCompressed<pcl::PointXYZRGB> (file + "_binary_compressed.pcd", *cloud);
std::cerr << "Data saved to " << ss.str () << "_{ascii,binary,binary_compresed}.pcd" << std::endl;
//no_frame = false;
}
}
void
run ()
{
// create a new grabber for OpenNI devices
pcl::Grabber* interface = new pcl::OpenNIGrabber();
// make callback function from member function
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f =
boost::bind (&OpenNIGrabFrame::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a point cloud with color values
boost::signals2::connection c = interface->registerCallback (f);
// start receiving point clouds
interface->start ();
// wait until user quits program with Ctrl-C, but no busy-waiting -> sleep (1);
while (no_frame)
boost::this_thread::sleep (boost::posix_time::seconds (1));
// stop the grabber
interface->stop ();
}
pcl::PCDWriter w;
bool no_frame;
};
int
main ()
{
OpenNIGrabFrame v;
v.run ();
return 0;
}
<commit_msg>* added functionality for openni_grab_frame * added optional command line options * optinal output filename * chose output format<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Nico Blodow (blodow@cs.tum.edu)
* Christian Potthast (potthast@usc.edu)
*/
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/common/time.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
using namespace pcl::console;
std::string default_format = "bc";
bool default_noend = false;
bool set_file_name = false;
class OpenNIGrabFrame
{
public:
OpenNIGrabFrame () : no_frame(true) {}
void
cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
if (no_frame)
{
std::string output_dir;
if (output_dir.empty ())
output_dir = ".";
std::stringstream ss;
if (noend || !set_file_name)
{
ss << output_dir << "/frame_" << boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::local_time());
file = ss.str ();
}
if (strcmp (format.c_str(), "ascii") == 0)
{
w.writeASCII<pcl::PointXYZRGB> (file + ".pcd", *cloud);
std::cerr << "Data saved in ASCII format to " << file << ".pcd" << std::endl;
}
else if (strcmp (format.c_str(), "b") == 0)
{
w.writeBinary<pcl::PointXYZRGB> (file + ".pcd", *cloud);
std::cerr << "Data saved in BINARY format to " << file << ".pcd" << std::endl;
}
else if (strcmp (format.c_str(), "bc") == 0)
{
w.writeBinaryCompressed<pcl::PointXYZRGB> (file + ".pcd", *cloud);
std::cerr << "Data saved in BINARY COMPRESSED format to " << file << ".pcd" << std::endl;
}
else if (strcmp (format.c_str(), "all") == 0)
{
w.writeASCII<pcl::PointXYZRGB> (file + "_ascii.pcd", *cloud);
w.writeBinary<pcl::PointXYZRGB> (file + "_binary.pcd", *cloud);
w.writeBinaryCompressed<pcl::PointXYZRGB> (file + "_binary_compressed.pcd", *cloud);
std::cerr << "Data saved as ASCII, BINARY and BINARY COMPRESSED to " << file << "_{ascii,binary,binary_compresed}.pcd" << std::endl;
}
if (!noend)
no_frame = false;
}
}
void
run ()
{
// create a new grabber for OpenNI devices
pcl::Grabber* interface = new pcl::OpenNIGrabber();
// make callback function from member function
boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f =
boost::bind (&OpenNIGrabFrame::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a point cloud with color values
boost::signals2::connection c = interface->registerCallback (f);
// start receiving point clouds
interface->start ();
// wait until user quits program with Ctrl-C, but no busy-waiting -> sleep (1);
while (no_frame)
boost::this_thread::sleep (boost::posix_time::seconds (1));
// stop the grabber
interface->stop ();
}
void
setOptions (std::string filename, std::string pcd_format, bool loop)
{
if (strcmp (filename.c_str(), "") != 0)
{
set_file_name = true;
size_t index = filename.find(".");
file = filename.substr(0, index);
}
noend = loop;
format = pcd_format;
}
pcl::PCDWriter w;
bool no_frame;
bool noend;
std::string file;
std::string format;
};
void
usage (char ** argv)
{
std::cout << "usage: " << argv[0] << " <filename> <options>\n\n";
print_info (" filename: if no filename is provided a generic timestamp will be set as filename\n\n");
print_info (" where options are:\n");
print_info (" -format = PCD file format (b=binary; bc=binary compressed; ascii=acsii; all=all) (default: ");
print_value ("%s", default_format.c_str()); print_info(")\n");
print_info (" -noend = Store files to disk until the user quits the program with Ctrl-C (default: ") ;
print_value ("%d", default_noend); print_info(")\n");
}
int
main (int argc, char** argv)
{
OpenNIGrabFrame v;
std::string arg;
if (argc > 1)
arg = std::string (argv[1]);
if (arg == "--help" || arg == "-h")
{
usage (argv);
return 1;
}
std::string format = default_format;
bool noend = default_noend;
std::string filename;
if (argc > 1)
{
// Parse the command line arguments for .pcd file
std::vector<int> p_file_indices;
p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
if (p_file_indices.size () > 0)
filename = argv[p_file_indices[0]];
// Command line parsing
parse_argument (argc, argv, "-format", format);
if (find_argument(argc, argv, "-noend") != -1)
noend = true;
}
v.setOptions (filename, format, noend);
v.run ();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// 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 project 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 PROJECT 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 PROJECT 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 "../../../Building/BuildingToHumanTranslator.hpp"
#include "../../HumanToBuildingTranslator.hpp"
#include "EngageHumanOperator.hpp"
#include <GameServer/Configuration/Configurator/Human/ConfiguratorHuman.hpp>
using namespace GameServer::Building;
using namespace GameServer::Common;
using namespace GameServer::Configuration;
using namespace GameServer::Persistence;
using namespace GameServer::Resource;
namespace GameServer
{
namespace Human
{
EngageHumanOperator::EngageHumanOperator(
IContextShrPtr const a_context,
IBuildingPersistenceFacadeShrPtr a_building_persistence_facade,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
IResourcePersistenceFacadeShrPtr a_resource_persistence_facade
)
: m_context(a_context),
m_building_persistence_facade(a_building_persistence_facade),
m_human_persistence_facade(a_human_persistence_facade),
m_resource_persistence_facade(a_resource_persistence_facade)
{
}
/**
* TODO: Check if holder exists.
*/
EngageHumanOperatorExitCode EngageHumanOperator::engageHuman(
ITransactionShrPtr a_transaction,
IDHolder const & a_id_holder,
IHumanKey const & a_key,
Volume const & a_volume
) const
{
try
{
// Trying to engage zero humans.
if (a_volume == 0)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_TRYING_TO_ENGAGE_ZERO_HUMANS);
}
// Human is not engageable.
if (!verifyEngageable(a_transaction, a_key))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_HUMAN_IS_NOT_ENGAGEABLE);
}
// There are not enough jobless.
if (!verifyJobless(a_transaction, a_id_holder, a_volume))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_NOT_ENOUGH_JOBLESS);
}
// Get available resources.
ResourceSet resource_set = m_resource_persistence_facade->getResources(a_transaction, a_id_holder);
// Get total cost.
ResourceSet cost = CONFIGURATOR_HUMAN.getHuman(a_key)->getCostsToEngage();
// Multiply total cost.
cost *= a_volume;
// Check if there is enough resources.
if (!(resource_set >= cost))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_NOT_ENOUGH_RESOURCES);
}
// Verifies if all possible dependencies on buildings are fulfilled.
if (!verifyDependencyOfEngagementOnBuilding(a_transaction, a_id_holder, a_key, a_volume))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_NOT_ENOUGH_BUILDINGS);
}
// Subtract the resources.
bool const result_subtract_resource =
m_resource_persistence_facade->subtractResourceSet(a_transaction, a_id_holder, cost);
// There is a possible situation (in multithreaded application) of a race condition between checking if
// there is enough resources and trying to subtract it.
// As it is not an error (just a result of another action) the appropriate exit code is returned.
if (!result_subtract_resource)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_RESOURCES_MISSING_IN_THE_MEANTIME);
}
// Subtract the jobless.
bool const result_subtract_human =
m_human_persistence_facade->subtractHuman(a_transaction, a_id_holder, KEY_WORKER_JOBLESS_NOVICE, a_volume);
// There is a possible situation (in multithreaded application) of a race condition between checking if
// there is enough jobless and trying to subtract them.
// As it is not an error (just a result of another action) the appropriate exit code is returned.
if (!result_subtract_human)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_JOBLESS_MISSING_IN_THE_MEANTIME);
}
// Add the humans.
m_human_persistence_facade->addHuman(a_transaction, a_id_holder, a_key, a_volume);
// Everything went fine.
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_HUMAN_HAS_BEEN_ENGAGED);
}
catch (...)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR);
}
}
bool EngageHumanOperator::verifyDependencyOfEngagementOnBuilding(
ITransactionShrPtr a_transaction,
IDHolder const & a_id_holder,
IHumanKey const & a_key,
Volume const & a_volume
) const
{
// Verify space in buildings.
HumanToBuildingTranslator translator;
IBuildingShrPtr building = translator.getPlaceOfWork(m_context, a_key);
if (building)
{
// Get available buildings.
BuildingWithVolumeShrPtr building_with_volume =
m_building_persistence_facade->getBuilding(a_transaction, a_id_holder, building->getKey());
// Building does not exist.
if (!building_with_volume)
{
return false;
}
// Get a vector of identifiers of a human to check if building is a place of work for some humans.
KeyVec humans = BuildingToHumanTranslator::getHumansHostedForWork(building->getKey());
// The building is a place of work for at least one human.
BOOST_ASSERT(!humans.empty());
// A sum of humans.
Volume sum(0);
// Get humans engaged in buildings.
for (KeyVec::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// Get a human by identifier of a human.
HumanWithVolumeShrPtr human = m_human_persistence_facade->getHuman(a_transaction, a_id_holder, *it);
if (human)
{
sum += human->getVolume();
}
}
// Check if there is enough place.
{
// Check if there is enough capacity.
if (building_with_volume->getVolume() * building_with_volume->getBuilding()->getCapacity() - sum < a_volume)
{
return false;
}
}
}
return true;
}
bool EngageHumanOperator::verifyEngageable(
ITransactionShrPtr a_transaction,
IHumanKey const & a_key
) const
{
IHumanShrPtr human = CONFIGURATOR_HUMAN.getHuman(a_key);
BOOST_ASSERT(human);
return human->isEngageable();
}
bool EngageHumanOperator::verifyJobless(
ITransactionShrPtr a_transaction,
IDHolder const & a_id_holder,
Volume const & a_volume
) const
{
// Get the jobless.
HumanWithVolumeShrPtr jobless =
m_human_persistence_facade->getHuman(a_transaction, a_id_holder, KEY_WORKER_JOBLESS_NOVICE);
// There are no jobless.
if (!jobless)
{
return false;
}
return (jobless->getVolume() >= a_volume);
}
} // namespace Human
} // namespace GameServer
<commit_msg>EngageHumanOperator uses ConfiguratorHuman got from Context.<commit_after>// Copyright (C) 2010 and 2011 Marcin Arkadiusz Skrobiranda.
// 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 project 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 PROJECT 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 PROJECT 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 "../../../Building/BuildingToHumanTranslator.hpp"
#include "../../HumanToBuildingTranslator.hpp"
#include "EngageHumanOperator.hpp"
using namespace GameServer::Building;
using namespace GameServer::Common;
using namespace GameServer::Configuration;
using namespace GameServer::Persistence;
using namespace GameServer::Resource;
namespace GameServer
{
namespace Human
{
EngageHumanOperator::EngageHumanOperator(
IContextShrPtr const a_context,
IBuildingPersistenceFacadeShrPtr a_building_persistence_facade,
IHumanPersistenceFacadeShrPtr a_human_persistence_facade,
IResourcePersistenceFacadeShrPtr a_resource_persistence_facade
)
: m_context(a_context),
m_building_persistence_facade(a_building_persistence_facade),
m_human_persistence_facade(a_human_persistence_facade),
m_resource_persistence_facade(a_resource_persistence_facade)
{
}
/**
* TODO: Check if holder exists.
*/
EngageHumanOperatorExitCode EngageHumanOperator::engageHuman(
ITransactionShrPtr a_transaction,
IDHolder const & a_id_holder,
IHumanKey const & a_key,
Volume const & a_volume
) const
{
try
{
// Trying to engage zero humans.
if (a_volume == 0)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_TRYING_TO_ENGAGE_ZERO_HUMANS);
}
// Human is not engageable.
if (!verifyEngageable(a_transaction, a_key))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_HUMAN_IS_NOT_ENGAGEABLE);
}
// There are not enough jobless.
if (!verifyJobless(a_transaction, a_id_holder, a_volume))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_NOT_ENOUGH_JOBLESS);
}
// Get available resources.
ResourceSet resource_set = m_resource_persistence_facade->getResources(a_transaction, a_id_holder);
// Get total cost.
ResourceSet cost = m_context->getConfiguratorHuman()->getHuman(a_key)->getCostsToEngage();
// Multiply total cost.
cost *= a_volume;
// Check if there is enough resources.
if (!(resource_set >= cost))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_NOT_ENOUGH_RESOURCES);
}
// Verifies if all possible dependencies on buildings are fulfilled.
if (!verifyDependencyOfEngagementOnBuilding(a_transaction, a_id_holder, a_key, a_volume))
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_NOT_ENOUGH_BUILDINGS);
}
// Subtract the resources.
bool const result_subtract_resource =
m_resource_persistence_facade->subtractResourceSet(a_transaction, a_id_holder, cost);
// There is a possible situation (in multithreaded application) of a race condition between checking if
// there is enough resources and trying to subtract it.
// As it is not an error (just a result of another action) the appropriate exit code is returned.
if (!result_subtract_resource)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_RESOURCES_MISSING_IN_THE_MEANTIME);
}
// Subtract the jobless.
bool const result_subtract_human =
m_human_persistence_facade->subtractHuman(a_transaction, a_id_holder, KEY_WORKER_JOBLESS_NOVICE, a_volume);
// There is a possible situation (in multithreaded application) of a race condition between checking if
// there is enough jobless and trying to subtract them.
// As it is not an error (just a result of another action) the appropriate exit code is returned.
if (!result_subtract_human)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_JOBLESS_MISSING_IN_THE_MEANTIME);
}
// Add the humans.
m_human_persistence_facade->addHuman(a_transaction, a_id_holder, a_key, a_volume);
// Everything went fine.
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_HUMAN_HAS_BEEN_ENGAGED);
}
catch (...)
{
return EngageHumanOperatorExitCode(ENGAGE_HUMAN_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR);
}
}
bool EngageHumanOperator::verifyDependencyOfEngagementOnBuilding(
ITransactionShrPtr a_transaction,
IDHolder const & a_id_holder,
IHumanKey const & a_key,
Volume const & a_volume
) const
{
// Verify space in buildings.
HumanToBuildingTranslator translator;
IBuildingShrPtr building = translator.getPlaceOfWork(m_context, a_key);
if (building)
{
// Get available buildings.
BuildingWithVolumeShrPtr building_with_volume =
m_building_persistence_facade->getBuilding(a_transaction, a_id_holder, building->getKey());
// Building does not exist.
if (!building_with_volume)
{
return false;
}
// Get a vector of identifiers of a human to check if building is a place of work for some humans.
KeyVec humans = BuildingToHumanTranslator::getHumansHostedForWork(building->getKey());
// The building is a place of work for at least one human.
BOOST_ASSERT(!humans.empty());
// A sum of humans.
Volume sum(0);
// Get humans engaged in buildings.
for (KeyVec::const_iterator it = humans.begin(); it != humans.end(); ++it)
{
// Get a human by identifier of a human.
HumanWithVolumeShrPtr human = m_human_persistence_facade->getHuman(a_transaction, a_id_holder, *it);
if (human)
{
sum += human->getVolume();
}
}
// Check if there is enough place.
{
// Check if there is enough capacity.
if (building_with_volume->getVolume() * building_with_volume->getBuilding()->getCapacity() - sum < a_volume)
{
return false;
}
}
}
return true;
}
bool EngageHumanOperator::verifyEngageable(
ITransactionShrPtr a_transaction,
IHumanKey const & a_key
) const
{
IHumanShrPtr human = m_context->getConfiguratorHuman()->getHuman(a_key);
BOOST_ASSERT(human);
return human->isEngageable();
}
bool EngageHumanOperator::verifyJobless(
ITransactionShrPtr a_transaction,
IDHolder const & a_id_holder,
Volume const & a_volume
) const
{
// Get the jobless.
HumanWithVolumeShrPtr jobless =
m_human_persistence_facade->getHuman(a_transaction, a_id_holder, KEY_WORKER_JOBLESS_NOVICE);
// There are no jobless.
if (!jobless)
{
return false;
}
return (jobless->getVolume() >= a_volume);
}
} // namespace Human
} // namespace GameServer
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkPath.h"
#include "SkCanvas.h"
static void appendStr(SkString* str, const SkPaint& paint) {
str->appendf(" style[%d] cap[%d] join[%d] antialias[%d]",
paint.getStyle(), paint.getStrokeCap(),
paint.getStrokeJoin(), paint.isAntiAlias());
}
static void appendStr(SkString* str, const SkPath& path) {
str->appendf(" filltype[%d] ptcount[%d]",
path.getFillType(), path.countPoints());
}
#define DIMENSION 32
static void drawAndTest(skiatest::Reporter* reporter, const SkPath& path,
const SkPaint& paint, bool shouldDraw) {
SkBitmap bm;
// explicitly specify a trim rowbytes, so we have no padding on each row
bm.setConfig(SkBitmap::kARGB_8888_Config, DIMENSION, DIMENSION, DIMENSION*4);
bm.allocPixels();
bm.eraseColor(0);
SkCanvas canvas(bm);
SkPaint p(paint);
p.setColor(SK_ColorWHITE);
canvas.drawPath(path, p);
size_t count = DIMENSION * DIMENSION;
const SkPMColor* ptr = bm.getAddr32(0, 0);
SkPMColor andValue = ~0;
SkPMColor orValue = 0;
for (size_t i = 0; i < count; ++i) {
SkPMColor c = ptr[i];
andValue &= c;
orValue |= c;
}
// success means we drew everywhere or nowhere (depending on shouldDraw)
bool success = shouldDraw ? (~0 == andValue) : (0 == orValue);
if (!success) {
SkString str;
if (shouldDraw) {
str.set("Path expected to draw everywhere, but didn't. ");
} else {
str.set("Path expected to draw nowhere, but did. ");
}
appendStr(&str, paint);
appendStr(&str, path);
reporter->report(str.c_str(), skiatest::Reporter::kFailed);
// uncomment this if you want to step in to see the failure
// canvas.drawPath(path, p);
}
}
static void iter_paint(skiatest::Reporter* reporter, const SkPath& path, bool shouldDraw) {
static const SkPaint::Cap gCaps[] = {
SkPaint::kButt_Cap,
SkPaint::kRound_Cap,
SkPaint::kSquare_Cap
};
static const SkPaint::Join gJoins[] = {
SkPaint::kMiter_Join,
SkPaint::kRound_Join,
SkPaint::kBevel_Join
};
static const SkPaint::Style gStyles[] = {
SkPaint::kFill_Style,
SkPaint::kStroke_Style,
SkPaint::kStrokeAndFill_Style
};
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
for (size_t join = 0; join < SK_ARRAY_COUNT(gJoins); ++join) {
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
SkPaint paint;
paint.setStrokeWidth(SkIntToScalar(10));
paint.setStrokeCap(gCaps[cap]);
paint.setStrokeJoin(gJoins[join]);
paint.setStyle(gStyles[style]);
paint.setAntiAlias(false);
drawAndTest(reporter, path, paint, shouldDraw);
paint.setAntiAlias(true);
drawAndTest(reporter, path, paint, shouldDraw);
}
}
}
}
#define CX (SkIntToScalar(DIMENSION) / 2)
#define CY (SkIntToScalar(DIMENSION) / 2)
static void make_empty(SkPath* path) {}
static void make_move(SkPath* path) { path->moveTo(CX, CY); }
static void make_line(SkPath* path) { path->moveTo(CX, CY); path->lineTo(CX, CY); }
static void make_quad(SkPath* path) { path->moveTo(CX, CY); path->quadTo(CX, CY, CX, CY); }
static void make_cubic(SkPath* path) { path->moveTo(CX, CY); path->cubicTo(CX, CY, CX, CY, CX, CY); }
/* Two invariants are tested: How does an empty/degenerate path draw?
* - if the path is drawn inverse, it should draw everywhere
* - if the path is drawn non-inverse, it should draw nowhere
*
* Things to iterate on:
* - path (empty, degenerate line/quad/cubic w/ and w/o close
* - paint style
* - path filltype
* - path stroke variants (e.g. caps, joins, width)
*/
static void test_emptydrawing(skiatest::Reporter* reporter) {
static void (*gMakeProc[])(SkPath*) = {
make_empty, make_move, make_line, make_quad, make_cubic
};
static SkPath::FillType gFills[] = {
SkPath::kWinding_FillType,
SkPath::kEvenOdd_FillType,
SkPath::kInverseWinding_FillType,
SkPath::kInverseEvenOdd_FillType
};
for (int doClose = 0; doClose < 2; ++doClose) {
for (size_t i = 0; i < SK_ARRAY_COUNT(gMakeProc); ++i) {
SkPath path;
gMakeProc[i](&path);
if (doClose) {
path.close();
}
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
path.setFillType(gFills[fill]);
bool shouldDraw = path.isInverseFillType();
iter_paint(reporter, path, shouldDraw);
}
}
}
}
static void TestEmptyPath(skiatest::Reporter* reporter) {
test_emptydrawing(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("EmptyPath", TestEmptyPathClass, TestEmptyPath)
<commit_msg>add move-close-move and move-close-move-close to the "empty" paths to test<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkPath.h"
#include "SkCanvas.h"
static void appendStr(SkString* str, const SkPaint& paint) {
str->appendf(" style[%d] cap[%d] join[%d] antialias[%d]",
paint.getStyle(), paint.getStrokeCap(),
paint.getStrokeJoin(), paint.isAntiAlias());
}
static void appendStr(SkString* str, const SkPath& path) {
str->appendf(" filltype[%d] ptcount[%d]",
path.getFillType(), path.countPoints());
}
#define DIMENSION 32
static void drawAndTest(skiatest::Reporter* reporter, const SkPath& path,
const SkPaint& paint, bool shouldDraw) {
SkBitmap bm;
// explicitly specify a trim rowbytes, so we have no padding on each row
bm.setConfig(SkBitmap::kARGB_8888_Config, DIMENSION, DIMENSION, DIMENSION*4);
bm.allocPixels();
bm.eraseColor(0);
SkCanvas canvas(bm);
SkPaint p(paint);
p.setColor(SK_ColorWHITE);
canvas.drawPath(path, p);
size_t count = DIMENSION * DIMENSION;
const SkPMColor* ptr = bm.getAddr32(0, 0);
SkPMColor andValue = ~0;
SkPMColor orValue = 0;
for (size_t i = 0; i < count; ++i) {
SkPMColor c = ptr[i];
andValue &= c;
orValue |= c;
}
// success means we drew everywhere or nowhere (depending on shouldDraw)
bool success = shouldDraw ? (~0 == andValue) : (0 == orValue);
if (!success) {
SkString str;
if (shouldDraw) {
str.set("Path expected to draw everywhere, but didn't. ");
} else {
str.set("Path expected to draw nowhere, but did. ");
}
appendStr(&str, paint);
appendStr(&str, path);
reporter->report(str.c_str(), skiatest::Reporter::kFailed);
// uncomment this if you want to step in to see the failure
// canvas.drawPath(path, p);
}
}
static void iter_paint(skiatest::Reporter* reporter, const SkPath& path, bool shouldDraw) {
static const SkPaint::Cap gCaps[] = {
SkPaint::kButt_Cap,
SkPaint::kRound_Cap,
SkPaint::kSquare_Cap
};
static const SkPaint::Join gJoins[] = {
SkPaint::kMiter_Join,
SkPaint::kRound_Join,
SkPaint::kBevel_Join
};
static const SkPaint::Style gStyles[] = {
SkPaint::kFill_Style,
SkPaint::kStroke_Style,
SkPaint::kStrokeAndFill_Style
};
for (size_t cap = 0; cap < SK_ARRAY_COUNT(gCaps); ++cap) {
for (size_t join = 0; join < SK_ARRAY_COUNT(gJoins); ++join) {
for (size_t style = 0; style < SK_ARRAY_COUNT(gStyles); ++style) {
SkPaint paint;
paint.setStrokeWidth(SkIntToScalar(10));
paint.setStrokeCap(gCaps[cap]);
paint.setStrokeJoin(gJoins[join]);
paint.setStyle(gStyles[style]);
paint.setAntiAlias(false);
drawAndTest(reporter, path, paint, shouldDraw);
paint.setAntiAlias(true);
drawAndTest(reporter, path, paint, shouldDraw);
}
}
}
}
#define CX (SkIntToScalar(DIMENSION) / 2)
#define CY (SkIntToScalar(DIMENSION) / 2)
static void make_empty(SkPath* path) {}
static void make_M(SkPath* path) { path->moveTo(CX, CY); }
static void make_MM(SkPath* path) { path->moveTo(CX, CY); path->moveTo(CX, CY); }
static void make_MZM(SkPath* path) { path->moveTo(CX, CY); path->close(); path->moveTo(CX, CY); }
static void make_L(SkPath* path) { path->moveTo(CX, CY); path->lineTo(CX, CY); }
static void make_Q(SkPath* path) { path->moveTo(CX, CY); path->quadTo(CX, CY, CX, CY); }
static void make_C(SkPath* path) { path->moveTo(CX, CY); path->cubicTo(CX, CY, CX, CY, CX, CY); }
/* Two invariants are tested: How does an empty/degenerate path draw?
* - if the path is drawn inverse, it should draw everywhere
* - if the path is drawn non-inverse, it should draw nowhere
*
* Things to iterate on:
* - path (empty, degenerate line/quad/cubic w/ and w/o close
* - paint style
* - path filltype
* - path stroke variants (e.g. caps, joins, width)
*/
static void test_emptydrawing(skiatest::Reporter* reporter) {
static void (*gMakeProc[])(SkPath*) = {
make_empty, make_M, make_MM, make_MZM, make_L, make_Q, make_C
};
static SkPath::FillType gFills[] = {
SkPath::kWinding_FillType,
SkPath::kEvenOdd_FillType,
SkPath::kInverseWinding_FillType,
SkPath::kInverseEvenOdd_FillType
};
for (int doClose = 0; doClose < 2; ++doClose) {
for (size_t i = 0; i < SK_ARRAY_COUNT(gMakeProc); ++i) {
SkPath path;
gMakeProc[i](&path);
if (doClose) {
path.close();
}
for (size_t fill = 0; fill < SK_ARRAY_COUNT(gFills); ++fill) {
path.setFillType(gFills[fill]);
bool shouldDraw = path.isInverseFillType();
iter_paint(reporter, path, shouldDraw);
}
}
}
}
static void TestEmptyPath(skiatest::Reporter* reporter) {
test_emptydrawing(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("EmptyPath", TestEmptyPathClass, TestEmptyPath)
<|endoftext|>
|
<commit_before>// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
vector<TreeNode *> nodeStack;
for (int i = 0; i < A.size(); ++i) {
auto tmp = new TreeNode(A[i]);
while (!nodeStack.empty() && A[i] > nodeStack.back()->val) {
tmp->left = nodeStack.back();
nodeStack.pop_back();
}
if (!nodeStack.empty()) {
nodeStack.back()->right = tmp;
}
nodeStack.emplace_back(tmp);
}
return nodeStack.front();
}
};
<commit_msg>Update max-tree.cpp<commit_after>// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
vector<TreeNode *> nodeStack;
for (int i = 0; i < A.size(); ++i) {
auto node = new TreeNode(A[i]);
while (!nodeStack.empty() && A[i] > nodeStack.back()->val) {
node->left = nodeStack.back();
nodeStack.pop_back();
}
if (!nodeStack.empty()) {
nodeStack.back()->right = node;
}
nodeStack.emplace_back(node);
}
return nodeStack.front();
}
};
<|endoftext|>
|
<commit_before>/*
Generic replacement for memalign in terms of xxmalloc and xxfree.
LIMITATIONS:
- This code assumes that the underlying allocator will do "the right
thing" when xxfree() is called with a pointer internal to an
allocated object. Header-based allocators, for example, need not
apply.
*/
extern "C" {
void * xxmalloc(size_t);
void xxfree(void *);
}
extern "C"
void * generic_xxmemalign(size_t alignment, size_t size) {
// Check for non power-of-two alignment.
if ((alignment == 0) || (alignment & (alignment - 1)))
{
return nullptr;
}
if (alignment <= alignof(max_align_t)) {
// Already aligned by default.
return xxmalloc(size);
} else {
// Try to just allocate an object of the requested size.
// If it happens to be aligned properly, just return it.
void * ptr = xxmalloc(size);
if (((size_t) ptr & ~(alignment - 1)) == (size_t) ptr) {
// It is already aligned just fine; return it.
return ptr;
}
// It was not aligned as requested: free the object and allocate a big one,
// and align within.
xxfree(ptr);
ptr = xxmalloc (size + 2 * alignment);
void * alignedPtr = (void *) (((size_t) ptr + alignment - 1) & ~(alignment - 1));
return alignedPtr;
}
}
<commit_msg>Added include for size_t and alignment types.<commit_after>/*
Generic replacement for memalign in terms of xxmalloc and xxfree.
LIMITATIONS:
- This code assumes that the underlying allocator will do "the right
thing" when xxfree() is called with a pointer internal to an
allocated object. Header-based allocators, for example, need not
apply.
*/
#include <stddef.h>
extern "C" {
void * xxmalloc(size_t);
void xxfree(void *);
}
extern "C"
void * generic_xxmemalign(size_t alignment, size_t size) {
// Check for non power-of-two alignment.
if ((alignment == 0) || (alignment & (alignment - 1)))
{
return nullptr;
}
if (alignment <= alignof(max_align_t)) {
// Already aligned by default.
return xxmalloc(size);
} else {
// Try to just allocate an object of the requested size.
// If it happens to be aligned properly, just return it.
void * ptr = xxmalloc(size);
if (((size_t) ptr & ~(alignment - 1)) == (size_t) ptr) {
// It is already aligned just fine; return it.
return ptr;
}
// It was not aligned as requested: free the object and allocate a big one,
// and align within.
xxfree(ptr);
ptr = xxmalloc (size + 2 * alignment);
void * alignedPtr = (void *) (((size_t) ptr + alignment - 1) & ~(alignment - 1));
return alignedPtr;
}
}
<|endoftext|>
|
<commit_before>#include "caffeine/layer.hpp"
namespace caffeine {
INSTANTIATE_CLASS(Layer);
} // namespace caffeine
<commit_msg>layer implementation now purely in layer.hpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
/*
Approach 1:
- Updated Init function to take initial contion as input
- Setting options must occur after initialization
- Addition of LinSysSetup functions to setup linear systems
- Addition of SUNLinSolEmpty() and SUNMatEmpty() functions to make
creating wrappers to linear solver and matrix easier. Also protects
against the addition of new optional operations to the APIs.
- Simplified user-supplied methods for custom linear solvers.
- Need to add ReInit and ReSize methods.
*/
#ifndef MFEM_SUNDIALS
#define MFEM_SUNDIALS
#include "../config/config.hpp"
#ifdef MFEM_USE_SUNDIALS
#ifdef MFEM_USE_MPI
#include <mpi.h>
#endif
#include "ode.hpp"
#include "solvers.hpp"
#include <cvode/cvode.h>
#include <arkode/arkode_arkstep.h>
namespace mfem
{
// ---------------------------------------------------------------------------
// Base class for interfacing with SUNMatrix and SUNLinearSolver API
// ---------------------------------------------------------------------------
/** Abstract base class for providing custom linear solvers to SUNDIALS ODE
packages, CVODE and ARKODE. For a given ODE system
dy/dt = f(y,t) or M dy/dt = f(y,t)
the purpose of this class is to facilitate the (approximate) solution of
linear systems of the form
(I - gamma J) y = b or (M - gamma J) y = b, J = J(y,t) = df/dy
and mass matrix systems of the form
M y = b, M = M(t)
for given b, y, t and gamma, where gamma is a scaled time step. */
class SundialsODELinearSolver
{
private:
TimeDependentOperator *oper;
protected:
SundialsODELinearSolver() : oper(NULL) { }
virtual ~SundialsODELinearSolver();
public:
/** Setup the ODE linear system A(y,t) = (I - gamma J) or A = (M - gamma J)
@param[in] t The time at which A(y,t) should be evaluated
@param[in] y The state at which A(y,t) should be evaluated
@param[in] fy The current value of the ODE Rhs function, f(y,t)
@param[in] jok Flag indicating if the Jacobian should be updated
@param[out] jcur Flag to signal if the Jacobian was updated
@param[in] gamma The scaled time step value */
virtual int ODELinSys(double t, Vector y, Vector fy, int jok, int *jcur,
double gamma)
{
mfem_error("SundialsODELinearSolver::ODELinSys() is not overridden!");
return(1);
}
/** Setup the ODE Mass matrix system M
@param[in] t The time at which M(t) should be evaluated*/
virtual int ODEMassSys(double t)
{
mfem_error("SundialsODELinearSolver::ODEMassSys() is not overridden!");
return(1);
}
/** Initialize the linear solver (optional) */
virtual int LSInit() { return(0); };
/** Setup the linear solver (optional) */
virtual int LSSetup() { return(0); };
/** Solve the linear system A x = b
@param[in/out] x On input, the initial guess. On output, the solution
@param[in] b The linear system right-hand side */
virtual int LSSolve(Vector &x, Vector b) = 0;
};
// ---------------------------------------------------------------------------
// Base class for interfacing with SUNDIALS packages
// ---------------------------------------------------------------------------
class SundialsODESolver
{
protected:
void *sundials_mem; /// SUNDIALS mem structure
mutable int flag; /// Last flag returned from a call to SUNDIALS
int step_mode; /// SUNDIALS step mode (NORMAL or ONE_STEP)
N_Vector y; /// State vector
SUNMatrix A; /// Linear system A = (I - gamma J) or (M - gamma J)
SUNMatrix M; /// Mass matrix M
SUNLinearSolver LSA; /// Linear solver for A
SUNLinearSolver LSM; /// Linear solver for M
SUNNonlinearSolver NLS; /// Nonlinear solver
#ifdef MFEM_USE_MPI
bool Parallel() const
{ return (N_VGetVectorID(y) != SUNDIALS_NVEC_SERIAL); }
#else
bool Parallel() const { return false; }
#endif
/// Wrapper to compute the ODE Rhs function
static int ODERhs(realtype t, const N_Vector y, N_Vector ydot,
void *user_data);
/// Default scalar tolerances
static constexpr double default_rel_tol = 1e-4;
static constexpr double default_abs_tol = 1e-9;
/// Constructors
SundialsODESolver() : sundials_mem(NULL), flag(0), step_mode(1),
y(NULL), A(NULL), M(NULL), LSA(NULL), LSM(NULL),
NLS(NULL) { }
SundialsODESolver(void *mem) : sundials_mem(mem) { }
public:
/// Access the SUNDIALS memory structure
void *GetMem() const { return sundials_mem; }
/// Returns the last flag retured a call to a SUNDIALS function
int GetFlag() const { return flag; }
};
// ---------------------------------------------------------------------------
// Interface to the CVODE library -- linear multi-step methods
// ---------------------------------------------------------------------------
class CVODESolver : public ODESolver, public SundialsODESolver
{
public:
/** Construct a serial wrapper to SUNDIALS' CVODE integrator
@param[in] lmm Specifies the linear multistep method, the options are:
CV_ADAMS - implicit methods for non-stiff systems
CV_BDF - implicit methods for stiff systems */
CVODESolver(int lmm = CV_BDF);
#ifdef MFEM_USE_MPI
/** Construct a parallel wrapper to SUNDIALS' CVODE integrator
@param[in] comm The MPI communicator used to partition the ODE system
@param[in] lmm Specifies the linear multistep method, the options are:
CV_ADAMS - implicit methods for non-stiff systems
CV_BDF - implicit methods for stiff systems */
CVODESolver(MPI_Comm comm, int lmm = CV_BDF);
#endif
/// Base class Init -- DO NOT CALL, use the below initialization function
/// that takes the initial t and x as inputs.
virtual void Init(TimeDependentOperator &f_);
/** Initialize CVODE: Calls CVodeInit() and sets some defaults.
@param[in] f_ the TimeDependentOperator that defines the ODE system
@param[in] t the initial time
@param[in] x the initial condition
@note All other methods must be called after Init(). */
void Init(TimeDependentOperator &f_, double &t, Vector &x);
/** Integrate the ODE with CVODE using the specified step mode.
@param[out] x Solution vector at the requested output timem x=x(t).
@param[in/out] t On output, the output time reached.
@param[in/out] dt On output, the last time step taken.
@note On input, the values of t and dt are used to compute desired
output time for the integration, tout = t + dt.
*/
virtual void Step(Vector &x, double &t, double &dt);
/** Attach a custom linear solver solver to CVODE
@param[in] ls_spec A SundialsODELinearSolver object defining the custom
linear solver */
void SetLinearSolver(SundialsODELinearSolver &ls_spec);
/** Select the CVODE step mode: CV_NORMAL (default) or CV_ONE_STEP
@param[in] itask The desired step mode */
void SetStepMode(int itask);
/** Print various CVODE statistics. */
void PrintInfo() const;
/// Destroy the associated CVODE memory and SUNDIALS objects
virtual ~CVODESolver();
};
// ---------------------------------------------------------------------------
// Interface to ARKode's ARKStep module -- Additive Runge-Kutta methods
// ---------------------------------------------------------------------------
class ARKStepSolver : public ODESolver, public SundialsODESolver
{
protected:
bool use_implicit;
int irk_table, erk_table;
public:
/// Types of ARKODE solvers.
enum Type { EXPLICIT, IMPLICIT };
/** Construct a serial wrapper to SUNDIALS' ARKode integrator
@param[in] type Specifies the RK method type
EXPLICIT - explicit RK method
IMPLICIT - implicit RK method */
ARKStepSolver(Type type = EXPLICIT);
#ifdef MFEM_USE_MPI
/** Construct a parallel wrapper to SUNDIALS' ARKode integrator
@param[in] comm The MPI communicator used to partition the ODE system
@param[in] type Specifies the RK method type
EXPLICIT - explicit RK method
IMPLICIT - implicit RK method */
ARKStepSolver(MPI_Comm comm, Type type = EXPLICIT);
#endif
/// Base class Init -- DO NOT CALL, use the below initialization function
/// that takes the initial t and x as inputs.
virtual void Init(TimeDependentOperator &f_);
/** Initialize ARKode: Calls ARKStepInit() and sets some defaults.
@param[in] f_ the TimeDependentOperator that defines the ODE system
@param[in] t the initial time
@param[in] x the initial condition
@note All other methods must be called after Init(). */
void Init(TimeDependentOperator &f_, double &t, Vector &x);
/** Integrate the ODE with ARKode using the specified step mode.
@param[out] x Solution vector at the requested output timem x=x(t).
@param[in/out] t On output, the output time reached.
@param[in/out] dt On output, the last time step taken.
@note On input, the values of t and dt are used to compute desired
output time for the integration, tout = t + dt.
*/
virtual void Step(Vector &x, double &t, double &dt);
/** Attach a custom linear solver solver to ARKode
@param[in] ls_spec A SundialsODELinearSolver object defining the custom
linear solver */
void SetLinearSolver(SundialsODELinearSolver &ls_spec);
/** Attach a custom mass matrix linear solver solver to ARKode
@param[in] ls_spec A SundialsODELinearSolver object defining the custom
linear solver
@param[in] tdep A integer flag indicating if the mass matrix is time
dependent (1) or time independent (0). */
void SetMassLinearSolver(SundialsODELinearSolver &ls_spec, int tdep);
/** Select the ARKode step mode: ARK_NORMAL (default) or ARK_ONE_STEP
@param[in] itask The desired step mode */
void SetStepMode(int itask);
/** Print various ARKStep statistics. */
void PrintInfo() const;
/// Destroy the associated ARKode memory and SUNDIALS objects
virtual ~ARKStepSolver();
};
} // namespace mfem
#endif // MFEM_USE_SUNDIALS
#endif // MFEM_SUNDIALS
<commit_msg>remove operator from LS base class<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
/*
Approach 1:
- Updated Init function to take initial contion as input
- Setting options must occur after initialization
- Addition of LinSysSetup functions to setup linear systems
- Addition of SUNLinSolEmpty() and SUNMatEmpty() functions to make
creating wrappers to linear solver and matrix easier. Also protects
against the addition of new optional operations to the APIs.
- Simplified user-supplied methods for custom linear solvers.
- Need to add ReInit and ReSize methods.
*/
#ifndef MFEM_SUNDIALS
#define MFEM_SUNDIALS
#include "../config/config.hpp"
#ifdef MFEM_USE_SUNDIALS
#ifdef MFEM_USE_MPI
#include <mpi.h>
#endif
#include "ode.hpp"
#include "solvers.hpp"
#include <cvode/cvode.h>
#include <arkode/arkode_arkstep.h>
namespace mfem
{
// ---------------------------------------------------------------------------
// Base class for interfacing with SUNMatrix and SUNLinearSolver API
// ---------------------------------------------------------------------------
/** Abstract base class for providing custom linear solvers to SUNDIALS ODE
packages, CVODE and ARKODE. For a given ODE system
dy/dt = f(y,t) or M dy/dt = f(y,t)
the purpose of this class is to facilitate the (approximate) solution of
linear systems of the form
(I - gamma J) y = b or (M - gamma J) y = b, J = J(y,t) = df/dy
and mass matrix systems of the form
M y = b, M = M(t)
for given b, y, t and gamma, where gamma is a scaled time step. */
class SundialsODELinearSolver
{
public:
/** Setup the ODE linear system A(y,t) = (I - gamma J) or A = (M - gamma J)
@param[in] t The time at which A(y,t) should be evaluated
@param[in] y The state at which A(y,t) should be evaluated
@param[in] fy The current value of the ODE Rhs function, f(y,t)
@param[in] jok Flag indicating if the Jacobian should be updated
@param[out] jcur Flag to signal if the Jacobian was updated
@param[in] gamma The scaled time step value */
virtual int ODELinSys(double t, Vector y, Vector fy, int jok, int *jcur,
double gamma)
{
mfem_error("SundialsODELinearSolver::ODELinSys() is not overridden!");
return(-1);
}
/** Setup the ODE Mass matrix system M
@param[in] t The time at which M(t) should be evaluated*/
virtual int ODEMassSys(double t)
{
mfem_error("SundialsODELinearSolver::ODEMassSys() is not overridden!");
return(-1);
}
/** Initialize the linear solver (optional) */
virtual int LSInit() { return(0); };
/** Setup the linear solver (optional) */
virtual int LSSetup() { return(0); };
/** Solve the linear system A x = b
@param[in/out] x On input, the initial guess. On output, the solution
@param[in] b The linear system right-hand side */
virtual int LSSolve(Vector &x, Vector b) = 0;
};
// ---------------------------------------------------------------------------
// Base class for interfacing with SUNDIALS packages
// ---------------------------------------------------------------------------
class SundialsODESolver
{
protected:
void *sundials_mem; /// SUNDIALS mem structure
mutable int flag; /// Last flag returned from a call to SUNDIALS
int step_mode; /// SUNDIALS step mode (NORMAL or ONE_STEP)
N_Vector y; /// State vector
SUNMatrix A; /// Linear system A = (I - gamma J) or (M - gamma J)
SUNMatrix M; /// Mass matrix M
SUNLinearSolver LSA; /// Linear solver for A
SUNLinearSolver LSM; /// Linear solver for M
SUNNonlinearSolver NLS; /// Nonlinear solver
#ifdef MFEM_USE_MPI
bool Parallel() const
{ return (N_VGetVectorID(y) != SUNDIALS_NVEC_SERIAL); }
#else
bool Parallel() const { return false; }
#endif
/// Wrapper to compute the ODE Rhs function
static int ODERhs(realtype t, const N_Vector y, N_Vector ydot,
void *user_data);
/// Default scalar tolerances
static constexpr double default_rel_tol = 1e-4;
static constexpr double default_abs_tol = 1e-9;
/// Constructors
SundialsODESolver() : sundials_mem(NULL), flag(0), step_mode(1),
y(NULL), A(NULL), M(NULL), LSA(NULL), LSM(NULL),
NLS(NULL) { }
SundialsODESolver(void *mem) : sundials_mem(mem) { }
public:
/// Access the SUNDIALS memory structure
void *GetMem() const { return sundials_mem; }
/// Returns the last flag retured a call to a SUNDIALS function
int GetFlag() const { return flag; }
};
// ---------------------------------------------------------------------------
// Interface to the CVODE library -- linear multi-step methods
// ---------------------------------------------------------------------------
class CVODESolver : public ODESolver, public SundialsODESolver
{
public:
/** Construct a serial wrapper to SUNDIALS' CVODE integrator
@param[in] lmm Specifies the linear multistep method, the options are:
CV_ADAMS - implicit methods for non-stiff systems
CV_BDF - implicit methods for stiff systems */
CVODESolver(int lmm = CV_BDF);
#ifdef MFEM_USE_MPI
/** Construct a parallel wrapper to SUNDIALS' CVODE integrator
@param[in] comm The MPI communicator used to partition the ODE system
@param[in] lmm Specifies the linear multistep method, the options are:
CV_ADAMS - implicit methods for non-stiff systems
CV_BDF - implicit methods for stiff systems */
CVODESolver(MPI_Comm comm, int lmm = CV_BDF);
#endif
/// Base class Init -- DO NOT CALL, use the below initialization function
/// that takes the initial t and x as inputs.
virtual void Init(TimeDependentOperator &f_);
/** Initialize CVODE: Calls CVodeInit() and sets some defaults.
@param[in] f_ the TimeDependentOperator that defines the ODE system
@param[in] t the initial time
@param[in] x the initial condition
@note All other methods must be called after Init(). */
void Init(TimeDependentOperator &f_, double &t, Vector &x);
/** Integrate the ODE with CVODE using the specified step mode.
@param[out] x Solution vector at the requested output timem x=x(t).
@param[in/out] t On output, the output time reached.
@param[in/out] dt On output, the last time step taken.
@note On input, the values of t and dt are used to compute desired
output time for the integration, tout = t + dt.
*/
virtual void Step(Vector &x, double &t, double &dt);
/** Attach a custom linear solver solver to CVODE
@param[in] ls_spec A SundialsODELinearSolver object defining the custom
linear solver */
void SetLinearSolver(SundialsODELinearSolver &ls_spec);
/** Select the CVODE step mode: CV_NORMAL (default) or CV_ONE_STEP
@param[in] itask The desired step mode */
void SetStepMode(int itask);
/** Print various CVODE statistics. */
void PrintInfo() const;
/// Destroy the associated CVODE memory and SUNDIALS objects
virtual ~CVODESolver();
};
// ---------------------------------------------------------------------------
// Interface to ARKode's ARKStep module -- Additive Runge-Kutta methods
// ---------------------------------------------------------------------------
class ARKStepSolver : public ODESolver, public SundialsODESolver
{
protected:
bool use_implicit;
int irk_table, erk_table;
public:
/// Types of ARKODE solvers.
enum Type { EXPLICIT, IMPLICIT };
/** Construct a serial wrapper to SUNDIALS' ARKode integrator
@param[in] type Specifies the RK method type
EXPLICIT - explicit RK method
IMPLICIT - implicit RK method */
ARKStepSolver(Type type = EXPLICIT);
#ifdef MFEM_USE_MPI
/** Construct a parallel wrapper to SUNDIALS' ARKode integrator
@param[in] comm The MPI communicator used to partition the ODE system
@param[in] type Specifies the RK method type
EXPLICIT - explicit RK method
IMPLICIT - implicit RK method */
ARKStepSolver(MPI_Comm comm, Type type = EXPLICIT);
#endif
/// Base class Init -- DO NOT CALL, use the below initialization function
/// that takes the initial t and x as inputs.
virtual void Init(TimeDependentOperator &f_);
/** Initialize ARKode: Calls ARKStepInit() and sets some defaults.
@param[in] f_ the TimeDependentOperator that defines the ODE system
@param[in] t the initial time
@param[in] x the initial condition
@note All other methods must be called after Init(). */
void Init(TimeDependentOperator &f_, double &t, Vector &x);
/** Integrate the ODE with ARKode using the specified step mode.
@param[out] x Solution vector at the requested output timem x=x(t).
@param[in/out] t On output, the output time reached.
@param[in/out] dt On output, the last time step taken.
@note On input, the values of t and dt are used to compute desired
output time for the integration, tout = t + dt.
*/
virtual void Step(Vector &x, double &t, double &dt);
/** Attach a custom linear solver solver to ARKode
@param[in] ls_spec A SundialsODELinearSolver object defining the custom
linear solver */
void SetLinearSolver(SundialsODELinearSolver &ls_spec);
/** Attach a custom mass matrix linear solver solver to ARKode
@param[in] ls_spec A SundialsODELinearSolver object defining the custom
linear solver
@param[in] tdep A integer flag indicating if the mass matrix is time
dependent (1) or time independent (0). */
void SetMassLinearSolver(SundialsODELinearSolver &ls_spec, int tdep);
/** Select the ARKode step mode: ARK_NORMAL (default) or ARK_ONE_STEP
@param[in] itask The desired step mode */
void SetStepMode(int itask);
/** Print various ARKStep statistics. */
void PrintInfo() const;
/// Destroy the associated ARKode memory and SUNDIALS objects
virtual ~ARKStepSolver();
};
} // namespace mfem
#endif // MFEM_USE_SUNDIALS
#endif // MFEM_SUNDIALS
<|endoftext|>
|
<commit_before>/* This is a simple HTTP(S) web server much like Python's SimpleHTTPServer */
#include <App.h>
/* Helpers for this example */
#include "helpers/AsyncFileReader.h"
#include "helpers/AsyncFileStreamer.h"
#include "helpers/Middleware.h"
/* optparse */
#define OPTPARSE_IMPLEMENTATION
#include "helpers/optparse.h"
int main(int argc, char **argv) {
int option;
struct optparse options;
optparse_init(&options, argv);
struct optparse_long longopts[] = {
{"port", 'p', OPTPARSE_REQUIRED},
{"help", 'h', OPTPARSE_NONE},
{"passphrase", 'a', OPTPARSE_REQUIRED},
{"key", 'k', OPTPARSE_REQUIRED},
{"cert", 'c', OPTPARSE_REQUIRED},
{"dh_params", 'd', OPTPARSE_REQUIRED},
{0}
};
int port = 3000;
struct us_ssl_socket_context_options ssl_options = {};
while ((option = optparse_long(&options, longopts, nullptr)) != -1) {
switch (option) {
case 'p':
port = atoi(options.optarg);
break;
case 'a':
ssl_options.passphrase = options.optarg;
break;
case 'c':
ssl_options.cert_file_name = options.optarg;
break;
case 'k':
ssl_options.key_file_name = options.optarg;
break;
case 'd':
ssl_options.dh_params_file_name = options.optarg;
break;
case 'h':
case '?':
fail:
std::cout << "Usage: " << argv[0] << " [--help] [--port <port>] [--key <ssl key>] [--cert <ssl cert>] [--passphrase <ssl key passphrase>] [--dh_params <ssl dh params file>] <public root>" << std::endl;
return 0;
}
}
char *root = optparse_arg(&options);
if (!root) {
goto fail;
}
AsyncFileStreamer asyncFileStreamer(root);
/* Either serve over HTTP or HTTPS */
struct us_ssl_socket_context_options empty_ssl_options = {};
if (memcmp(&ssl_options, &empty_ssl_options, sizeof(empty_ssl_options))) {
/* HTTPS */
uWS::SSLApp(ssl_options).get("/*", [&asyncFileStreamer](auto *res, auto *req) {
asyncFileStreamer.streamFile(res, req->getUrl());
}).listen(port, [port, root](auto *token) {
if (token) {
std::cout << "Serving " << root << " over HTTPS a " << port << std::endl;
}
}).run();
} else {
/* HTTP */
uWS::App().get("/*", [&asyncFileStreamer](auto *res, auto *req) {
asyncFileStreamer.streamFile(res, req->getUrl());
}).listen(port, [port, root](auto *token) {
if (token) {
std::cout << "Serving " << root << " over HTTP a " << port << std::endl;
}
}).run();
}
std::cout << "Failed to listen to port " << port << std::endl;
}
<commit_msg>Add mime types to files served<commit_after>/* This is a simple HTTP(S) web server much like Python's SimpleHTTPServer */
#include <App.h>
/* Helpers for this example */
#include "helpers/AsyncFileReader.h"
#include "helpers/AsyncFileStreamer.h"
#include "helpers/Middleware.h"
/* optparse */
#define OPTPARSE_IMPLEMENTATION
#include "helpers/optparse.h"
int main(int argc, char **argv) {
int option;
struct optparse options;
optparse_init(&options, argv);
struct optparse_long longopts[] = {
{"port", 'p', OPTPARSE_REQUIRED},
{"help", 'h', OPTPARSE_NONE},
{"passphrase", 'a', OPTPARSE_REQUIRED},
{"key", 'k', OPTPARSE_REQUIRED},
{"cert", 'c', OPTPARSE_REQUIRED},
{"dh_params", 'd', OPTPARSE_REQUIRED},
{0}
};
int port = 3000;
struct us_ssl_socket_context_options ssl_options = {};
while ((option = optparse_long(&options, longopts, nullptr)) != -1) {
switch (option) {
case 'p':
port = atoi(options.optarg);
break;
case 'a':
ssl_options.passphrase = options.optarg;
break;
case 'c':
ssl_options.cert_file_name = options.optarg;
break;
case 'k':
ssl_options.key_file_name = options.optarg;
break;
case 'd':
ssl_options.dh_params_file_name = options.optarg;
break;
case 'h':
case '?':
fail:
std::cout << "Usage: " << argv[0] << " [--help] [--port <port>] [--key <ssl key>] [--cert <ssl cert>] [--passphrase <ssl key passphrase>] [--dh_params <ssl dh params file>] <public root>" << std::endl;
return 0;
}
}
char *root = optparse_arg(&options);
if (!root) {
goto fail;
}
AsyncFileStreamer asyncFileStreamer(root);
/* Either serve over HTTP or HTTPS */
struct us_ssl_socket_context_options empty_ssl_options = {};
if (memcmp(&ssl_options, &empty_ssl_options, sizeof(empty_ssl_options))) {
/* HTTPS */
uWS::SSLApp(ssl_options).get("/*", [&asyncFileStreamer](auto *res, auto *req) {
serveFile(res, req);
asyncFileStreamer.streamFile(res, req->getUrl());
}).listen(port, [port, root](auto *token) {
if (token) {
std::cout << "Serving " << root << " over HTTPS a " << port << std::endl;
}
}).run();
} else {
/* HTTP */
uWS::App().get("/*", [&asyncFileStreamer](auto *res, auto *req) {
serveFile(res, req);
asyncFileStreamer.streamFile(res, req->getUrl());
}).listen(port, [port, root](auto *token) {
if (token) {
std::cout << "Serving " << root << " over HTTP a " << port << std::endl;
}
}).run();
}
std::cout << "Failed to listen to port " << port << std::endl;
}
<|endoftext|>
|
<commit_before>/*
* fairness_test.cpp
*/
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include "gtest/gtest.h"
#include "fair_mutex.hpp"
#include "yamc_testutil.hpp"
#define WAIT_TICK \
std::this_thread::sleep_for(std::chrono::milliseconds(200))
#if 0
namespace {
std::mutex g_guard;
#define TRACE(msg_) \
(std::unique_lock<std::mutex>(g_guard),\
std::cout << std::this_thread::get_id() << ':' << (msg_) << std::endl)
}
#else
#define TRACE(msg_)
#endif
using FairMutexTypes = ::testing::Types<
yamc::fair::mutex,
yamc::fair::recursive_mutex
>;
template <typename Mutex>
struct FairMutexTest : ::testing::Test {};
TYPED_TEST_CASE(FairMutexTest, FairMutexTypes);
// FIFO scheduling
TYPED_TEST(FairMutexTest, FifoSched)
{
yamc::test::phaser phaser(3);
int step = 0;
TypeParam mtx;
yamc::test::join_thread thd0([&]{
auto ph = phaser.get(0);
WAIT_TICK;
TRACE("request... L1");
mtx.lock(); // 1) acquire 1st lock
TRACE("acquire L1");
WAIT_TICK;
ph.advance(2);
WAIT_TICK;
ph.await();
WAIT_TICK;
EXPECT_EQ(1, ++step);
mtx.unlock(); // 4) unlock
TRACE("release L1");
});
yamc::test::join_thread thd1([&]{
auto ph = phaser.get(1);
WAIT_TICK;
ph.await();
WAIT_TICK;
ph.advance(2);
WAIT_TICK;
TRACE("request... L2");
mtx.lock(); // 2) request 2nd lock
TRACE("acquire L2");
EXPECT_EQ(2, ++step); // 5) acquire 2nd lock (before 3rd lock)
WAIT_TICK;
mtx.unlock(); // 6) unlock
TRACE("release L2");
});
{
auto ph = phaser.get(2);
WAIT_TICK;
ph.await();
WAIT_TICK;
ph.await();
WAIT_TICK;
ph.advance(1);
WAIT_TICK;
TRACE("request... L3");
mtx.lock(); // 3) request 3rd lock
TRACE("acquire L3");
EXPECT_EQ(3, ++step); // 7) acquire 3rd lock
WAIT_TICK;
mtx.unlock();
TRACE("release L3");
}
}
<commit_msg>refine FairMutexTest test<commit_after>/*
* fairness_test.cpp
*/
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include "gtest/gtest.h"
#include "fair_mutex.hpp"
#include "yamc_testutil.hpp"
#define TEST_TICKS std::chrono::milliseconds(200)
#define EXPECT_STEP(n_) \
{ EXPECT_EQ(n_, ++step); std::this_thread::sleep_for(TEST_TICKS); }
#if 0
namespace {
std::mutex g_guard;
#define TRACE(msg_) \
(std::unique_lock<std::mutex>(g_guard),\
std::cout << std::this_thread::get_id() << ':' << (msg_) << std::endl)
}
#else
#define TRACE(msg_)
#endif
using FairMutexTypes = ::testing::Types<
yamc::fair::mutex,
yamc::fair::recursive_mutex
>;
template <typename Mutex>
struct FairMutexTest : ::testing::Test {};
TYPED_TEST_CASE(FairMutexTest, FairMutexTypes);
// FIFO scheduling
TYPED_TEST(FairMutexTest, FifoSched)
{
yamc::test::phaser phaser(3);
int step = 0;
TypeParam mtx;
yamc::test::stopwatch<> sw;
yamc::test::task_runner(3, [&](std::size_t id) {
auto ph = phaser.get(id);
switch (id) {
case 0:
TRACE("request... L1");
mtx.lock(); // 1) acquire 1st lock
TRACE("acquire L1");
EXPECT_STEP(1)
ph.advance(2);
ph.await();
EXPECT_STEP(4)
mtx.unlock(); // 4) unlock
TRACE("release L1");
break;
case 1:
ph.await();
EXPECT_STEP(2)
ph.advance(2);
TRACE("request... L2");
mtx.lock(); // 2) request 2nd lock
TRACE("acquire L2");
EXPECT_STEP(5) // 5) acquire 2nd lock (before 3rd lock)
mtx.unlock(); // 6) unlock
TRACE("release L2");
break;
case 2:
ph.await();
ph.await();
EXPECT_STEP(3)
ph.advance(1);
TRACE("request... L3");
mtx.lock(); // 3) request 3rd lock
TRACE("acquire L3");
EXPECT_STEP(6) // 7) acquire 3rd lock (after 2nd unlock)
mtx.unlock();
TRACE("release L3");
break;
}
});
ASSERT_LE(TEST_TICKS * step, sw.elapsed());
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2021-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <type_traits>
#include <seastar/util/concepts.hh>
namespace utils {
/*
* Wraps a collection into immutable form.
*
* Immutability here means that the collection itself cannot be modified,
* i.e. adding or removing elements is not possible. Read-only methods such
* as find(), begin()/end(), lower_bound(), etc. are available and are
* transparently forwarded to the underlying collection. Return values from
* those methods are also returned as-is so it's pretty much like a const
* reference on the collection.
*
* The important difference from the const reference is that obtained
* elements or iterators are not necessarily const too, so it's possible
* to modify the found or iterated over elements.
*/
template <typename Collection>
class immutable_collection {
Collection& _col;
public:
immutable_collection(Collection& col) noexcept : _col(col) {}
#define DO_WRAP_METHOD(method, is_const) \
template <typename... Args> \
auto method(Args&&... args) is_const noexcept(noexcept(std::declval<is_const Collection>().method(args...))) { \
return _col.method(std::forward<Args>(args)...); \
}
#define WRAP_CONST_METHOD(method) \
DO_WRAP_METHOD(method, const)
#define WRAP_METHOD(method) \
WRAP_CONST_METHOD(method) \
DO_WRAP_METHOD(method, )
WRAP_METHOD(find)
WRAP_METHOD(lower_bound)
WRAP_METHOD(upper_bound)
WRAP_METHOD(slice)
WRAP_METHOD(lower_slice)
WRAP_METHOD(upper_slice)
WRAP_CONST_METHOD(empty)
WRAP_CONST_METHOD(size)
WRAP_CONST_METHOD(calculate_size)
WRAP_CONST_METHOD(external_memory_usage)
WRAP_METHOD(begin)
WRAP_METHOD(end)
WRAP_METHOD(rbegin)
WRAP_METHOD(rend)
WRAP_CONST_METHOD(cbegin)
WRAP_CONST_METHOD(cend)
WRAP_CONST_METHOD(crbegin)
WRAP_CONST_METHOD(crend)
#undef WRAP_METHOD
#undef WRAP_CONST_METHOD
#undef DO_WRAP_METHOD
};
} // namespace utils
<commit_msg>utils: immutable-collection: Make movable<commit_after>/*
* Copyright (C) 2021-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <type_traits>
#include <seastar/util/concepts.hh>
namespace utils {
/*
* Wraps a collection into immutable form.
*
* Immutability here means that the collection itself cannot be modified,
* i.e. adding or removing elements is not possible. Read-only methods such
* as find(), begin()/end(), lower_bound(), etc. are available and are
* transparently forwarded to the underlying collection. Return values from
* those methods are also returned as-is so it's pretty much like a const
* reference on the collection.
*
* The important difference from the const reference is that obtained
* elements or iterators are not necessarily const too, so it's possible
* to modify the found or iterated over elements.
*/
template <typename Collection>
class immutable_collection {
Collection* _col;
public:
immutable_collection(Collection& col) noexcept : _col(&col) {}
#define DO_WRAP_METHOD(method, is_const) \
template <typename... Args> \
auto method(Args&&... args) is_const noexcept(noexcept(std::declval<is_const Collection>().method(args...))) { \
return _col->method(std::forward<Args>(args)...); \
}
#define WRAP_CONST_METHOD(method) \
DO_WRAP_METHOD(method, const)
#define WRAP_METHOD(method) \
WRAP_CONST_METHOD(method) \
DO_WRAP_METHOD(method, )
WRAP_METHOD(find)
WRAP_METHOD(lower_bound)
WRAP_METHOD(upper_bound)
WRAP_METHOD(slice)
WRAP_METHOD(lower_slice)
WRAP_METHOD(upper_slice)
WRAP_CONST_METHOD(empty)
WRAP_CONST_METHOD(size)
WRAP_CONST_METHOD(calculate_size)
WRAP_CONST_METHOD(external_memory_usage)
WRAP_METHOD(begin)
WRAP_METHOD(end)
WRAP_METHOD(rbegin)
WRAP_METHOD(rend)
WRAP_CONST_METHOD(cbegin)
WRAP_CONST_METHOD(cend)
WRAP_CONST_METHOD(crbegin)
WRAP_CONST_METHOD(crend)
#undef WRAP_METHOD
#undef WRAP_CONST_METHOD
#undef DO_WRAP_METHOD
};
} // namespace utils
<|endoftext|>
|
<commit_before>/*
-------------------------------------------------------------------------
This file is part of BayesOpt, an efficient C++ library for
Bayesian optimization.
Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>
BayesOpt is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BayesOpt 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 BayesOpt. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/
#include <ctime>
#include <fstream>
#include "testfunctions.hpp"
int main(int nargs, char *args[])
{
bopt_params par = initialize_parameters_to_default();
par.n_iterations = 190;
par.verbose_level = 1;
par.noise = 1e-10;
par.force_jump = 30;
std::ofstream log;
std::clock_t start_t;
/* Branin */
log.open("branin.log");
par.n_init_samples = 5;
par.n_iterations = 190;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
BraninNormalized branin(par);
vectord result(2);
start_t = clock();
branin.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
branin.stepOptimization();
if (jj == 50)
{
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
}
}
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Camel */
log.open("camel.log");
par.n_init_samples = 5;
par.n_iterations = 90;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
ExampleCamelback camel(par);
vectord result(2);
vectord lb(2); lb(0) = -2; lb(1) = -1;
vectord ub(2); ub(0) = 2; ub(1) = 1;
camel.setBoundingBox(lb,ub);
start_t = clock();
camel.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
camel.stepOptimization();
if (jj == 50)
{
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
}
}
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Hart */
log.open("hart.log");
par.n_init_samples = 10;
par.n_iterations = 190;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
ExampleHartmann6 hart(par);
vectord result(6);
start_t = clock();
hart.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
hart.stepOptimization();
if (jj == 50)
{
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
}
}
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/***********************************************************************/
par.n_init_samples = 2;
par.n_iter_relearn = 1;
par.l_type = L_MCMC;
par.sc_type = SC_MAP;
/* Branin */
log.open("branin_mcmc.log");
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
par.n_iterations = 190;
BraninNormalized branin(par);
vectord result(2);
start_t = clock();
branin.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
branin.stepOptimization();
if (jj == 50)
{
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
}
}
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Camel */
log.open("camel_mcmc.log");
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
par.n_iterations = 90;
ExampleCamelback camel(par);
vectord result(2);
vectord lb(2); lb(0) = -2; lb(1) = -1;
vectord ub(2); ub(0) = 2; ub(1) = 1;
camel.setBoundingBox(lb,ub);
start_t = clock();
camel.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
camel.stepOptimization();
if (jj == 50)
{
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
}
}
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Hart */
log.open("hart_mcmc.log");
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
par.n_iterations = 190;
ExampleHartmann6 hart(par);
vectord result(6);
start_t = clock();
hart.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
hart.stepOptimization();
if (jj == 50)
{
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
}
}
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
return 0;
}
<commit_msg>Fixing minor bug<commit_after>/*
-------------------------------------------------------------------------
This file is part of BayesOpt, an efficient C++ library for
Bayesian optimization.
Copyright (C) 2011-2013 Ruben Martinez-Cantin <rmcantin@unizar.es>
BayesOpt is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BayesOpt 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 BayesOpt. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
*/
#include <ctime>
#include <fstream>
#include "testfunctions.hpp"
int main(int nargs, char *args[])
{
bopt_params par = initialize_parameters_to_default();
par.verbose_level = 0;
par.noise = 1e-10;
par.force_jump = 30;
std::ofstream log;
std::clock_t start_t;
/* Branin */
log.open("branin.log");
par.n_init_samples = 5;
par.n_iterations = 195;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
BraninNormalized branin(par);
vectord result(2);
start_t = clock();
branin.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
branin.stepOptimization();
if (jj == 50)
{
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
}
}
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Camel */
log.open("camel.log");
par.n_init_samples = 5;
par.n_iterations = 95;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
ExampleCamelback camel(par);
vectord result(2);
vectord lb(2); lb(0) = -2; lb(1) = -1;
vectord ub(2); ub(0) = 2; ub(1) = 1;
camel.setBoundingBox(lb,ub);
start_t = clock();
camel.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
camel.stepOptimization();
if (jj == 50)
{
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
}
}
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Hart */
log.open("hart.log");
par.n_init_samples = 10;
par.n_iterations = 190;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
ExampleHartmann6 hart(par);
vectord result(6);
start_t = clock();
hart.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
hart.stepOptimization();
if (jj == 50)
{
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
}
}
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/***********************************************************************/
par.n_init_samples = 2;
par.n_iter_relearn = 1;
par.l_type = L_MCMC;
par.sc_type = SC_MAP;
/* Branin */
log.open("branin_mcmc.log");
par.n_iterations = 198;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
BraninNormalized branin(par);
vectord result(2);
start_t = clock();
branin.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
branin.stepOptimization();
if (jj == 50)
{
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
}
}
result = branin.getFinalResult();
log << branin.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Camel */
log.open("camel_mcmc.log");
par.n_iterations = 98;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
ExampleCamelback camel(par);
vectord result(2);
vectord lb(2); lb(0) = -2; lb(1) = -1;
vectord ub(2); ub(0) = 2; ub(1) = 1;
camel.setBoundingBox(lb,ub);
start_t = clock();
camel.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
camel.stepOptimization();
if (jj == 50)
{
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
}
}
result = camel.getFinalResult();
log << camel.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
/* Hart */
log.open("hart_mcmc.log");
par.n_iterations = 198;
for (size_t ii = 0; ii < 10; ++ii)
{
par.random_seed = ii;
ExampleHartmann6 hart(par);
vectord result(6);
start_t = clock();
hart.initializeOptimization();
for (size_t jj = 0; jj < par.n_iterations; ++jj)
{
hart.stepOptimization();
if (jj == 50)
{
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
}
}
result = hart.getFinalResult();
log << hart.evaluateSample(result) << ", ";
log << static_cast<double>(clock() - start_t) / static_cast<double>(CLOCKS_PER_SEC)
<< std::endl;
}
log.close();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 "stdio.h"
#include "iostream"
//! [Interesting]
#include "uart_ow.hpp"
using namespace std;
int
main(int argc, char** argv)
{
mraa::UartOW* uart = new mraa::UartOW(0);
// Reset the ow bus and see if anything is present
mraa::Result rv;
if ((rv = uart->reset()) == mraa::SUCCESS) {
cout << "Reset succeeded, device(s) detected!" << endl;
} else {
cout << "Reset failed, returned " << int(rv) << ". No devices on bus?" << endl;
return 1;
}
cout << "Looking for devices..." << endl;
;
uint8_t count = 0;
// start the search from scratch
string id = uart->search(true);
if (id.empty()) {
cout << "No devices detected." << endl;
return 1;
}
while (!id.empty()) {
// hack so we don't need to cast each element of the romcode
// for printf purposes
uint8_t* ptr = (uint8_t*) id.c_str();
// The first byte (0) is the device type (family) code.
// The last byte (7) is the rom code CRC value. The
// intervening bytes are the unique 48 bit device ID.
printf("Device %02d Type 0x%02x ID %02x%02x%02x%02x%02x%02x CRC 0x%02x\n", count, ptr[0],
ptr[6], ptr[5], ptr[4], ptr[3], ptr[2], ptr[1], ptr[7]);
count++;
// continue the search with start argument set to false
id = uart->search(false);
}
cout << "Exiting..." << endl;
delete uart;
return 0;
}
//! [Interesting]
<commit_msg>UartOW.cpp example: Use .data() string accessor instead of .c_str().<commit_after>/*
* Author: Jon Trulson <jtrulson@ics.com>
* Copyright (c) 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 "stdio.h"
#include "iostream"
//! [Interesting]
#include "uart_ow.hpp"
using namespace std;
int
main(int argc, char** argv)
{
mraa::UartOW* uart = new mraa::UartOW(0);
// Reset the ow bus and see if anything is present
mraa::Result rv;
if ((rv = uart->reset()) == mraa::SUCCESS) {
cout << "Reset succeeded, device(s) detected!" << endl;
} else {
cout << "Reset failed, returned " << int(rv) << ". No devices on bus?" << endl;
return 1;
}
cout << "Looking for devices..." << endl;
;
uint8_t count = 0;
// start the search from scratch
string id = uart->search(true);
if (id.empty()) {
cout << "No devices detected." << endl;
return 1;
}
while (!id.empty()) {
// hack so we don't need to cast each element of the romcode
// for printf purposes
uint8_t* ptr = (uint8_t*) id.data();
// The first byte (0) is the device type (family) code.
// The last byte (7) is the rom code CRC value. The
// intervening bytes are the unique 48 bit device ID.
printf("Device %02d Type 0x%02x ID %02x%02x%02x%02x%02x%02x CRC 0x%02x\n", count, ptr[0],
ptr[6], ptr[5], ptr[4], ptr[3], ptr[2], ptr[1], ptr[7]);
count++;
// continue the search with start argument set to false
id = uart->search(false);
}
cout << "Exiting..." << endl;
delete uart;
return 0;
}
//! [Interesting]
<|endoftext|>
|
<commit_before>// RUN: clang -parse-noop %s -verify
void f() {
int a;
while (a) ;
while (int x) ; // expected-error {{expected '=' after declarator}}
while (float x = 0) ;
if (const int x = a) ;
switch (int x = a+10) {}
for (; int x = ++a; ) ;
}
<commit_msg>Fix test case.<commit_after>// RUN: clang -parse-noop -verify %s
void f() {
int a;
while (a) ;
while (int x) ; // expected-error {{expected '=' after declarator}}
while (float x = 0) ;
if (const int x = a) ;
switch (int x = a+10) {}
for (; int x = ++a; ) ;
}
<|endoftext|>
|
<commit_before><commit_msg>vcl: avoid possible leaks in case of unexpected exceptions<commit_after><|endoftext|>
|
<commit_before>#include "ESP8266_AT.h"
ESP8266_AT::ESP8266_AT(uint32_t rxPin, uint32_t txPin, uint32_t baud) :
m_rxPin(rxPin), m_txPin(txPin)
{
SoftwareSerial *serial = new SoftwareSerial(rxPin, txPin);
serial->begin(baud);
m_serial = serial;
}
ESP8266_AT::ESP8266_AT(SoftwareSerial &serial) :
m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}
ESP8266_AT::ESP8266_AT(HardwareSerial &serial) :
m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}
ESP8266_AT::~ESP8266_AT() {
disconnectAP();
if(m_rxPin != 0 && m_txPin !=0) delete m_serial;
}
void ESP8266_AT::rxClear() {
while(m_serial->available() > 0) m_serial->read();
}
bool ESP8266_AT::checkATResponse(String *buf, String target, uint32_t timeout) {
*buf = "";
char c;
unsigned long start = millis();
while (millis() - start < timeout) {
while(m_serial->available() > 0) {
c = m_serial->read(); // 1 byte
if(c == '\0') continue;
*buf += c;
}
if (buf->indexOf(target) != -1) return true;
}
return false;
}
bool ESP8266_AT::checkATResponse(String target, uint32_t timeout) {
String buf;
return checkATResponse(&buf, target, timeout);
}
bool ESP8266_AT::statusAT() {
rxClear();
m_serial->println("AT");
return checkATResponse();
}
bool ESP8266_AT::restart() {
rxClear();
m_serial->println("AT+RST");
if(!checkATResponse()) return false;
delay(2000);
unsigned long start = millis();
while(millis() - start < 3000) {
if(statusAT()) {
delay(1500);
return true;
}
delay(100);
}
return false;
}
bool ESP8266_AT::connectAP(String ssid, String password) {
rxClear();
m_serial->println("AT+CWMODE_DEF=1"); // 1: station(client) mode, 2: softAP(server) mode, 3: 1&2
if(!(checkATResponse() && restart())) return false; // change "DEF"ault cwMode and restart
// Connect to an AP
rxClear();
m_serial->print("AT+CWJAP_DEF=\"");
m_serial->print(ssid);
m_serial->print("\",\"");
m_serial->print(password);
m_serial->println("\"");
return checkATResponse("OK", 10000);
}
bool ESP8266_AT::disconnectAP() {
rxClear();
m_serial->println("AT+CWQAP");
return checkATResponse();
}
uint8_t ESP8266_AT::ipStatus() {
String buf;
rxClear();
m_serial->println("AT+CIPSTATUS");
checkATResponse(&buf, "S:");
uint32_t index = buf.indexOf(":");
return buf.substring(index + 1, index + 2).toInt();
}
bool ESP8266_AT::statusWiFi() {
return (ipStatus() != 5);
}
int ESP8266_AT::connect(const char *host, uint16_t port) {
if(connected()) stop();
String buf;
uint8_t retry = 10;
while(retry--) {
rxClear();
m_serial->print("AT+CIPSTART=\"TCP\",\"");
m_serial->print(host);
m_serial->print("\",");
m_serial->println(port);
checkATResponse(&buf);
if(buf.indexOf("OK") != -1 || buf.indexOf("ALREADY") != -1) {
return 1; // SUCCESS
}
delay(100);
}
return -1; // TIMED_OUT
}
int ESP8266_AT::connect(IPAddress ip, uint16_t port) {
String host = "";
for(uint8_t i = 0; i < 4;) {
host += String(ip[i]);
if(++i < 4) host += ".";
}
return connect(host.c_str(), port);
}
void ESP8266_AT::stop() {
rxClear();
m_serial->println("AT+CIPCLOSE");
checkATResponse();
}
uint8_t ESP8266_AT::connected() {
uint8_t retry = 5;
while(retry--) {
if(ipStatus() == 3) return 1;
delay(100);
}
return 0;
}
size_t ESP8266_AT::write(const uint8_t *buf, size_t size) {
return 0; // TODO
}
size_t ESP8266_AT::write(uint8_t) {
return 0; // TODO
}
int ESP8266_AT::available() {
return 0; // TODO
}
int ESP8266_AT::read() {
return 0; // TODO
}
int ESP8266_AT::read(uint8_t *buf, size_t size) {
return 0; // TODO
}
int ESP8266_AT::peek() {
return 0; // TODO
}
void ESP8266_AT::flush() {
// TODO
}
ESP8266_AT::operator bool() {
// TODO
}
<commit_msg>Added some retry functionality for some unstable network methods<commit_after>#include "ESP8266_AT.h"
ESP8266_AT::ESP8266_AT(uint32_t rxPin, uint32_t txPin, uint32_t baud) :
m_rxPin(rxPin), m_txPin(txPin)
{
SoftwareSerial *serial = new SoftwareSerial(rxPin, txPin);
serial->begin(baud);
m_serial = serial;
}
ESP8266_AT::ESP8266_AT(SoftwareSerial &serial) :
m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}
ESP8266_AT::ESP8266_AT(HardwareSerial &serial) :
m_rxPin(0), m_txPin(0), m_serial(&serial)
{
}
ESP8266_AT::~ESP8266_AT() {
disconnectAP();
if(m_rxPin != 0 && m_txPin !=0) delete m_serial;
}
void ESP8266_AT::rxClear() {
while(m_serial->available() > 0) m_serial->read();
}
bool ESP8266_AT::checkATResponse(String *buf, String target, uint32_t timeout) {
*buf = "";
char c;
unsigned long start = millis();
while (millis() - start < timeout) {
while(m_serial->available() > 0) {
c = m_serial->read(); // 1 byte
if(c == '\0') continue;
*buf += c;
}
if (buf->indexOf(target) != -1) return true;
}
return false;
}
bool ESP8266_AT::checkATResponse(String target, uint32_t timeout) {
String buf;
return checkATResponse(&buf, target, timeout);
}
bool ESP8266_AT::statusAT() {
rxClear();
m_serial->println("AT");
return checkATResponse();
}
bool ESP8266_AT::restart() {
rxClear();
m_serial->println("AT+RST");
if(!checkATResponse()) return false;
delay(2000);
unsigned long start = millis();
while(millis() - start < 3000) {
if(statusAT()) {
delay(1500);
return true;
}
delay(100);
}
return false;
}
bool ESP8266_AT::connectAP(String ssid, String password) {
rxClear();
m_serial->println("AT+CWMODE_DEF=1"); // 1: station(client) mode, 2: softAP(server) mode, 3: 1&2
if(!(checkATResponse() && restart())) return false; // change "DEF"ault cwMode and restart
uint8_t retry = 5;
while(retry--) {
// Connect to an AP
rxClear();
m_serial->print("AT+CWJAP_DEF=\"");
m_serial->print(ssid);
m_serial->print("\",\"");
m_serial->print(password);
m_serial->println("\"");
if(checkATResponse("OK", 10000)) return true;
delay(100);
}
return false;
}
bool ESP8266_AT::disconnectAP() {
rxClear();
m_serial->println("AT+CWQAP");
return checkATResponse();
}
uint8_t ESP8266_AT::ipStatus() {
String buf;
rxClear();
m_serial->println("AT+CIPSTATUS");
checkATResponse(&buf, "S:");
uint32_t index = buf.indexOf(":");
return buf.substring(index + 1, index + 2).toInt();
}
bool ESP8266_AT::statusWiFi() {
uint8_t checkCnt = 5;
while(checkCnt--) {
if(ipStatus() == 5) return false;
delay(100);
}
return true;
}
int ESP8266_AT::connect(const char *host, uint16_t port) {
if(connected()) stop();
String buf;
uint8_t retry = 10;
while(retry--) {
rxClear();
m_serial->print("AT+CIPSTART=\"TCP\",\"");
m_serial->print(host);
m_serial->print("\",");
m_serial->println(port);
checkATResponse(&buf);
if(buf.indexOf("OK") != -1 || buf.indexOf("ALREADY") != -1) {
return 1; // SUCCESS
}
delay(100);
}
return -1; // TIMED_OUT
}
int ESP8266_AT::connect(IPAddress ip, uint16_t port) {
String host = "";
for(uint8_t i = 0; i < 4;) {
host += String(ip[i]);
if(++i < 4) host += ".";
}
return connect(host.c_str(), port);
}
void ESP8266_AT::stop() {
rxClear();
m_serial->println("AT+CIPCLOSE");
checkATResponse();
}
uint8_t ESP8266_AT::connected() {
uint8_t retry = 5;
while(retry--) {
if(ipStatus() == 3) return 1;
delay(100);
}
return 0;
}
size_t ESP8266_AT::write(const uint8_t *buf, size_t size) {
return 0; // TODO
}
size_t ESP8266_AT::write(uint8_t) {
return 0; // TODO
}
int ESP8266_AT::available() {
return 0; // TODO
}
int ESP8266_AT::read() {
return 0; // TODO
}
int ESP8266_AT::read(uint8_t *buf, size_t size) {
return 0; // TODO
}
int ESP8266_AT::peek() {
return 0; // TODO
}
void ESP8266_AT::flush() {
// TODO
}
ESP8266_AT::operator bool() {
// TODO
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: salsys.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2003-03-27 17:58:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <salsys.hxx>
#include <stacktrace.hxx>
#include <stdio.h>
#include <salunx.h>
#include <saldisp.hxx>
#include <dtint.hxx>
#include <msgbox.hxx>
#include <button.hxx>
#include <svdata.hxx>
// -----------------------------------------------------------------------
String GetSalSummarySystemInfos( ULONG nFlags )
{
sal_PostMortem aPostMortem;
/*
* unimplemented flags:
* SALSYSTEM_GETSYSTEMINFO_MODULES
* SALSYSTEM_GETSYSTEMINFO_MOUSEINFO
* SALSYSTEM_GETSYSTEMINFO_SYSTEMDIRS
* SALSYSTEM_GETSYSTEMINFO_LOCALVOLUMES
*/
ByteString aRet;
if( nFlags & SALSYSTEM_GETSYSTEMINFO_SYSTEMVERSION )
aRet += aPostMortem.getSystemInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_CPUTYPE )
aRet += aPostMortem.getProcessorInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_MEMORYINFO )
aRet += aPostMortem.getMemoryInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_STACK )
aRet += aPostMortem.getStackTrace();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_GRAPHICSSYSTEM )
aRet += aPostMortem.getGraphicsSystem();
#ifdef DEBUG
fprintf( stderr, "SalSystem::GetSummarySystemInfos() =\n%s", aRet.GetBuffer() );
#endif
return String( aRet, RTL_TEXTENCODING_ISO_8859_1 );
}
bool GetSalSystemDisplayInfo( System::DisplayInfo& rInfo )
{
bool bSuccess = false;
Display* pDisplay = XOpenDisplay( NULL );
if( pDisplay )
{
int nScreen = DefaultScreen( pDisplay );
XVisualInfo aVI;
/* note: SalDisplay::BestVisual does not
* access saldata or any other data available
* only after InitVCL; nor does SalOpenGL:MakeVisualWeights
* which gets called by SalDisplay::BestVisual.
* this is crucial since GetSalSystemDisplayInfo
* gets called BEFORE Init.
*/
SalDisplay::BestVisual( pDisplay, nScreen, aVI );
rInfo.nDepth = aVI.depth;
rInfo.nWidth = DisplayWidth( pDisplay, nScreen );
rInfo.nHeight = DisplayHeight( pDisplay, nScreen );
XCloseDisplay( pDisplay );
bSuccess = true;
}
return bSuccess;
}
int ImplShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton )
{
int nRet = -1;
ImplSVData* pSVData = ImplGetSVData();
if( pSVData->mpIntroWindow )
pSVData->mpIntroWindow->Hide();
DtIntegrator* pIntegrator = DtIntegrator::CreateDtIntegrator( NULL );
if( pIntegrator->GetDtType() == DtGNOME )
{
ByteString aCmdLine( "msgbox-gnome ");
int nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
if( nButton == nDefButton )
aCmdLine.Append( "-defaultbutton" );
else
aCmdLine.Append( "-button" );
nButton++;
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( *it, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" " );
}
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( rTitle, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" \"" );
aCmdLine.Append( ByteString( rMessage, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" 2>/dev/null" );
FILE* fp = popen( aCmdLine.GetBuffer(), "r" );
if( fp )
{
ByteString aAnswer;
char buf[16];
while( fgets( buf, sizeof( buf ), fp ) )
{
aAnswer.Append( buf );
}
pclose( fp );
nRet = aAnswer.ToInt32();
}
}
else // default to a VCL dialogue since we do not have a native implementation
{
WarningBox aWarn( NULL, WB_STDWORK, rMessage );
aWarn.SetText( rTitle );
aWarn.Clear();
USHORT nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 );
nButton++;
}
aWarn.SetFocusButton( (USHORT)nDefButton+1 );
nRet = ((int)aWarn.Execute()) - 1;
}
// normalize behaviour, actually this should never happen
if( nRet < -1 || nRet >= rButtons.size() )
nRet = -1;
return nRet;
}
int ImplShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
int nDefButton = 0;
std::list< String > aButtons;
int nButtonIds[5], nBut = 0;
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_OK ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
{
aButtons.push_back( Button::GetStandardText( BUTTON_YES ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
aButtons.push_back( Button::GetStandardText( BUTTON_NO ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
nDefButton = 1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
}
aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
nDefButton = aButtons.size()-1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
{
aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
switch( nDefaultButton )
{
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
}
}
int nResult = ImplShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );
return nResult != -1 ? nButtonIds[ nResult ] : 0;
}
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.5.4.1.56); FILE MERGED 2003/04/10 09:28:31 kso 1.5.4.1.56.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
*
* $RCSfile: salsys.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-04-15 16:08:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <salsys.hxx>
#include <stacktrace.hxx>
#include <stdio.h>
#include <salunx.h>
#include <saldisp.hxx>
#include <dtint.hxx>
#include <msgbox.hxx>
#include <button.hxx>
#include <svdata.hxx>
// -----------------------------------------------------------------------
String GetSalSummarySystemInfos( ULONG nFlags )
{
sal_PostMortem aPostMortem;
/*
* unimplemented flags:
* SALSYSTEM_GETSYSTEMINFO_MODULES
* SALSYSTEM_GETSYSTEMINFO_MOUSEINFO
* SALSYSTEM_GETSYSTEMINFO_SYSTEMDIRS
* SALSYSTEM_GETSYSTEMINFO_LOCALVOLUMES
*/
ByteString aRet;
if( nFlags & SALSYSTEM_GETSYSTEMINFO_SYSTEMVERSION )
aRet += aPostMortem.getSystemInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_CPUTYPE )
aRet += aPostMortem.getProcessorInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_MEMORYINFO )
aRet += aPostMortem.getMemoryInfo();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_STACK )
aRet += aPostMortem.getStackTrace();
if( nFlags & SALSYSTEM_GETSYSTEMINFO_GRAPHICSSYSTEM )
aRet += aPostMortem.getGraphicsSystem();
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "SalSystem::GetSummarySystemInfos() =\n%s", aRet.GetBuffer() );
#endif
return String( aRet, RTL_TEXTENCODING_ISO_8859_1 );
}
bool GetSalSystemDisplayInfo( System::DisplayInfo& rInfo )
{
bool bSuccess = false;
Display* pDisplay = XOpenDisplay( NULL );
if( pDisplay )
{
int nScreen = DefaultScreen( pDisplay );
XVisualInfo aVI;
/* note: SalDisplay::BestVisual does not
* access saldata or any other data available
* only after InitVCL; nor does SalOpenGL:MakeVisualWeights
* which gets called by SalDisplay::BestVisual.
* this is crucial since GetSalSystemDisplayInfo
* gets called BEFORE Init.
*/
SalDisplay::BestVisual( pDisplay, nScreen, aVI );
rInfo.nDepth = aVI.depth;
rInfo.nWidth = DisplayWidth( pDisplay, nScreen );
rInfo.nHeight = DisplayHeight( pDisplay, nScreen );
XCloseDisplay( pDisplay );
bSuccess = true;
}
return bSuccess;
}
int ImplShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton )
{
int nRet = -1;
ImplSVData* pSVData = ImplGetSVData();
if( pSVData->mpIntroWindow )
pSVData->mpIntroWindow->Hide();
DtIntegrator* pIntegrator = DtIntegrator::CreateDtIntegrator( NULL );
if( pIntegrator->GetDtType() == DtGNOME )
{
ByteString aCmdLine( "msgbox-gnome ");
int nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
if( nButton == nDefButton )
aCmdLine.Append( "-defaultbutton" );
else
aCmdLine.Append( "-button" );
nButton++;
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( *it, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" " );
}
aCmdLine.Append( " \"" );
aCmdLine.Append( ByteString( rTitle, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" \"" );
aCmdLine.Append( ByteString( rMessage, RTL_TEXTENCODING_UTF8 ) );
aCmdLine.Append( "\" 2>/dev/null" );
FILE* fp = popen( aCmdLine.GetBuffer(), "r" );
if( fp )
{
ByteString aAnswer;
char buf[16];
while( fgets( buf, sizeof( buf ), fp ) )
{
aAnswer.Append( buf );
}
pclose( fp );
nRet = aAnswer.ToInt32();
}
}
else // default to a VCL dialogue since we do not have a native implementation
{
WarningBox aWarn( NULL, WB_STDWORK, rMessage );
aWarn.SetText( rTitle );
aWarn.Clear();
USHORT nButton = 0;
for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it )
{
aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 );
nButton++;
}
aWarn.SetFocusButton( (USHORT)nDefButton+1 );
nRet = ((int)aWarn.Execute()) - 1;
}
// normalize behaviour, actually this should never happen
if( nRet < -1 || nRet >= rButtons.size() )
nRet = -1;
return nRet;
}
int ImplShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton)
{
int nDefButton = 0;
std::list< String > aButtons;
int nButtonIds[5], nBut = 0;
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_OK ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO )
{
aButtons.push_back( Button::GetStandardText( BUTTON_YES ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES;
aButtons.push_back( Button::GetStandardText( BUTTON_NO ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO )
nDefButton = 1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL ||
nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL )
{
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
}
aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL;
if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL )
nDefButton = aButtons.size()-1;
}
if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE )
{
aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT;
aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY;
aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) );
nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE;
switch( nDefaultButton )
{
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break;
case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break;
}
}
int nResult = ImplShowNativeDialog( rTitle, rMessage, aButtons, nDefButton );
return nResult != -1 ? nButtonIds[ nResult ] : 0;
}
<|endoftext|>
|
<commit_before>#include "vsclanguage.h"
#include "hdddevice.hpp"
#include "debug.hpp"
#include "vschddone.h"
#include "factory.hpp"
extern Factory *gFactory;
VSCLanguage::VSCLanguage(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
gFactory->GetLang(m_lang);
connect( this->ui.pushButtonApply, SIGNAL( clicked() ), this, SLOT(applyConfig()));
SetupValue();
}
void VSCLanguage::SetupValue()
{
switch(m_lang)
{
case VSC_LANG_EN:
ui.radioButtonEN->setChecked(true);
break;
case VSC_LANG_ZH:
ui.radioButtonZH->setChecked(true);
break;
default:
return;
}
}
void VSCLanguage::applyConfig()
{
if (ui.radioButtonEN->isChecked() == true)
{
m_lang = VSC_LANG_EN;
}else if (ui.radioButtonZH->isChecked() == true)
{
m_lang = VSC_LANG_ZH;
}
gFactory->SetLang(m_lang);
return;
}
<commit_msg>fix lang for tabbed<commit_after>#include "vsclanguage.h"
#include "hdddevice.hpp"
#include "debug.hpp"
#include "vschddone.h"
#include "factory.hpp"
extern Factory *gFactory;
VSCLanguage::VSCLanguage(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
gFactory->GetLang(m_lang);
connect( this->ui.pushButtonApply, SIGNAL( clicked() ), this, SLOT(applyConfig()));
SetupValue();
}
void VSCLanguage::SetupValue()
{
switch(m_lang)
{
case VSC_LANG_AUTO:
ui.radioButtonAuto->setChecked(true);
break;
case VSC_LANG_EN:
ui.radioButtonEN->setChecked(true);
break;
case VSC_LANG_ZH:
ui.radioButtonZH->setChecked(true);
break;
default:
return;
}
}
void VSCLanguage::applyConfig()
{
if (ui.radioButtonAuto->isChecked() == true)
{
m_lang = VSC_LANG_AUTO;
}
else if (ui.radioButtonEN->isChecked() == true)
{
m_lang = VSC_LANG_EN;
}
else if (ui.radioButtonZH->isChecked() == true)
{
m_lang = VSC_LANG_ZH;
}
gFactory->SetLang(m_lang);
return;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.
#include "master/master_main_runner.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/hash.h"
#include "base/md5.h"
#include "base/strings/string_piece.h"
#include "base/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "common/util.h"
#include "curl/curl.h"
#include "master/master_rpc.h"
#include "ninja/dn_builder.h"
#include "ninja/ninja_main.h"
#include "thread/ninja_thread.h"
namespace {
const char kHttp[] = "http://";
// Curl helper, with md5 check sum.
class CurlHelper {
public:
static size_t WriteDataStatic(void* ptr, size_t size, size_t count,
CurlHelper* curl_helper) {
return curl_helper->WriteData(ptr, size, count);
}
CurlHelper() : curl_(curl_easy_init()) {
}
~CurlHelper() {
curl_easy_cleanup(curl_);
}
std::string Get(const std::string& url, const base::FilePath& filename) {
base::MD5Init(&md5_context_);
CHECK(base::CreateDirectory(filename.DirName()));
file_.reset(base::OpenFile(filename, "wb"));
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, CurlHelper::WriteDataStatic);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
if (curl_easy_perform(curl_) != CURLE_OK)
return "";
base::MD5Digest digest;
base::MD5Final(&digest, &md5_context_);
return MD5DigestToBase16(digest);
}
size_t WriteData(void* ptr, size_t size, size_t count) {
base::MD5Update(
&md5_context_,
base::StringPiece(reinterpret_cast<char*>(ptr), size * count));
return fwrite(ptr, size, count, file_.get());
}
private:
CURL* curl_;
base::MD5Context md5_context_;
base::ScopedFILE file_;
};
} // namespace
namespace master {
MasterMainRunner::MasterMainRunner(const std::string& bind_ip, uint16 port)
: bind_ip_(bind_ip),
port_(port),
number_of_slave_processors_(0) {
// |curl_global_init| is not thread-safe, following advice in docs of
// |curl_easy_init|, we call it manually.
curl_global_init(CURL_GLOBAL_ALL);
}
MasterMainRunner::~MasterMainRunner() {
curl_global_cleanup();
}
bool MasterMainRunner::PostCreateThreads() {
master_rpc_.reset(new MasterRPC(bind_ip_, port_, this));
return true;
}
void MasterMainRunner::StartBuild() {
std::string error;
config_.parallelism = common::GuessParallelism();
ninja_main()->RunBuild(ninja_main()->state().DefaultNodes(&error), this);
}
bool MasterMainRunner::LocalCanRunMore() {
size_t subproc_number =
subprocs_.running_.size() + subprocs_.finished_.size();
return static_cast<int>(subproc_number) < config_.parallelism;
}
bool MasterMainRunner::RemoteCanRunMore() {
return static_cast<int>(outstanding_edges_.size()) <=
number_of_slave_processors_;
}
bool MasterMainRunner::StartCommand(Edge* edge, bool run_in_local) {
if (run_in_local)
return StartCommandLocally(edge);
else
return StartCommandRemotely(edge);
}
bool MasterMainRunner::StartCommandLocally(Edge* edge) {
base::ThreadRestrictions::AssertIOAllowed();
// Create directories necessary for outputs.
for (vector<Node*>::iterator o = edge->outputs_.begin();
o != edge->outputs_.end(); ++o) {
if (!ninja_main()->disk_interface()->MakeDirs((*o)->path()))
return false;
}
// Create response file, if needed
std::string rspfile = edge->GetUnescapedRspfile();
if (!rspfile.empty()) {
std::string content = edge->GetBinding("rspfile_content");
if (!ninja_main()->disk_interface()->WriteFile(rspfile, content))
return false;
}
std::string command = edge->EvaluateCommand();
Subprocess* subproc = subprocs_.Add(command, edge->use_console());
if (!subproc)
return false;
subproc_to_edge_.insert(make_pair(subproc, edge));
return true;
}
bool MasterMainRunner::StartCommandRemotely(Edge* edge) {
int connection_id = FindMostAvailableSlave();
if (connection_id == INT_MIN)
return false;
MasterRPC::OutputPaths output_paths;
for (vector<Node*>::iterator o = edge->outputs_.begin();
o != edge->outputs_.end();
++o) {
output_paths.push_back((*o)->path());
}
std::string command = edge->EvaluateCommand();
uint32 edge_id = base::Hash(command);
outstanding_edges_[edge_id] = edge;
NinjaThread::PostTask(
NinjaThread::RPC,
FROM_HERE,
base::Bind(&MasterRPC::StartCommandRemotely,
base::Unretained(master_rpc_.get()),
connection_id,
output_paths,
edge->GetUnescapedRspfile(),
edge->GetBinding("rspfile_content"),
command,
edge_id));
return true;
}
bool MasterMainRunner::WaitForCommand(CommandRunner::Result* result) {
Subprocess* subproc;
while ((subproc = subprocs_.NextFinished()) == NULL) {
bool interrupted = subprocs_.DoWork();
if (interrupted)
return false;
}
result->status = subproc->Finish();
result->output = subproc->GetOutput();
SubprocessToEdgeMap::iterator e = subproc_to_edge_.find(subproc);
result->edge = e->second;
subproc_to_edge_.erase(e);
delete subproc;
return true;
}
std::vector<Edge*> MasterMainRunner::GetActiveEdges() {
std::vector<Edge*> edges;
for (SubprocessToEdgeMap::iterator e = subproc_to_edge_.begin();
e != subproc_to_edge_.end(); ++e)
edges.push_back(e->second);
return edges;
}
void MasterMainRunner::Abort() {
subprocs_.Clear();
}
bool MasterMainRunner::HasPendingLocalCommands() {
return !subproc_to_edge_.empty();
}
void MasterMainRunner::OnFetchTargetsDone(CommandRunner::Result result) {
DCHECK(NinjaThread::CurrentlyOn(NinjaThread::MAIN));
std::string error;
if (!ninja_main()->builder()->HasRemoteCommandRunLocally(result.edge))
ninja_main()->builder()->FinishCommand(&result, &error);
}
void MasterMainRunner::OnRemoteCommandDone(
int connection_id,
uint32 edge_id,
ExitStatus status,
const std::string& output,
const std::vector<std::string>& md5s) {
OutstandingEdgeMap::iterator it = outstanding_edges_.find(edge_id);
DCHECK(it != outstanding_edges_.end());
CommandRunner::Result result;
result.edge = it->second;
result.status = status;
result.output = output; // The output stream of the command.
outstanding_edges_.erase(it);
std::string error;
if (status != ExitSuccess) {
ninja_main()->builder()->FinishCommand(&result, &error);
return;
}
DCHECK(result.edge->outputs_.size() == md5s.size());
TargetVector targets;
for (size_t i = 0; i < result.edge->outputs_.size(); ++i) {
targets.push_back(
std::make_pair(result.edge->outputs_[i]->path(), md5s[i]));
}
DCHECK(slave_info_id_map_.find(connection_id) != slave_info_id_map_.end());
// TODO(zhchbin): Remove hard code 8080.
std::string host = slave_info_id_map_[connection_id].ip + ":" + "8080";
NinjaThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&MasterMainRunner::FetchTargetsOnBlockingPool,
this,
host,
targets,
result));
}
void MasterMainRunner::OnSlaveSystemInfoAvailable(int connection_id,
const SlaveInfo& info) {
if (slave_info_id_map_.find(connection_id) != slave_info_id_map_.end())
return;
if (info.operating_system_name != base::SysInfo::OperatingSystemName() ||
info.operating_system_architecture !=
base::SysInfo::OperatingSystemArchitecture()) {
static const string kRejectReason =
"Different system name or architecture, system info of master: \"" +
base::SysInfo::OperatingSystemName() + ", " +
base::SysInfo::OperatingSystemArchitecture() + "\".";
NinjaThread::PostTask(
NinjaThread::RPC,
FROM_HERE,
base::Bind(&MasterRPC::QuitSlave,
base::Unretained(master_rpc_.get()),
connection_id,
kRejectReason));
return;
}
slave_info_id_map_[connection_id] = info;
number_of_slave_processors_ += info.number_of_processors;
}
void MasterMainRunner::OnSlaveStatusUpdate(
int connection_id,
double load_average,
int amount_of_running_commands,
int64 amount_of_available_physical_memory) {
// Don't update the status until |OnSlaveSystemInfoAvailable| is called.
SlaveInfoIdMap::iterator it = slave_info_id_map_.find(connection_id);
if (it == slave_info_id_map_.end())
return;
it->second.load_average = load_average;
it->second.amount_of_running_commands = amount_of_running_commands;
it->second.amount_of_available_physical_memory =
amount_of_available_physical_memory;
}
void MasterMainRunner::OnSlaveClose(int connection_id) {
DCHECK(slave_info_id_map_.find(connection_id) != slave_info_id_map_.end());
slave_info_id_map_.erase(connection_id);
}
int MasterMainRunner::FindMostAvailableSlave() {
int connection_id = INT_MIN;
int max_number_of_available_processors = INT_MIN;
for (SlaveInfoIdMap::iterator it = slave_info_id_map_.begin();
it != slave_info_id_map_.end();
++it) {
int tmp =
it->second.number_of_processors - it->second.amount_of_running_commands;
if (tmp > max_number_of_available_processors) {
tmp = max_number_of_available_processors;
connection_id = it->first;
}
}
return connection_id;
}
void MasterMainRunner::FetchTargetsOnBlockingPool(
const std::string& host,
const TargetVector& targets,
CommandRunner::Result result) {
bool success = true;
if (result.success()) {
CurlHelper curl_helper;
for (size_t i = 0; i < targets.size(); ++i) {
base::FilePath filename =
base::FilePath::FromUTF8Unsafe(targets[i].first);
std::string url = kHttp + host + "/" + targets[i].first;
success = (curl_helper.Get(url, filename) == targets[i].second);
if (!success)
break;
}
}
if (success) {
NinjaThread::PostTask(
NinjaThread::MAIN,
FROM_HERE,
base::Bind(&MasterMainRunner::OnFetchTargetsDone, this, result));
}
// DO NOT call |MasterMainRunner::OnFetchTargetsDone| if curl is failed,
// since we will try to start unfinished outstanding edges locally.
}
} // namespace master
<commit_msg>[WIN] Unlock file when curl done.<commit_after>// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.
#include "master/master_main_runner.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/hash.h"
#include "base/md5.h"
#include "base/strings/string_piece.h"
#include "base/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "common/util.h"
#include "curl/curl.h"
#include "master/master_rpc.h"
#include "ninja/dn_builder.h"
#include "ninja/ninja_main.h"
#include "thread/ninja_thread.h"
namespace {
const char kHttp[] = "http://";
// Curl helper, with md5 check sum.
class CurlHelper {
public:
static size_t WriteDataStatic(void* ptr, size_t size, size_t count,
CurlHelper* curl_helper) {
return curl_helper->WriteData(ptr, size, count);
}
CurlHelper() : curl_(curl_easy_init()) {
}
~CurlHelper() {
curl_easy_cleanup(curl_);
}
std::string Get(const std::string& url, const base::FilePath& filename) {
base::MD5Init(&md5_context_);
CHECK(base::CreateDirectory(filename.DirName()));
file_.InitializeUnsafe(filename,
base::File::FLAG_CREATE | base::File::FLAG_WRITE);
if (!file_.IsValid()) {
LOG(ERROR) << filename.value();
return "";
}
curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, CurlHelper::WriteDataStatic);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, this);
if (curl_easy_perform(curl_) != CURLE_OK)
return "";
file_.Unlock();
file_.Close();
base::MD5Digest digest;
base::MD5Final(&digest, &md5_context_);
return MD5DigestToBase16(digest);
}
size_t WriteData(void* ptr, size_t size, size_t count) {
base::MD5Update(
&md5_context_,
base::StringPiece(reinterpret_cast<char*>(ptr), size * count));
return file_.WriteAtCurrentPos(reinterpret_cast<char*>(ptr), size * count);
}
private:
CURL* curl_;
base::MD5Context md5_context_;
base::File file_;
};
} // namespace
namespace master {
MasterMainRunner::MasterMainRunner(const std::string& bind_ip, uint16 port)
: bind_ip_(bind_ip),
port_(port),
number_of_slave_processors_(0) {
// |curl_global_init| is not thread-safe, following advice in docs of
// |curl_easy_init|, we call it manually.
curl_global_init(CURL_GLOBAL_ALL);
}
MasterMainRunner::~MasterMainRunner() {
curl_global_cleanup();
}
bool MasterMainRunner::PostCreateThreads() {
master_rpc_.reset(new MasterRPC(bind_ip_, port_, this));
return true;
}
void MasterMainRunner::StartBuild() {
std::string error;
config_.parallelism = common::GuessParallelism();
ninja_main()->RunBuild(ninja_main()->state().DefaultNodes(&error), this);
}
bool MasterMainRunner::LocalCanRunMore() {
size_t subproc_number =
subprocs_.running_.size() + subprocs_.finished_.size();
return static_cast<int>(subproc_number) < config_.parallelism;
}
bool MasterMainRunner::RemoteCanRunMore() {
return static_cast<int>(outstanding_edges_.size()) <=
number_of_slave_processors_;
}
bool MasterMainRunner::StartCommand(Edge* edge, bool run_in_local) {
if (run_in_local)
return StartCommandLocally(edge);
else
return StartCommandRemotely(edge);
}
bool MasterMainRunner::StartCommandLocally(Edge* edge) {
base::ThreadRestrictions::AssertIOAllowed();
// Create directories necessary for outputs.
for (vector<Node*>::iterator o = edge->outputs_.begin();
o != edge->outputs_.end(); ++o) {
if (!ninja_main()->disk_interface()->MakeDirs((*o)->path()))
return false;
}
// Create response file, if needed
std::string rspfile = edge->GetUnescapedRspfile();
if (!rspfile.empty()) {
std::string content = edge->GetBinding("rspfile_content");
if (!ninja_main()->disk_interface()->WriteFile(rspfile, content))
return false;
}
std::string command = edge->EvaluateCommand();
Subprocess* subproc = subprocs_.Add(command, edge->use_console());
if (!subproc)
return false;
subproc_to_edge_.insert(make_pair(subproc, edge));
return true;
}
bool MasterMainRunner::StartCommandRemotely(Edge* edge) {
int connection_id = FindMostAvailableSlave();
if (connection_id == INT_MIN)
return false;
MasterRPC::OutputPaths output_paths;
for (vector<Node*>::iterator o = edge->outputs_.begin();
o != edge->outputs_.end();
++o) {
output_paths.push_back((*o)->path());
}
std::string command = edge->EvaluateCommand();
uint32 edge_id = base::Hash(command);
outstanding_edges_[edge_id] = edge;
NinjaThread::PostTask(
NinjaThread::RPC,
FROM_HERE,
base::Bind(&MasterRPC::StartCommandRemotely,
base::Unretained(master_rpc_.get()),
connection_id,
output_paths,
edge->GetUnescapedRspfile(),
edge->GetBinding("rspfile_content"),
command,
edge_id));
return true;
}
bool MasterMainRunner::WaitForCommand(CommandRunner::Result* result) {
Subprocess* subproc;
while ((subproc = subprocs_.NextFinished()) == NULL) {
bool interrupted = subprocs_.DoWork();
if (interrupted)
return false;
}
result->status = subproc->Finish();
result->output = subproc->GetOutput();
SubprocessToEdgeMap::iterator e = subproc_to_edge_.find(subproc);
result->edge = e->second;
subproc_to_edge_.erase(e);
delete subproc;
return true;
}
std::vector<Edge*> MasterMainRunner::GetActiveEdges() {
std::vector<Edge*> edges;
for (SubprocessToEdgeMap::iterator e = subproc_to_edge_.begin();
e != subproc_to_edge_.end(); ++e)
edges.push_back(e->second);
return edges;
}
void MasterMainRunner::Abort() {
subprocs_.Clear();
}
bool MasterMainRunner::HasPendingLocalCommands() {
return !subproc_to_edge_.empty();
}
void MasterMainRunner::OnFetchTargetsDone(CommandRunner::Result result) {
DCHECK(NinjaThread::CurrentlyOn(NinjaThread::MAIN));
std::string error;
if (!ninja_main()->builder()->HasRemoteCommandRunLocally(result.edge))
ninja_main()->builder()->FinishCommand(&result, &error);
}
void MasterMainRunner::OnRemoteCommandDone(
int connection_id,
uint32 edge_id,
ExitStatus status,
const std::string& output,
const std::vector<std::string>& md5s) {
OutstandingEdgeMap::iterator it = outstanding_edges_.find(edge_id);
DCHECK(it != outstanding_edges_.end());
CommandRunner::Result result;
result.edge = it->second;
result.status = status;
result.output = output; // The output stream of the command.
outstanding_edges_.erase(it);
std::string error;
if (status != ExitSuccess) {
ninja_main()->builder()->FinishCommand(&result, &error);
return;
}
DCHECK(result.edge->outputs_.size() == md5s.size());
TargetVector targets;
for (size_t i = 0; i < result.edge->outputs_.size(); ++i) {
targets.push_back(
std::make_pair(result.edge->outputs_[i]->path(), md5s[i]));
}
DCHECK(slave_info_id_map_.find(connection_id) != slave_info_id_map_.end());
// TODO(zhchbin): Remove hard code 8080.
std::string host = slave_info_id_map_[connection_id].ip + ":" + "8080";
NinjaThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&MasterMainRunner::FetchTargetsOnBlockingPool,
this,
host,
targets,
result));
}
void MasterMainRunner::OnSlaveSystemInfoAvailable(int connection_id,
const SlaveInfo& info) {
if (slave_info_id_map_.find(connection_id) != slave_info_id_map_.end())
return;
if (info.operating_system_name != base::SysInfo::OperatingSystemName() ||
info.operating_system_architecture !=
base::SysInfo::OperatingSystemArchitecture()) {
static const string kRejectReason =
"Different system name or architecture, system info of master: \"" +
base::SysInfo::OperatingSystemName() + ", " +
base::SysInfo::OperatingSystemArchitecture() + "\".";
NinjaThread::PostTask(
NinjaThread::RPC,
FROM_HERE,
base::Bind(&MasterRPC::QuitSlave,
base::Unretained(master_rpc_.get()),
connection_id,
kRejectReason));
return;
}
slave_info_id_map_[connection_id] = info;
number_of_slave_processors_ += info.number_of_processors;
}
void MasterMainRunner::OnSlaveStatusUpdate(
int connection_id,
double load_average,
int amount_of_running_commands,
int64 amount_of_available_physical_memory) {
// Don't update the status until |OnSlaveSystemInfoAvailable| is called.
SlaveInfoIdMap::iterator it = slave_info_id_map_.find(connection_id);
if (it == slave_info_id_map_.end())
return;
it->second.load_average = load_average;
it->second.amount_of_running_commands = amount_of_running_commands;
it->second.amount_of_available_physical_memory =
amount_of_available_physical_memory;
}
void MasterMainRunner::OnSlaveClose(int connection_id) {
DCHECK(slave_info_id_map_.find(connection_id) != slave_info_id_map_.end());
slave_info_id_map_.erase(connection_id);
}
int MasterMainRunner::FindMostAvailableSlave() {
int connection_id = INT_MIN;
int max_number_of_available_processors = INT_MIN;
for (SlaveInfoIdMap::iterator it = slave_info_id_map_.begin();
it != slave_info_id_map_.end();
++it) {
int tmp =
it->second.number_of_processors - it->second.amount_of_running_commands;
if (tmp > max_number_of_available_processors) {
tmp = max_number_of_available_processors;
connection_id = it->first;
}
}
return connection_id;
}
void MasterMainRunner::FetchTargetsOnBlockingPool(
const std::string& host,
const TargetVector& targets,
CommandRunner::Result result) {
bool success = true;
if (result.success()) {
CurlHelper curl_helper;
for (size_t i = 0; i < targets.size(); ++i) {
base::FilePath filename =
base::FilePath::FromUTF8Unsafe(targets[i].first);
std::string url = kHttp + host + "/" + targets[i].first;
success = (curl_helper.Get(url, filename) == targets[i].second);
if (!success)
break;
}
}
if (success) {
NinjaThread::PostTask(
NinjaThread::MAIN,
FROM_HERE,
base::Bind(&MasterMainRunner::OnFetchTargetsDone, this, result));
}
// DO NOT call |MasterMainRunner::OnFetchTargetsDone| if curl is failed,
// since we will try to start unfinished outstanding edges locally.
}
} // namespace master
<|endoftext|>
|
<commit_before>// $Id$
#include <vector>
#include "ScoreComponentCollection.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
ScoreComponentCollection::ScoreIndexMap ScoreComponentCollection::s_scoreIndexes;
size_t ScoreComponentCollection::s_denseVectorSize = 0;
ScoreComponentCollection::ScoreComponentCollection() : m_scores(s_denseVectorSize)
{}
void ScoreComponentCollection::RegisterScoreProducer
(const FeatureFunction* scoreProducer)
{
size_t start = s_denseVectorSize;
size_t end = start + scoreProducer->GetNumScoreComponents();
VERBOSE(1, "FeatureFunction: " << scoreProducer->GetScoreProducerDescription() << " start: " << start << " end: " << end << endl);
s_scoreIndexes[scoreProducer] = pair<size_t,size_t>(start,end);
s_denseVectorSize = end;
}
float ScoreComponentCollection::GetWeightedScore() const
{
return m_scores.inner_product(StaticData::Instance().GetAllWeights().m_scores);
}
void ScoreComponentCollection::MultiplyEquals(float scalar)
{
m_scores *= scalar;
}
// Multiply all weights of this sparse producer by a given scalar
void ScoreComponentCollection::MultiplyEquals(const FeatureFunction* sp, float scalar)
{
std::string prefix = sp->GetScoreProducerDescription() + FName::SEP;
for(FVector::FNVmap::const_iterator i = m_scores.cbegin(); i != m_scores.cend(); i++) {
std::stringstream name;
name << i->first;
if (name.str().substr( 0, prefix.length() ).compare( prefix ) == 0)
m_scores[i->first] = i->second * scalar;
}
}
// Count weights belonging to this sparse producer
size_t ScoreComponentCollection::GetNumberWeights(const FeatureFunction* sp)
{
std::string prefix = sp->GetScoreProducerDescription() + FName::SEP;
size_t weights = 0;
for(FVector::FNVmap::const_iterator i = m_scores.cbegin(); i != m_scores.cend(); i++) {
std::stringstream name;
name << i->first;
if (name.str().substr( 0, prefix.length() ).compare( prefix ) == 0)
weights++;
}
return weights;
}
void ScoreComponentCollection::DivideEquals(float scalar)
{
m_scores /= scalar;
}
void ScoreComponentCollection::CoreDivideEquals(float scalar)
{
m_scores.coreDivideEquals(scalar);
}
void ScoreComponentCollection::DivideEquals(const ScoreComponentCollection& rhs)
{
m_scores.divideEquals(rhs.m_scores);
}
void ScoreComponentCollection::MultiplyEquals(const ScoreComponentCollection& rhs)
{
m_scores *= rhs.m_scores;
}
void ScoreComponentCollection::MultiplyEqualsBackoff(const ScoreComponentCollection& rhs, float backoff)
{
m_scores.multiplyEqualsBackoff(rhs.m_scores, backoff);
}
void ScoreComponentCollection::MultiplyEquals(float core_r0, float sparse_r0)
{
m_scores.multiplyEquals(core_r0, sparse_r0);
}
std::ostream& operator<<(std::ostream& os, const ScoreComponentCollection& rhs)
{
os << rhs.m_scores;
return os;
}
void ScoreComponentCollection::L1Normalise()
{
m_scores /= m_scores.l1norm_coreFeatures();
}
float ScoreComponentCollection::GetL1Norm() const
{
return m_scores.l1norm();
}
float ScoreComponentCollection::GetL2Norm() const
{
return m_scores.l2norm();
}
float ScoreComponentCollection::GetLInfNorm() const
{
return m_scores.linfnorm();
}
size_t ScoreComponentCollection::L1Regularize(float lambda)
{
return m_scores.l1regularize(lambda);
}
void ScoreComponentCollection::L2Regularize(float lambda)
{
m_scores.l2regularize(lambda);
}
size_t ScoreComponentCollection::SparseL1Regularize(float lambda)
{
return m_scores.sparseL1regularize(lambda);
}
void ScoreComponentCollection::SparseL2Regularize(float lambda)
{
m_scores.sparseL2regularize(lambda);
}
void ScoreComponentCollection::Save(ostream& out) const
{
ScoreIndexMap::const_iterator iter = s_scoreIndexes.begin();
for (; iter != s_scoreIndexes.end(); ++iter ) {
string name = iter->first->GetScoreProducerDescription();
IndexPair ip = iter->second; // feature indices
if (ip.second-ip.first == 1) {
out << name << " " << m_scores[ip.first] << endl;
} else {
for (size_t i=ip.first; i < ip.second; ++i) {
ostringstream fullname;
fullname << name << "_" << (i + 1 - ip.first);
out << fullname.str() << " " << m_scores[i] << endl;
}
}
}
// write sparse features
m_scores.write(out);
}
void ScoreComponentCollection::Save(const string& filename) const
{
ofstream out(filename.c_str());
if (!out) {
ostringstream msg;
msg << "Unable to open " << filename;
throw runtime_error(msg.str());
}
Save(out);
out.close();
}
void ScoreComponentCollection::Assign(const FeatureFunction* sp, const string line)
{
istringstream istr(line);
while(istr) {
string namestring;
FValue value;
istr >> namestring;
if (!istr) break;
istr >> value;
FName fname(sp->GetScoreProducerDescription(), namestring);
m_scores[fname] = value;
}
}
void ScoreComponentCollection::ZeroDenseFeatures(const FeatureFunction* sp)
{
size_t numScores = sp->GetNumScoreComponents();
Scores vec(numScores, 0);
Assign(sp, vec);
}
//! get subset of scores that belong to a certain sparse ScoreProducer
FVector ScoreComponentCollection::GetVectorForProducer(const FeatureFunction* sp) const
{
FVector fv(s_denseVectorSize);
std::string prefix = sp->GetScoreProducerDescription() + FName::SEP;
for(FVector::FNVmap::const_iterator i = m_scores.cbegin(); i != m_scores.cend(); i++) {
std::stringstream name;
name << i->first;
if (name.str().substr( 0, prefix.length() ).compare( prefix ) == 0)
fv[i->first] = i->second;
}
return fv;
}
}
<commit_msg>minor debug tweak<commit_after>// $Id$
#include <vector>
#include "ScoreComponentCollection.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
ScoreComponentCollection::ScoreIndexMap ScoreComponentCollection::s_scoreIndexes;
size_t ScoreComponentCollection::s_denseVectorSize = 0;
ScoreComponentCollection::ScoreComponentCollection() : m_scores(s_denseVectorSize)
{}
void ScoreComponentCollection::RegisterScoreProducer
(const FeatureFunction* scoreProducer)
{
size_t start = s_denseVectorSize;
size_t end = start + scoreProducer->GetNumScoreComponents();
VERBOSE(1, "FeatureFunction: " << scoreProducer->GetScoreProducerDescription() << " start: " << start << " end: " << (end-1) << endl);
s_scoreIndexes[scoreProducer] = pair<size_t,size_t>(start,end);
s_denseVectorSize = end;
}
float ScoreComponentCollection::GetWeightedScore() const
{
return m_scores.inner_product(StaticData::Instance().GetAllWeights().m_scores);
}
void ScoreComponentCollection::MultiplyEquals(float scalar)
{
m_scores *= scalar;
}
// Multiply all weights of this sparse producer by a given scalar
void ScoreComponentCollection::MultiplyEquals(const FeatureFunction* sp, float scalar)
{
std::string prefix = sp->GetScoreProducerDescription() + FName::SEP;
for(FVector::FNVmap::const_iterator i = m_scores.cbegin(); i != m_scores.cend(); i++) {
std::stringstream name;
name << i->first;
if (name.str().substr( 0, prefix.length() ).compare( prefix ) == 0)
m_scores[i->first] = i->second * scalar;
}
}
// Count weights belonging to this sparse producer
size_t ScoreComponentCollection::GetNumberWeights(const FeatureFunction* sp)
{
std::string prefix = sp->GetScoreProducerDescription() + FName::SEP;
size_t weights = 0;
for(FVector::FNVmap::const_iterator i = m_scores.cbegin(); i != m_scores.cend(); i++) {
std::stringstream name;
name << i->first;
if (name.str().substr( 0, prefix.length() ).compare( prefix ) == 0)
weights++;
}
return weights;
}
void ScoreComponentCollection::DivideEquals(float scalar)
{
m_scores /= scalar;
}
void ScoreComponentCollection::CoreDivideEquals(float scalar)
{
m_scores.coreDivideEquals(scalar);
}
void ScoreComponentCollection::DivideEquals(const ScoreComponentCollection& rhs)
{
m_scores.divideEquals(rhs.m_scores);
}
void ScoreComponentCollection::MultiplyEquals(const ScoreComponentCollection& rhs)
{
m_scores *= rhs.m_scores;
}
void ScoreComponentCollection::MultiplyEqualsBackoff(const ScoreComponentCollection& rhs, float backoff)
{
m_scores.multiplyEqualsBackoff(rhs.m_scores, backoff);
}
void ScoreComponentCollection::MultiplyEquals(float core_r0, float sparse_r0)
{
m_scores.multiplyEquals(core_r0, sparse_r0);
}
std::ostream& operator<<(std::ostream& os, const ScoreComponentCollection& rhs)
{
os << rhs.m_scores;
return os;
}
void ScoreComponentCollection::L1Normalise()
{
m_scores /= m_scores.l1norm_coreFeatures();
}
float ScoreComponentCollection::GetL1Norm() const
{
return m_scores.l1norm();
}
float ScoreComponentCollection::GetL2Norm() const
{
return m_scores.l2norm();
}
float ScoreComponentCollection::GetLInfNorm() const
{
return m_scores.linfnorm();
}
size_t ScoreComponentCollection::L1Regularize(float lambda)
{
return m_scores.l1regularize(lambda);
}
void ScoreComponentCollection::L2Regularize(float lambda)
{
m_scores.l2regularize(lambda);
}
size_t ScoreComponentCollection::SparseL1Regularize(float lambda)
{
return m_scores.sparseL1regularize(lambda);
}
void ScoreComponentCollection::SparseL2Regularize(float lambda)
{
m_scores.sparseL2regularize(lambda);
}
void ScoreComponentCollection::Save(ostream& out) const
{
ScoreIndexMap::const_iterator iter = s_scoreIndexes.begin();
for (; iter != s_scoreIndexes.end(); ++iter ) {
string name = iter->first->GetScoreProducerDescription();
IndexPair ip = iter->second; // feature indices
if (ip.second-ip.first == 1) {
out << name << " " << m_scores[ip.first] << endl;
} else {
for (size_t i=ip.first; i < ip.second; ++i) {
ostringstream fullname;
fullname << name << "_" << (i + 1 - ip.first);
out << fullname.str() << " " << m_scores[i] << endl;
}
}
}
// write sparse features
m_scores.write(out);
}
void ScoreComponentCollection::Save(const string& filename) const
{
ofstream out(filename.c_str());
if (!out) {
ostringstream msg;
msg << "Unable to open " << filename;
throw runtime_error(msg.str());
}
Save(out);
out.close();
}
void ScoreComponentCollection::Assign(const FeatureFunction* sp, const string line)
{
istringstream istr(line);
while(istr) {
string namestring;
FValue value;
istr >> namestring;
if (!istr) break;
istr >> value;
FName fname(sp->GetScoreProducerDescription(), namestring);
m_scores[fname] = value;
}
}
void ScoreComponentCollection::ZeroDenseFeatures(const FeatureFunction* sp)
{
size_t numScores = sp->GetNumScoreComponents();
Scores vec(numScores, 0);
Assign(sp, vec);
}
//! get subset of scores that belong to a certain sparse ScoreProducer
FVector ScoreComponentCollection::GetVectorForProducer(const FeatureFunction* sp) const
{
FVector fv(s_denseVectorSize);
std::string prefix = sp->GetScoreProducerDescription() + FName::SEP;
for(FVector::FNVmap::const_iterator i = m_scores.cbegin(); i != m_scores.cend(); i++) {
std::stringstream name;
name << i->first;
if (name.str().substr( 0, prefix.length() ).compare( prefix ) == 0)
fv[i->first] = i->second;
}
return fv;
}
}
<|endoftext|>
|
<commit_before>//
// Created by jonas on 10.12.15.
//
#include "image.h"
#if IMAGE_MAGICK
#include <Magick++/Image.h>
#include <Magick++/Montage.h>
#include <Magick++/STL.h>
using namespace Magick;
#elif PNG_LIB
#include <png.h>
#endif
void dump_image( Direction direction )
{
GLint view[4];
glGetIntegerv( GL_VIEWPORT, view );
GLint w = view[2];
GLint h = view[3];
GLbyte* pixels = new GLbyte[3 * w * h];
glPixelStorei( GL_PACK_ALIGNMENT, 1 );
glReadPixels( 0, 0, w, h, GL_RGB, GL_BYTE, pixels );
#if IMAGE_MAGICK
static list<Image> images;
for ( int j = 0; j * 2 < h; ++j )
{
int x = j * w * 3;
int y = (h - 1 - j) * w * 3;
for ( int i = w * 3; i > 0; --i )
{
char tmp = pixels[x];
pixels[x] = pixels[y];
pixels[y] = tmp;
x++;
y++;
}
}
Image image;
image.read( static_cast<const size_t>(w), static_cast<const size_t>(h), "RGB", CharPixel, pixels );
image.transparent( "black" );
image.trim();
images.push_back(image);
if( direction == RIGHT)
{
Montage m;
m.backgroundColor("black");
m.geometry("300x300+2+2");
m.tile("3x2");
m.fileName(mesh->get_name()+".png");
list<Image> mImages;
montageImages(&mImages, images.begin(), images.end(), m);
writeImages(mImages.begin(), mImages.end(), m.fileName());
}
#else
string name = mesh->get_name();
name += to_string( direction );
name += ".png";
save_png( name, pixels, w, h );
#endif
delete[] pixels;
}
#if PNG_LIB
bool save_png( const string& name, GLbyte* pixels, GLint w, GLint h )
{
png_structp png = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
if ( !png )
return false;
png_infop info = png_create_info_struct( png );
if ( !info )
{
png_destroy_write_struct( &png, &info );
return false;
}
FILE* fp = fopen( name.c_str(), "wb" );
if ( !fp )
{
png_destroy_write_struct( &png, &info );
return false;
}
png_init_io( png, fp );
png_set_IHDR( png, info, static_cast<png_uint_32>(w), static_cast<png_uint_32>(h), 8 /* depth */, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE );
png_colorp palette = ( png_colorp ) png_malloc( png, PNG_MAX_PALETTE_LENGTH * sizeof( png_color ));
if ( !palette )
{
fclose( fp );
png_destroy_write_struct( &png, &info );
return false;
}
png_set_PLTE( png, info, palette, PNG_MAX_PALETTE_LENGTH );
png_write_info( png, info );
png_set_packing( png );
png_bytepp rows = ( png_bytepp ) png_malloc( png, h * sizeof( png_bytep ));
for ( int i = 0; i < h; ++i )
rows[i] = ( png_bytep ) (pixels + (h - i - 1) * w * 3);
png_write_image( png, rows );
png_write_end( png, info );
png_free( png, palette );
png_destroy_write_struct( &png, &info );
fclose( fp );
delete[] rows;
return true;
}
#endif
<commit_msg>insert image_path into the image store method<commit_after>//
// Created by jonas on 10.12.15.
//
#include "image.h"
#if IMAGE_MAGICK
#include <Magick++/Image.h>
#include <Magick++/Montage.h>
#include <Magick++/STL.h>
using namespace Magick;
#elif PNG_LIB
#include <png.h>
#endif
void dump_image( Direction direction )
{
GLint view[4];
glGetIntegerv( GL_VIEWPORT, view );
GLint w = view[2];
GLint h = view[3];
GLbyte* pixels = new GLbyte[3 * w * h];
glPixelStorei( GL_PACK_ALIGNMENT, 1 );
glReadPixels( 0, 0, w, h, GL_RGB, GL_BYTE, pixels );
#if IMAGE_MAGICK
static list<Image> images;
for ( int j = 0; j * 2 < h; ++j )
{
int x = j * w * 3;
int y = (h - 1 - j) * w * 3;
for ( int i = w * 3; i > 0; --i )
{
char tmp = pixels[x];
pixels[x] = pixels[y];
pixels[y] = tmp;
x++;
y++;
}
}
Image image;
image.read( static_cast<const size_t>(w), static_cast<const size_t>(h), "RGB", CharPixel, pixels );
image.transparent( "black" );
image.trim();
images.push_back(image);
if( direction == RIGHT)
{
Montage m;
m.backgroundColor("black");
m.geometry("300x300+2+2");
m.tile("3x2");
m.fileName(image_path + "/" + mesh->get_name()+".png");
list<Image> mImages;
montageImages(&mImages, images.begin(), images.end(), m);
writeImages(mImages.begin(), mImages.end(), m.fileName());
}
#else
string name = image_path + "/" + mesh->get_name();
name += to_string( direction );
name += ".png";
save_png( name, pixels, w, h );
#endif
delete[] pixels;
}
#if PNG_LIB
bool save_png( const string& name, GLbyte* pixels, GLint w, GLint h )
{
png_structp png = png_create_write_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
if ( !png )
return false;
png_infop info = png_create_info_struct( png );
if ( !info )
{
png_destroy_write_struct( &png, &info );
return false;
}
FILE* fp = fopen( name.c_str(), "wb" );
if ( !fp )
{
png_destroy_write_struct( &png, &info );
return false;
}
png_init_io( png, fp );
png_set_IHDR( png, info, static_cast<png_uint_32>(w), static_cast<png_uint_32>(h), 8 /* depth */, PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE );
png_colorp palette = ( png_colorp ) png_malloc( png, PNG_MAX_PALETTE_LENGTH * sizeof( png_color ));
if ( !palette )
{
fclose( fp );
png_destroy_write_struct( &png, &info );
return false;
}
png_set_PLTE( png, info, palette, PNG_MAX_PALETTE_LENGTH );
png_write_info( png, info );
png_set_packing( png );
png_bytepp rows = ( png_bytepp ) png_malloc( png, h * sizeof( png_bytep ));
for ( int i = 0; i < h; ++i )
rows[i] = ( png_bytep ) (pixels + (h - i - 1) * w * 3);
png_write_image( png, rows );
png_write_end( png, info );
png_free( png, palette );
png_destroy_write_struct( &png, &info );
fclose( fp );
delete[] rows;
return true;
}
#endif
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#pragma once
#ifndef MODEL_SQUIRREL_HPP
#define MODEL_SQUIRREL_HPP
#include <locale>
#include <algorithm>
#include "json.hpp"
namespace acorn {
/**
*
*/
struct Squirrel : json::Serializable {
size_t key;
Squirrel() : key(0) {}
/**
*
*/
Squirrel(std::string name, size_t age, std::string occupation)
: key {0}
, name_ {name}
, age_ {age}
, occupation_ {occupation}
{}
/**
*
*/
std::string json() const;
/**
*
*/
virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override;
/**
*
*/
virtual bool deserialize(const rapidjson::Document&) override;
/**
*
*/
bool is_equal(const Squirrel&) const;
/**
*
*/
static bool is_equal(const Squirrel&, const Squirrel&);
private:
const std::string name_;
const size_t age_;
const std::string occupation_;
}; //< struct Squirrel
/**--v----------- Implementation Details -----------v--**/
inline void Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const {
writer.StartObject();
writer.Key("key");
writer.Uint(key);
writer.Key("name");
writer.String(name_);
writer.Key("age");
writer.Uint(age_);
writer.Key("occupation");
writer.String(occupation_);
writer.EndObject();
}
inline bool Squirrel::deserialize(const rapidjson::Document& doc) {
name_ = doc["name"].GetString();
age_ = doc["age"].GetUint();
occupation_ = doc["occupation"].GetString();
return true;
}
inline std::string Squirrel::json() const {
using namespace rapidjson;
StringBuffer sb;
Writer<StringBuffer> writer(sb);
serialize(writer);
return sb.GetString();
}
inline bool Squirrel::is_equal(const Squirrel& s) const {
if(name_.size() not_eq s.name_.size()) {
return false;
}
return std::equal(name_.begin(), name_.end(), s.name_.begin(), s.name_.end(),
[](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);
});
}
inline bool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) {
return s1.is_equal(s2);
}
inline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) {
return output_device.json();
}
/**--^----------- Implementation Details -----------^--**/
} //< namespace acorn
#endif //< MODEL_SQUIRREL_HPP
<commit_msg>Corrected error in squirrel output operator<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#pragma once
#ifndef MODEL_SQUIRREL_HPP
#define MODEL_SQUIRREL_HPP
#include <locale>
#include <algorithm>
#include "json.hpp"
namespace acorn {
/**
*
*/
struct Squirrel : json::Serializable {
size_t key;
Squirrel() : key(0) {}
/**
*
*/
Squirrel(std::string name, size_t age, std::string occupation)
: key {0}
, name_ {name}
, age_ {age}
, occupation_ {occupation}
{}
/**
*
*/
std::string json() const;
/**
*
*/
virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override;
/**
*
*/
virtual bool deserialize(const rapidjson::Document&) override;
/**
*
*/
bool is_equal(const Squirrel&) const;
/**
*
*/
static bool is_equal(const Squirrel&, const Squirrel&);
private:
const std::string name_;
const size_t age_;
const std::string occupation_;
}; //< struct Squirrel
/**--v----------- Implementation Details -----------v--**/
inline void Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const {
writer.StartObject();
writer.Key("key");
writer.Uint(key);
writer.Key("name");
writer.String(name_);
writer.Key("age");
writer.Uint(age_);
writer.Key("occupation");
writer.String(occupation_);
writer.EndObject();
}
inline bool Squirrel::deserialize(const rapidjson::Document& doc) {
name_ = doc["name"].GetString();
age_ = doc["age"].GetUint();
occupation_ = doc["occupation"].GetString();
return true;
}
inline std::string Squirrel::json() const {
using namespace rapidjson;
StringBuffer sb;
Writer<StringBuffer> writer(sb);
serialize(writer);
return sb.GetString();
}
inline bool Squirrel::is_equal(const Squirrel& s) const {
if(name_.size() not_eq s.name_.size()) {
return false;
}
return std::equal(name_.begin(), name_.end(), s.name_.begin(), s.name_.end(),
[](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);
});
}
inline bool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) {
return s1.is_equal(s2);
}
inline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) {
return output_device << s.json();
}
/**--^----------- Implementation Details -----------^--**/
} //< namespace acorn
#endif //< MODEL_SQUIRREL_HPP
<|endoftext|>
|
<commit_before>/*
* (C) 2014,2015 Jack Lloyd
* 2016 Matthias Gierlings
* 2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)
#include <botan/tls_client.h>
#include <botan/tls_policy.h>
#include <botan/x509path.h>
#include <botan/ocsp.h>
#include <botan/hex.h>
#include <botan/parsing.h>
#include <fstream>
#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
#include <botan/tls_session_manager_sqlite.h>
#endif
#include <string>
#include <memory>
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
#include <winsock2.h>
#include <WS2tcpip.h>
int close(int fd)
{
return ::closesocket(fd);
}
int read(int s, void* buf, size_t len)
{
return ::recv(s, reinterpret_cast<char*>(buf), static_cast<int>(len), 0);
}
int send(int s, const uint8_t* buf, size_t len, int flags)
{
return ::send(s, reinterpret_cast<const char*>(buf), static_cast<int>(len), flags);
}
#define STDIN_FILENO _fileno(stdin)
typedef size_t ssize_t;
#else
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#endif
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
#include "credentials.h"
namespace Botan_CLI {
class TLS_Client final : public Command, public Botan::TLS::Callbacks
{
public:
TLS_Client()
: Command("tls_client host --port=443 --print-certs --policy= "
"--tls1.0 --tls1.1 --tls1.2 "
"--session-db= --session-db-pass= --next-protocols= --type=tcp")
{
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
WSAData wsa_data;
WORD wsa_version = MAKEWORD(2, 2);
if(::WSAStartup(wsa_version, &wsa_data) != 0)
{
throw CLI_Error("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
}
if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
{
::WSACleanup();
throw CLI_Error("Could not find a usable version of Winsock.dll");
}
#endif
}
~TLS_Client()
{
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
::WSACleanup();
#endif
}
void go() override
{
// TODO client cert auth
std::unique_ptr<Botan::TLS::Session_Manager> session_mgr;
const std::string sessions_db = get_arg("session-db");
if(!sessions_db.empty())
{
#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
const std::string sessions_passphrase = get_arg("session-db-pass");
session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db));
#else
error_output() << "Ignoring session DB file, sqlite not enabled\n";
#endif
}
if(!session_mgr)
{
session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng()));
}
std::string policy_file = get_arg("policy");
std::unique_ptr<Botan::TLS::Policy> policy;
if(policy_file.size() > 0)
{
std::ifstream policy_stream(policy_file);
if(!policy_stream.good())
{
error_output() << "Failed reading policy file\n";
return;
}
policy.reset(new Botan::TLS::Text_Policy(policy_stream));
}
if(!policy)
{
policy.reset(new Botan::TLS::Policy);
}
Basic_Credentials_Manager creds;
const std::string host = get_arg("host");
const uint16_t port = get_arg_sz("port");
const std::string transport = get_arg("type");
const std::string next_protos = get_arg("next-protocols");
if(transport != "tcp" && transport != "udp")
{
throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
}
const bool use_tcp = (transport == "tcp");
const std::vector<std::string> protocols_to_offer = Botan::split_on(next_protos, ',');
m_sockfd = connect_to_host(host, port, use_tcp);
using namespace std::placeholders;
auto version = policy->latest_supported_version(!use_tcp);
if(flag_set("tls1.0"))
{
version = Botan::TLS::Protocol_Version::TLS_V10;
}
else if(flag_set("tls1.1"))
{
version = Botan::TLS::Protocol_Version::TLS_V11;
}
struct sockaddr_storage addrbuf;
std::string hostname;
if(!host.empty() &&
inet_pton(AF_INET, host.c_str(), &addrbuf) != 1 &&
inet_pton(AF_INET6, host.c_str(), &addrbuf) != 1)
{
hostname = host;
}
Botan::TLS::Client client(*this, *session_mgr, creds, *policy, rng(),
Botan::TLS::Server_Information(hostname, port),
version, protocols_to_offer);
bool first_active = true;
while(!client.is_closed())
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(m_sockfd, &readfds);
if(client.is_active())
{
FD_SET(STDIN_FILENO, &readfds);
if(first_active && !protocols_to_offer.empty())
{
std::string app = client.application_protocol();
if(app != "")
{
output() << "Server choose protocol: " << client.application_protocol() << "\n";
}
first_active = false;
}
}
struct timeval timeout = { 1, 0 };
::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout);
if(FD_ISSET(m_sockfd, &readfds))
{
uint8_t buf[4 * 1024] = { 0 };
ssize_t got = ::read(m_sockfd, buf, sizeof(buf));
if(got == 0)
{
output() << "EOF on socket\n";
break;
}
else if(got == -1)
{
output() << "Socket error: " << errno << " " << std::strerror(errno) << "\n";
continue;
}
client.received_data(buf, got);
}
if(FD_ISSET(STDIN_FILENO, &readfds))
{
uint8_t buf[1024] = { 0 };
ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));
if(got == 0)
{
output() << "EOF on stdin\n";
client.close();
break;
}
else if(got == -1)
{
output() << "Stdin error: " << errno << " " << std::strerror(errno) << "\n";
continue;
}
if(got == 2 && buf[1] == '\n')
{
char cmd = buf[0];
if(cmd == 'R' || cmd == 'r')
{
output() << "Client initiated renegotiation\n";
client.renegotiate(cmd == 'R');
}
else if(cmd == 'Q')
{
output() << "Client initiated close\n";
client.close();
}
}
else
{
client.send(buf, got);
}
}
if(client.timeout_check())
{
output() << "Timeout detected\n";
}
}
::close(m_sockfd);
}
private:
int connect_to_host(const std::string& host, uint16_t port, bool tcp)
{
addrinfo hints = {};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
addrinfo* res, *rp = nullptr;
if(::getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0)
{
throw CLI_Error("getaddrinfo failed for " + host);
}
int fd = 0;
for(rp = res; rp != nullptr; rp = rp->ai_next)
{
fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if(fd == -1)
{
continue;
}
if(::connect(fd, rp->ai_addr, rp->ai_addrlen) != 0)
{
::close(fd);
continue;
}
break;
}
::freeaddrinfo(res);
if(rp == nullptr) // no address succeeded
{
throw CLI_Error("connect failed");
}
return fd;
}
void tls_verify_cert_chain(
const std::vector<Botan::X509_Certificate>& cert_chain,
const std::vector<std::shared_ptr<const Botan::OCSP::Response>>& ocsp,
const std::vector<Botan::Certificate_Store*>& trusted_roots,
Botan::Usage_Type usage,
const std::string& hostname,
const Botan::TLS::Policy& policy) override
{
if(cert_chain.empty())
{
throw std::invalid_argument("Certificate chain was empty");
}
Botan::Path_Validation_Restrictions restrictions(
policy.require_cert_revocation_info(),
policy.minimum_signature_strength());
auto ocsp_timeout = std::chrono::milliseconds(1000);
Botan::Path_Validation_Result result = Botan::x509_path_validate(
cert_chain,
restrictions,
trusted_roots,
hostname,
usage,
std::chrono::system_clock::now(),
ocsp_timeout,
ocsp);
output() << "Certificate validation status: " << result.result_string() << "\n";
if(result.successful_validation())
{
auto status = result.all_statuses();
if(status.size() > 0 && status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD))
{
output() << "Valid OCSP response for this server\n";
}
}
}
bool tls_session_established(const Botan::TLS::Session& session) override
{
output() << "Handshake complete, " << session.version().to_string()
<< " using " << session.ciphersuite().to_string() << "\n";
if(!session.session_id().empty())
{
output() << "Session ID " << Botan::hex_encode(session.session_id()) << "\n";
}
if(!session.session_ticket().empty())
{
output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << "\n";
}
if(flag_set("print-certs"))
{
const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();
for(size_t i = 0; i != certs.size(); ++i)
{
output() << "Certificate " << i + 1 << "/" << certs.size() << "\n";
output() << certs[i].to_string();
output() << certs[i].PEM_encode();
}
}
return true;
}
static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length)
{
int r = ::send(sockfd, buf, length, MSG_NOSIGNAL);
if(r == -1)
{
throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
}
}
void tls_emit_data(const uint8_t buf[], size_t length) override
{
size_t offset = 0;
while(length)
{
ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL);
if(sent == -1)
{
if(errno == EINTR)
{
sent = 0;
}
else
{
throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
}
}
offset += sent;
length -= sent;
}
}
void tls_alert(Botan::TLS::Alert alert) override
{
output() << "Alert: " << alert.type_string() << "\n";
}
void tls_record_received(uint64_t /*seq_no*/, const uint8_t buf[], size_t buf_size) override
{
for(size_t i = 0; i != buf_size; ++i)
{
output() << buf[i];
}
}
private:
int m_sockfd = -1;
};
BOTAN_REGISTER_COMMAND("tls_client", TLS_Client);
}
#endif
<commit_msg>Avoid uninitialized field warnings<commit_after>/*
* (C) 2014,2015 Jack Lloyd
* 2016 Matthias Gierlings
* 2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include "cli.h"
#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)
#include <botan/tls_client.h>
#include <botan/tls_policy.h>
#include <botan/x509path.h>
#include <botan/ocsp.h>
#include <botan/hex.h>
#include <botan/parsing.h>
#include <fstream>
#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
#include <botan/tls_session_manager_sqlite.h>
#endif
#include <string>
#include <memory>
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
#include <winsock2.h>
#include <WS2tcpip.h>
int close(int fd)
{
return ::closesocket(fd);
}
int read(int s, void* buf, size_t len)
{
return ::recv(s, reinterpret_cast<char*>(buf), static_cast<int>(len), 0);
}
int send(int s, const uint8_t* buf, size_t len, int flags)
{
return ::send(s, reinterpret_cast<const char*>(buf), static_cast<int>(len), flags);
}
#define STDIN_FILENO _fileno(stdin)
typedef size_t ssize_t;
#else
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#endif
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
#include "credentials.h"
namespace Botan_CLI {
class TLS_Client final : public Command, public Botan::TLS::Callbacks
{
public:
TLS_Client()
: Command("tls_client host --port=443 --print-certs --policy= "
"--tls1.0 --tls1.1 --tls1.2 "
"--session-db= --session-db-pass= --next-protocols= --type=tcp")
{
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
WSAData wsa_data;
WORD wsa_version = MAKEWORD(2, 2);
if(::WSAStartup(wsa_version, &wsa_data) != 0)
{
throw CLI_Error("WSAStartup() failed: " + std::to_string(WSAGetLastError()));
}
if(LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
{
::WSACleanup();
throw CLI_Error("Could not find a usable version of Winsock.dll");
}
#endif
}
~TLS_Client()
{
#if defined(BOTAN_TARGET_OS_IS_WINDOWS)
::WSACleanup();
#endif
}
void go() override
{
// TODO client cert auth
std::unique_ptr<Botan::TLS::Session_Manager> session_mgr;
const std::string sessions_db = get_arg("session-db");
if(!sessions_db.empty())
{
#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)
const std::string sessions_passphrase = get_arg("session-db-pass");
session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db));
#else
error_output() << "Ignoring session DB file, sqlite not enabled\n";
#endif
}
if(!session_mgr)
{
session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng()));
}
std::string policy_file = get_arg("policy");
std::unique_ptr<Botan::TLS::Policy> policy;
if(policy_file.size() > 0)
{
std::ifstream policy_stream(policy_file);
if(!policy_stream.good())
{
error_output() << "Failed reading policy file\n";
return;
}
policy.reset(new Botan::TLS::Text_Policy(policy_stream));
}
if(!policy)
{
policy.reset(new Botan::TLS::Policy);
}
Basic_Credentials_Manager creds;
const std::string host = get_arg("host");
const uint16_t port = get_arg_sz("port");
const std::string transport = get_arg("type");
const std::string next_protos = get_arg("next-protocols");
if(transport != "tcp" && transport != "udp")
{
throw CLI_Usage_Error("Invalid transport type '" + transport + "' for TLS");
}
const bool use_tcp = (transport == "tcp");
const std::vector<std::string> protocols_to_offer = Botan::split_on(next_protos, ',');
m_sockfd = connect_to_host(host, port, use_tcp);
using namespace std::placeholders;
auto version = policy->latest_supported_version(!use_tcp);
if(flag_set("tls1.0"))
{
version = Botan::TLS::Protocol_Version::TLS_V10;
}
else if(flag_set("tls1.1"))
{
version = Botan::TLS::Protocol_Version::TLS_V11;
}
struct sockaddr_storage addrbuf;
std::string hostname;
if(!host.empty() &&
inet_pton(AF_INET, host.c_str(), &addrbuf) != 1 &&
inet_pton(AF_INET6, host.c_str(), &addrbuf) != 1)
{
hostname = host;
}
Botan::TLS::Client client(*this, *session_mgr, creds, *policy, rng(),
Botan::TLS::Server_Information(hostname, port),
version, protocols_to_offer);
bool first_active = true;
while(!client.is_closed())
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(m_sockfd, &readfds);
if(client.is_active())
{
FD_SET(STDIN_FILENO, &readfds);
if(first_active && !protocols_to_offer.empty())
{
std::string app = client.application_protocol();
if(app != "")
{
output() << "Server choose protocol: " << client.application_protocol() << "\n";
}
first_active = false;
}
}
struct timeval timeout = { 1, 0 };
::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout);
if(FD_ISSET(m_sockfd, &readfds))
{
uint8_t buf[4 * 1024] = { 0 };
ssize_t got = ::read(m_sockfd, buf, sizeof(buf));
if(got == 0)
{
output() << "EOF on socket\n";
break;
}
else if(got == -1)
{
output() << "Socket error: " << errno << " " << std::strerror(errno) << "\n";
continue;
}
client.received_data(buf, got);
}
if(FD_ISSET(STDIN_FILENO, &readfds))
{
uint8_t buf[1024] = { 0 };
ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));
if(got == 0)
{
output() << "EOF on stdin\n";
client.close();
break;
}
else if(got == -1)
{
output() << "Stdin error: " << errno << " " << std::strerror(errno) << "\n";
continue;
}
if(got == 2 && buf[1] == '\n')
{
char cmd = buf[0];
if(cmd == 'R' || cmd == 'r')
{
output() << "Client initiated renegotiation\n";
client.renegotiate(cmd == 'R');
}
else if(cmd == 'Q')
{
output() << "Client initiated close\n";
client.close();
}
}
else
{
client.send(buf, got);
}
}
if(client.timeout_check())
{
output() << "Timeout detected\n";
}
}
::close(m_sockfd);
}
private:
int connect_to_host(const std::string& host, uint16_t port, bool tcp)
{
addrinfo hints;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
addrinfo* res, *rp = nullptr;
if(::getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0)
{
throw CLI_Error("getaddrinfo failed for " + host);
}
int fd = 0;
for(rp = res; rp != nullptr; rp = rp->ai_next)
{
fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if(fd == -1)
{
continue;
}
if(::connect(fd, rp->ai_addr, rp->ai_addrlen) != 0)
{
::close(fd);
continue;
}
break;
}
::freeaddrinfo(res);
if(rp == nullptr) // no address succeeded
{
throw CLI_Error("connect failed");
}
return fd;
}
void tls_verify_cert_chain(
const std::vector<Botan::X509_Certificate>& cert_chain,
const std::vector<std::shared_ptr<const Botan::OCSP::Response>>& ocsp,
const std::vector<Botan::Certificate_Store*>& trusted_roots,
Botan::Usage_Type usage,
const std::string& hostname,
const Botan::TLS::Policy& policy) override
{
if(cert_chain.empty())
{
throw std::invalid_argument("Certificate chain was empty");
}
Botan::Path_Validation_Restrictions restrictions(
policy.require_cert_revocation_info(),
policy.minimum_signature_strength());
auto ocsp_timeout = std::chrono::milliseconds(1000);
Botan::Path_Validation_Result result = Botan::x509_path_validate(
cert_chain,
restrictions,
trusted_roots,
hostname,
usage,
std::chrono::system_clock::now(),
ocsp_timeout,
ocsp);
output() << "Certificate validation status: " << result.result_string() << "\n";
if(result.successful_validation())
{
auto status = result.all_statuses();
if(status.size() > 0 && status[0].count(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD))
{
output() << "Valid OCSP response for this server\n";
}
}
}
bool tls_session_established(const Botan::TLS::Session& session) override
{
output() << "Handshake complete, " << session.version().to_string()
<< " using " << session.ciphersuite().to_string() << "\n";
if(!session.session_id().empty())
{
output() << "Session ID " << Botan::hex_encode(session.session_id()) << "\n";
}
if(!session.session_ticket().empty())
{
output() << "Session ticket " << Botan::hex_encode(session.session_ticket()) << "\n";
}
if(flag_set("print-certs"))
{
const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();
for(size_t i = 0; i != certs.size(); ++i)
{
output() << "Certificate " << i + 1 << "/" << certs.size() << "\n";
output() << certs[i].to_string();
output() << certs[i].PEM_encode();
}
}
return true;
}
static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length)
{
int r = ::send(sockfd, buf, length, MSG_NOSIGNAL);
if(r == -1)
{
throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
}
}
void tls_emit_data(const uint8_t buf[], size_t length) override
{
size_t offset = 0;
while(length)
{
ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL);
if(sent == -1)
{
if(errno == EINTR)
{
sent = 0;
}
else
{
throw CLI_Error("Socket write failed errno=" + std::to_string(errno));
}
}
offset += sent;
length -= sent;
}
}
void tls_alert(Botan::TLS::Alert alert) override
{
output() << "Alert: " << alert.type_string() << "\n";
}
void tls_record_received(uint64_t /*seq_no*/, const uint8_t buf[], size_t buf_size) override
{
for(size_t i = 0; i != buf_size; ++i)
{
output() << buf[i];
}
}
private:
int m_sockfd = -1;
};
BOTAN_REGISTER_COMMAND("tls_client", TLS_Client);
}
#endif
<|endoftext|>
|
<commit_before>//===--- SIL.cpp - Implements random SIL functionality --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILUndef.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/ClangImporter/ClangModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
using namespace swift;
SILUndef *SILUndef::get(SILType Ty, SILModule *M) {
// Unique these.
SILUndef *&Entry = M->UndefValues[Ty];
if (Entry == nullptr)
Entry = new (*M) SILUndef(Ty);
return Entry;
}
FormalLinkage swift::getDeclLinkage(const ValueDecl *D) {
const DeclContext *fileContext = D->getDeclContext()->getModuleScopeContext();
// Clang declarations are public and can't be assured of having a
// unique defining location.
if (isa<ClangModuleUnit>(fileContext))
return FormalLinkage::PublicNonUnique;
if (!D->hasAccess()) {
assert(D->getDeclContext()->isLocalContext());
return FormalLinkage::Private;
}
switch (D->getEffectiveAccess()) {
case AccessLevel::Public:
case AccessLevel::Open:
return FormalLinkage::PublicUnique;
case AccessLevel::Internal:
return FormalLinkage::HiddenUnique;
case AccessLevel::FilePrivate:
case AccessLevel::Private:
return FormalLinkage::Private;
}
llvm_unreachable("Unhandled access level in switch.");
}
SILLinkage swift::getSILLinkage(FormalLinkage linkage,
ForDefinition_t forDefinition) {
switch (linkage) {
case FormalLinkage::PublicUnique:
return (forDefinition ? SILLinkage::Public : SILLinkage::PublicExternal);
case FormalLinkage::PublicNonUnique:
// FIXME: any place we have to do this that actually requires
// uniqueness is buggy.
return (forDefinition ? SILLinkage::Shared : SILLinkage::PublicExternal);
case FormalLinkage::HiddenUnique:
return (forDefinition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);
case FormalLinkage::Private:
return SILLinkage::Private;
}
llvm_unreachable("bad formal linkage");
}
SILLinkage
swift::getLinkageForProtocolConformance(const NormalProtocolConformance *C,
ForDefinition_t definition) {
// Behavior conformances are always private.
if (C->isBehaviorConformance())
return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);
// If the conformance was synthesized by the ClangImporter, give it
// shared linkage.
if (isa<ClangModuleUnit>(C->getDeclContext()->getModuleScopeContext()))
return SILLinkage::Shared;
auto typeDecl = C->getType()->getNominalOrBoundGenericNominal();
AccessLevel access = std::min(C->getProtocol()->getEffectiveAccess(),
typeDecl->getEffectiveAccess());
switch (access) {
case AccessLevel::Private:
case AccessLevel::FilePrivate:
return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);
case AccessLevel::Internal:
return (definition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);
default:
return (definition ? SILLinkage::Public : SILLinkage::PublicExternal);
}
}
<commit_msg>SIL: All declarations have access after type checking<commit_after>//===--- SIL.cpp - Implements random SIL functionality --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILUndef.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/ClangImporter/ClangModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
using namespace swift;
SILUndef *SILUndef::get(SILType Ty, SILModule *M) {
// Unique these.
SILUndef *&Entry = M->UndefValues[Ty];
if (Entry == nullptr)
Entry = new (*M) SILUndef(Ty);
return Entry;
}
FormalLinkage swift::getDeclLinkage(const ValueDecl *D) {
const DeclContext *fileContext = D->getDeclContext()->getModuleScopeContext();
// Clang declarations are public and can't be assured of having a
// unique defining location.
if (isa<ClangModuleUnit>(fileContext))
return FormalLinkage::PublicNonUnique;
switch (D->getEffectiveAccess()) {
case AccessLevel::Public:
case AccessLevel::Open:
return FormalLinkage::PublicUnique;
case AccessLevel::Internal:
return FormalLinkage::HiddenUnique;
case AccessLevel::FilePrivate:
case AccessLevel::Private:
return FormalLinkage::Private;
}
llvm_unreachable("Unhandled access level in switch.");
}
SILLinkage swift::getSILLinkage(FormalLinkage linkage,
ForDefinition_t forDefinition) {
switch (linkage) {
case FormalLinkage::PublicUnique:
return (forDefinition ? SILLinkage::Public : SILLinkage::PublicExternal);
case FormalLinkage::PublicNonUnique:
// FIXME: any place we have to do this that actually requires
// uniqueness is buggy.
return (forDefinition ? SILLinkage::Shared : SILLinkage::PublicExternal);
case FormalLinkage::HiddenUnique:
return (forDefinition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);
case FormalLinkage::Private:
return SILLinkage::Private;
}
llvm_unreachable("bad formal linkage");
}
SILLinkage
swift::getLinkageForProtocolConformance(const NormalProtocolConformance *C,
ForDefinition_t definition) {
// Behavior conformances are always private.
if (C->isBehaviorConformance())
return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);
// If the conformance was synthesized by the ClangImporter, give it
// shared linkage.
if (isa<ClangModuleUnit>(C->getDeclContext()->getModuleScopeContext()))
return SILLinkage::Shared;
auto typeDecl = C->getType()->getNominalOrBoundGenericNominal();
AccessLevel access = std::min(C->getProtocol()->getEffectiveAccess(),
typeDecl->getEffectiveAccess());
switch (access) {
case AccessLevel::Private:
case AccessLevel::FilePrivate:
return (definition ? SILLinkage::Private : SILLinkage::PrivateExternal);
case AccessLevel::Internal:
return (definition ? SILLinkage::Hidden : SILLinkage::HiddenExternal);
default:
return (definition ? SILLinkage::Public : SILLinkage::PublicExternal);
}
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// 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. //
// ======================================================================== //
#undef NDEBUG
// O_LARGEFILE is a GNU extension.
#ifdef __APPLE__
#define O_LARGEFILE 0
#endif
// sg
#include "SceneGraph.h"
#include "sg/common/Texture2D.h"
#include "sg/geometry/TriangleMesh.h"
//
#include "../3rdParty/ply.h"
namespace ospray {
namespace sg {
#if 0
namespace ply {
using std::string;
using std::cout;
using std::endl;
#define FALSE 0
#define TRUE 1
#define X 0
#define Y 1
#define Z 2
enum {
FACE_INDICES = 0,
FACE_RED,
FACE_GREEN,
FACE_BLUE
};
typedef float Point[3];
typedef float Vector[3];
typedef struct Vertex {
int id;
Point coord; /* coordinates of vertex */
Point normal; /* normal of vertex */
unsigned char red;
unsigned char green;
unsigned char blue;
unsigned char nfaces; /* number of face indices in list */
int *faces; /* face index list */
void *other_props; /* other properties */
} Vertex;
typedef struct Face {
int id;
unsigned char nverts; /* number of vertex indices in list */
int *verts; /* vertex index list */
unsigned char red;
unsigned char green;
unsigned char blue;
void *other_props; /* other properties */
} Face;
PlyProperty vert_props[] = { /* list of property information for a vertex */
{(char*)"x", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[X]), 0, 0, 0, 0},
{(char*)"y", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Y]), 0, 0, 0, 0},
{(char*)"z", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Z]), 0, 0, 0, 0},
{(char*)"nx", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[X]), 0, 0, 0, 0},
{(char*)"ny", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Y]), 0, 0, 0, 0},
{(char*)"nz", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Z]), 0, 0, 0, 0},
{(char*)"diffuse_red", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,red), 0, 0, 0, 0},
{(char*)"diffuse_green", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,green), 0, 0, 0, 0},
{(char*)"diffuse_blue", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,blue), 0, 0, 0, 0},
};
enum {
VTX_X = 0,
VTX_Y,
VTX_Z,
VTX_NX,
VTX_NY,
VTX_NZ,
VTX_RED,
VTX_GREEN,
VTX_BLUE
};
PlyProperty face_props[] = { /* list of property information for a face */
{(char*)"vertex_indices", PLY_INT, PLY_INT, offsetof(Face,verts),
1, PLY_UCHAR, PLY_UCHAR, offsetof(Face,nverts)},
{(char*)"red", PLY_UCHAR, PLY_UCHAR, offsetof(Face,red), 0, 0, 0, 0},
{(char*)"green", PLY_UCHAR, PLY_UCHAR, offsetof(Face,green), 0, 0, 0, 0},
{(char*)"blue", PLY_UCHAR, PLY_UCHAR, offsetof(Face,blue), 0, 0, 0, 0},
};
void readFile(const std::string &fileName, std::shared_ptr<sg::TriangleMesh> mesh)
{
int nprops;
PlyProperty **plist;
float version;
int vertices = 0;
int triangles = 0;
int has_x, has_y, has_z;
int has_face_red=0; // face colors
int has_face_green=0; // face colors
int has_face_blue=0; // face colors
int has_vertex_red=0; // vertex colors
int has_vertex_green=0; // vertex colors
int has_vertex_blue=0; // vertex colors
int has_nx=0, has_ny=0, has_nz=0;
int has_fverts=0;
PlyOtherElems *other_elements = NULL;
PlyOtherProp *vert_other,*face_other;//,*edge_other;
char **element_list = NULL;
int file_type = 0;
std::shared_ptr<sg::DataVector3f> pos = std::make_shared<sg::DataVector3f>();
std::shared_ptr<sg::DataVector3f> nor = std::make_shared<sg::DataVector3f>();
std::shared_ptr<sg::DataVector3i> idx = std::make_shared<sg::DataVector3i>();
/*** Read in the original PLY object ***/
const char *filename = fileName.c_str();
FILE *file;
bool isPipe = false;
if (strlen(filename) > 7 && !strcmp(filename+strlen(filename)-7,".ply.gz")) {
#ifdef _WIN32
THROW_SG_ERROR("#osp:sg:ply: gzipped file not supported yet on Windows");
#else
isPipe = true;
char cmd[10000];
sprintf(cmd,"/usr/bin/gunzip -c %s",filename);
file = popen(cmd,"r");
#endif
} else
file = fopen(filename,"rb");
if (!file)
throw std::runtime_error("#osp:sg:ply: could not open '"+fileName+"'");
int nelems = -1;
PlyFile *ply = ply_read (file, &nelems, &element_list);
ply_get_info (ply, &version, &file_type);
for (int i=0; i<nelems; i++) {
int num_elems;
/* get the description of the first element */
char *elem_name = element_list[i];
plist = ply_get_element_description (ply, elem_name, &num_elems, &nprops);
if (equal_strings ("vertex", elem_name)) {
/* create a vertex list to hold all the vertices */
/* set up for getting vertex elements */
/* verify which properties these vertices have */
has_x = has_y = has_z = FALSE;
has_nx = has_ny = has_nz = FALSE;
for (int j=0; j<nprops; j++) {
if (equal_strings("x", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_X]); /* x */
has_x = TRUE;
} else if (equal_strings("y", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_Y]); /* y */
has_y = TRUE;
} else if (equal_strings("z", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_Z]); /* z */
has_z = TRUE;
}
if (equal_strings("nx", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_NX]); /* x */
has_nx = TRUE;
} else if (equal_strings("ny", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_NY]); /* y */
has_ny = TRUE;
} else if (equal_strings("nz", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_NZ]); /* z */
has_nz = TRUE;
} else if (equal_strings("diffuse_red", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_RED]); /* z */
has_vertex_red = TRUE;
} else if (equal_strings("diffuse_green", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_GREEN]); /* z */
has_vertex_green = TRUE;
} else if (equal_strings("diffuse_blue", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_BLUE]); /* z */
has_vertex_blue = TRUE;
}
}
vert_other = ply_get_other_properties (ply, elem_name,
offsetof(Vertex,other_props));
/* test for necessary properties */
if ((!has_x) || (!has_y) || (!has_z))
{
fprintf(stderr, "Vertices don't have x, y, and z\n");
exit(-1);
}
vertices = num_elems;
if (has_nx && has_ny && has_nz)
nor->v.resize(vertices);
pos->v.resize(vertices);
/* grab all the vertex elements */
for (int j=0; j<vertices; j++) {
Vertex tmp;
ply_get_element (ply, (void *) &tmp);
pos->v[j] = vec3f(tmp.coord[0],tmp.coord[1],tmp.coord[2]);
if (has_nx && has_ny && has_nz)
nor->v[j] = vec3f(tmp.normal[0],tmp.normal[1],tmp.normal[2]);
}
} else if (equal_strings ("face", elem_name)) {
/* create a list to hold all the face elements */
cout << "num faces : " << (num_elems) << endl;
/* set up for getting face elements */
/* verify which properties these vertices have */
has_fverts = FALSE;
for (int j=0; j<nprops; j++) {
if (equal_strings("vertex_indices", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_INDICES]);/* vertex_indices */
has_fverts = TRUE;
} else if (equal_strings("red", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_RED]);/* vertex_indices */
has_face_red = TRUE;
} else if (equal_strings("green", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_GREEN]);/* vertex_indices */
has_face_green = TRUE;
} else if (equal_strings("blue", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_BLUE]);/* vertex_indices */
has_face_blue = TRUE;
}
}
face_other = ply_get_other_properties (ply, elem_name,
offsetof(Face,other_props));
/* test for necessary properties */
if (!has_fverts) {
fprintf(stderr, "Faces must have vertex indices\n");
exit(-1);
}
triangles = num_elems;
// numTrisWritten += num_elems;
/* grab all the face elements */
Face tmp;
tmp.verts = NULL;
tmp.other_props = NULL;
for (int j=0; j<num_elems; j++) {
ply_get_element (ply, (void *) &tmp);
if (!has_face_blue) {
tmp.red = tmp.green = tmp.blue = 255;
}
if (tmp.nverts == 3) {
// if (has_face_blue)
// material = getMaterial(tmp.red,tmp.green,tmp.blue);;
vec3i vtx;
vtx.x = tmp.verts[0]; //builder.addVertex(pos[tmp.verts[0]]);
vtx.y = tmp.verts[1]; //builder.addVertex(pos[tmp.verts[1]]);
vtx.z = tmp.verts[2]; //builder.addVertex(pos[tmp.verts[2]]);
idx->v.push_back(vtx);
} else {
PRINT((int)tmp.nverts);
FATAL("can only read ply files made up of triangles...");
}
free(tmp.verts);
if (tmp.other_props) free(tmp.other_props);
}
}
else {
other_elements = ply_get_other_element (ply, elem_name, num_elems);
ply_free_other_elements(other_elements);
}
}
int num_comments;
char **comments;
// PlyOtherProp *vert_other,*face_other;//,*edge_other;
int num_obj_info;
char **obj_info;
comments = ply_get_comments (ply, &num_comments);
obj_info = ply_get_obj_info (ply, &num_obj_info);
ply_close (ply);
for (int i=0;i<ply->nelems;i++) {
if (ply->elems[i]) continue;
PlyElement *e = ply->elems[i];
FREE(e->name);
FREE(e->store_prop);
if (e->props) {
for (int j=0;j<e->nprops;j++) {
PlyProperty *p = e->props[j];
if (!e) continue;
FREE(p->name);
FREE(p);
}
FREE(e->props);
}
FREE(e);
}
free(ply->elems);
mesh->index = idx;
mesh->vertex = pos;
if (!nor->v.empty())
mesh->normal = nor;
}
} // ::ospray::sg::ply
#endif
void importPLY(std::shared_ptr<Node> &world, const FileName &fileName)
{
#if 0
std::shared_ptr<sg::TriangleMesh> mesh =
std::static_pointer_cast<sg::TriangleMesh>(sg::createNode(fileName.name(), "TriangleMesh"));
ply::readFile(fileName.str(), mesh);
world->add(std::dynamic_pointer_cast<sg::Node>(mesh));
#endif
}
} // ::ospray::sg
} // ::ospray
<commit_msg>re-enable and fix PLY sg importer<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// 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. //
// ======================================================================== //
#undef NDEBUG
// O_LARGEFILE is a GNU extension.
#ifdef __APPLE__
#define O_LARGEFILE 0
#endif
// sg
#include "SceneGraph.h"
#include "sg/common/Texture2D.h"
#include "sg/geometry/TriangleMesh.h"
//
#include "../3rdParty/ply.h"
namespace ospray {
namespace sg {
namespace ply {
using std::string;
using std::cout;
using std::endl;
#define FALSE 0
#define TRUE 1
#define X 0
#define Y 1
#define Z 2
enum {
FACE_INDICES = 0,
FACE_RED,
FACE_GREEN,
FACE_BLUE
};
typedef float Point[3];
typedef float Vector[3];
typedef struct Vertex {
int id;
Point coord; /* coordinates of vertex */
Point normal; /* normal of vertex */
unsigned char red;
unsigned char green;
unsigned char blue;
unsigned char nfaces; /* number of face indices in list */
int *faces; /* face index list */
void *other_props; /* other properties */
} Vertex;
typedef struct Face {
int id;
unsigned char nverts; /* number of vertex indices in list */
int *verts; /* vertex index list */
unsigned char red;
unsigned char green;
unsigned char blue;
void *other_props; /* other properties */
} Face;
PlyProperty vert_props[] = { /* list of property information for a vertex */
{(char*)"x", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[X]), 0, 0, 0, 0},
{(char*)"y", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Y]), 0, 0, 0, 0},
{(char*)"z", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,coord[Z]), 0, 0, 0, 0},
{(char*)"nx", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[X]), 0, 0, 0, 0},
{(char*)"ny", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Y]), 0, 0, 0, 0},
{(char*)"nz", PLY_FLOAT, PLY_FLOAT, offsetof(::ospray::sg::ply::Vertex,normal[Z]), 0, 0, 0, 0},
{(char*)"diffuse_red", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,red), 0, 0, 0, 0},
{(char*)"diffuse_green", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,green), 0, 0, 0, 0},
{(char*)"diffuse_blue", PLY_UCHAR, PLY_UCHAR, offsetof(::ospray::sg::ply::Vertex,blue), 0, 0, 0, 0},
};
enum {
VTX_X = 0,
VTX_Y,
VTX_Z,
VTX_NX,
VTX_NY,
VTX_NZ,
VTX_RED,
VTX_GREEN,
VTX_BLUE
};
PlyProperty face_props[] = { /* list of property information for a face */
{(char*)"vertex_indices", PLY_INT, PLY_INT, offsetof(Face,verts),
1, PLY_UCHAR, PLY_UCHAR, offsetof(Face,nverts)},
{(char*)"red", PLY_UCHAR, PLY_UCHAR, offsetof(Face,red), 0, 0, 0, 0},
{(char*)"green", PLY_UCHAR, PLY_UCHAR, offsetof(Face,green), 0, 0, 0, 0},
{(char*)"blue", PLY_UCHAR, PLY_UCHAR, offsetof(Face,blue), 0, 0, 0, 0},
};
void readFile(const std::string &fileName, std::shared_ptr<sg::TriangleMesh> mesh)
{
int nprops;
PlyProperty **plist;
float version;
int vertices = 0;
int triangles = 0;
int has_x, has_y, has_z;
int has_face_red=0; // face colors
int has_face_green=0; // face colors
int has_face_blue=0; // face colors
int has_vertex_red=0; // vertex colors
int has_vertex_green=0; // vertex colors
int has_vertex_blue=0; // vertex colors
int has_nx=0, has_ny=0, has_nz=0;
int has_fverts=0;
PlyOtherElems *other_elements = NULL;
PlyOtherProp *vert_other,*face_other;//,*edge_other;
char **element_list = NULL;
int file_type = 0;
auto pos = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
auto nor = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>();
auto idx = createNode("index", "DataVector3i")->nodeAs<DataVector3i>();
/*** Read in the original PLY object ***/
const char *filename = fileName.c_str();
FILE *file;
bool isPipe = false;
if (strlen(filename) > 7 && !strcmp(filename+strlen(filename)-7,".ply.gz")) {
#ifdef _WIN32
THROW_SG_ERROR("#osp:sg:ply: gzipped file not supported yet on Windows");
#else
isPipe = true;
char cmd[10000];
sprintf(cmd,"/usr/bin/gunzip -c %s",filename);
file = popen(cmd,"r");
#endif
} else
file = fopen(filename,"rb");
if (!file)
throw std::runtime_error("#osp:sg:ply: could not open '"+fileName+"'");
int nelems = -1;
PlyFile *ply = ply_read (file, &nelems, &element_list);
ply_get_info (ply, &version, &file_type);
for (int i=0; i<nelems; i++) {
int num_elems;
/* get the description of the first element */
char *elem_name = element_list[i];
plist = ply_get_element_description (ply, elem_name, &num_elems, &nprops);
if (equal_strings ("vertex", elem_name)) {
/* create a vertex list to hold all the vertices */
/* set up for getting vertex elements */
/* verify which properties these vertices have */
has_x = has_y = has_z = FALSE;
has_nx = has_ny = has_nz = FALSE;
for (int j=0; j<nprops; j++) {
if (equal_strings("x", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_X]); /* x */
has_x = TRUE;
} else if (equal_strings("y", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_Y]); /* y */
has_y = TRUE;
} else if (equal_strings("z", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_Z]); /* z */
has_z = TRUE;
}
if (equal_strings("nx", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_NX]); /* x */
has_nx = TRUE;
} else if (equal_strings("ny", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_NY]); /* y */
has_ny = TRUE;
} else if (equal_strings("nz", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_NZ]); /* z */
has_nz = TRUE;
} else if (equal_strings("diffuse_red", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_RED]); /* z */
has_vertex_red = TRUE;
} else if (equal_strings("diffuse_green", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_GREEN]); /* z */
has_vertex_green = TRUE;
} else if (equal_strings("diffuse_blue", plist[j]->name)) {
ply_get_property (ply, elem_name, &vert_props[VTX_BLUE]); /* z */
has_vertex_blue = TRUE;
}
}
vert_other = ply_get_other_properties (ply, elem_name,
offsetof(Vertex,other_props));
/* test for necessary properties */
if ((!has_x) || (!has_y) || (!has_z))
{
fprintf(stderr, "Vertices don't have x, y, and z\n");
exit(-1);
}
vertices = num_elems;
if (has_nx && has_ny && has_nz)
nor->v.resize(vertices);
pos->v.resize(vertices);
/* grab all the vertex elements */
for (int j=0; j<vertices; j++) {
Vertex tmp;
ply_get_element (ply, (void *) &tmp);
pos->v[j] = vec3f(tmp.coord[0],tmp.coord[1],tmp.coord[2]);
if (has_nx && has_ny && has_nz)
nor->v[j] = vec3f(tmp.normal[0],tmp.normal[1],tmp.normal[2]);
}
} else if (equal_strings ("face", elem_name)) {
/* create a list to hold all the face elements */
cout << "num faces : " << (num_elems) << endl;
/* set up for getting face elements */
/* verify which properties these vertices have */
has_fverts = FALSE;
for (int j=0; j<nprops; j++) {
if (equal_strings("vertex_indices", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_INDICES]);/* vertex_indices */
has_fverts = TRUE;
} else if (equal_strings("red", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_RED]);/* vertex_indices */
has_face_red = TRUE;
} else if (equal_strings("green", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_GREEN]);/* vertex_indices */
has_face_green = TRUE;
} else if (equal_strings("blue", plist[j]->name)) {
ply_get_property(ply, elem_name, &face_props[FACE_BLUE]);/* vertex_indices */
has_face_blue = TRUE;
}
}
face_other = ply_get_other_properties (ply, elem_name,
offsetof(Face,other_props));
/* test for necessary properties */
if (!has_fverts) {
fprintf(stderr, "Faces must have vertex indices\n");
exit(-1);
}
triangles = num_elems;
// numTrisWritten += num_elems;
/* grab all the face elements */
Face tmp;
tmp.verts = NULL;
tmp.other_props = NULL;
for (int j=0; j<num_elems; j++) {
ply_get_element (ply, (void *) &tmp);
if (!has_face_blue) {
tmp.red = tmp.green = tmp.blue = 255;
}
if (tmp.nverts == 3) {
// if (has_face_blue)
// material = getMaterial(tmp.red,tmp.green,tmp.blue);;
vec3i vtx;
vtx.x = tmp.verts[0]; //builder.addVertex(pos[tmp.verts[0]]);
vtx.y = tmp.verts[1]; //builder.addVertex(pos[tmp.verts[1]]);
vtx.z = tmp.verts[2]; //builder.addVertex(pos[tmp.verts[2]]);
idx->v.push_back(vtx);
} else {
PRINT((int)tmp.nverts);
FATAL("can only read ply files made up of triangles...");
}
free(tmp.verts);
if (tmp.other_props) free(tmp.other_props);
}
}
else {
other_elements = ply_get_other_element (ply, elem_name, num_elems);
ply_free_other_elements(other_elements);
}
}
int num_comments;
char **comments;
// PlyOtherProp *vert_other,*face_other;//,*edge_other;
int num_obj_info;
char **obj_info;
comments = ply_get_comments (ply, &num_comments);
obj_info = ply_get_obj_info (ply, &num_obj_info);
ply_close (ply);
for (int i=0;i<ply->nelems;i++) {
if (ply->elems[i]) continue;
PlyElement *e = ply->elems[i];
FREE(e->name);
FREE(e->store_prop);
if (e->props) {
for (int j=0;j<e->nprops;j++) {
PlyProperty *p = e->props[j];
if (!e) continue;
FREE(p->name);
FREE(p);
}
FREE(e->props);
}
FREE(e);
}
free(ply->elems);
mesh->add(idx);
mesh->add(pos);
if (!nor->v.empty())
mesh->add(nor);
}
} // ::ospray::sg::ply
void importPLY(std::shared_ptr<Node> &world, const FileName &fileName)
{
auto mesh = sg::createNode(fileName.name(),
"TriangleMesh")->nodeAs<TriangleMesh>();
ply::readFile(fileName.str(), mesh);
world->add(mesh);
}
} // ::ospray::sg
} // ::ospray
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/run_test.h"
#include "webrtc/video/video_quality_test.h"
namespace webrtc {
namespace flags {
// Flags common with video loopback, with different default values.
DEFINE_int32(width, 1850, "Video width (crops source).");
size_t Width() {
return static_cast<size_t>(FLAGS_width);
}
DEFINE_int32(height, 1110, "Video height (crops source).");
size_t Height() {
return static_cast<size_t>(FLAGS_height);
}
DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
return static_cast<int>(FLAGS_fps);
}
DEFINE_int32(min_bitrate, 50, "Call and stream min bitrate in kbps.");
int MinBitrateKbps() {
return static_cast<int>(FLAGS_min_bitrate);
}
DEFINE_int32(start_bitrate, 200, "Call start bitrate in kbps.");
int StartBitrateKbps() {
return static_cast<int>(FLAGS_start_bitrate);
}
DEFINE_int32(target_bitrate, 2000, "Stream target bitrate in kbps.");
int TargetBitrateKbps() {
return static_cast<int>(FLAGS_target_bitrate);
}
DEFINE_int32(max_bitrate, 2000, "Call and stream max bitrate in kbps.");
int MaxBitrateKbps() {
return static_cast<int>(FLAGS_max_bitrate);
}
DEFINE_int32(num_temporal_layers, 2, "Number of temporal layers to use.");
int NumTemporalLayers() {
return static_cast<int>(FLAGS_num_temporal_layers);
}
// Flags common with video loopback, with equal default values.
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
return static_cast<std::string>(FLAGS_codec);
}
DEFINE_int32(selected_tl,
-1,
"Temporal layer to show or analyze. -1 to disable filtering.");
int SelectedTL() {
return static_cast<int>(FLAGS_selected_tl);
}
DEFINE_int32(
duration,
0,
"Duration of the test in seconds. If 0, rendered will be shown instead.");
int DurationSecs() {
return static_cast<int>(FLAGS_duration);
}
DEFINE_string(output_filename, "", "Target graph data filename.");
std::string OutputFilename() {
return static_cast<std::string>(FLAGS_output_filename);
}
DEFINE_string(graph_title,
"",
"If empty, title will be generated automatically.");
std::string GraphTitle() {
return static_cast<std::string>(FLAGS_graph_title);
}
DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
return static_cast<int>(FLAGS_loss_percent);
}
DEFINE_int32(link_capacity,
0,
"Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacityKbps() {
return static_cast<int>(FLAGS_link_capacity);
}
DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
return static_cast<int>(FLAGS_queue_size);
}
DEFINE_int32(avg_propagation_delay_ms,
0,
"Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}
DEFINE_int32(std_propagation_delay_ms,
0,
"Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
return static_cast<int>(FLAGS_std_propagation_delay_ms);
}
DEFINE_int32(selected_stream, 0, "ID of the stream to show or analyze.");
int SelectedStream() {
return static_cast<int>(FLAGS_selected_stream);
}
DEFINE_int32(num_spatial_layers, 1, "Number of spatial layers to use.");
int NumSpatialLayers() {
return static_cast<int>(FLAGS_num_spatial_layers);
}
DEFINE_int32(selected_sl,
-1,
"Spatial layer to show or analyze. -1 to disable filtering.");
int SelectedSL() {
return static_cast<int>(FLAGS_selected_sl);
}
DEFINE_string(stream0,
"",
"Comma separated values describing VideoStream for stream #0.");
std::string Stream0() {
return static_cast<std::string>(FLAGS_stream0);
}
DEFINE_string(stream1,
"",
"Comma separated values describing VideoStream for stream #1.");
std::string Stream1() {
return static_cast<std::string>(FLAGS_stream1);
}
DEFINE_string(sl0,
"",
"Comma separated values describing SpatialLayer for layer #0.");
std::string SL0() {
return static_cast<std::string>(FLAGS_sl0);
}
DEFINE_string(sl1,
"",
"Comma separated values describing SpatialLayer for layer #1.");
std::string SL1() {
return static_cast<std::string>(FLAGS_sl1);
}
DEFINE_bool(logs, false, "print logs to stderr");
DEFINE_bool(send_side_bwe, true, "Use send-side bandwidth estimation");
DEFINE_bool(allow_reordering, false, "Allow packet reordering to occur");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
" will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
// Screenshare-specific flags.
DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrateKbps() {
return FLAGS_min_transmit_bitrate;
}
DEFINE_int32(slide_change_interval,
10,
"Interval (in seconds) between simulated slide changes.");
int SlideChangeInterval() {
return static_cast<int>(FLAGS_slide_change_interval);
}
DEFINE_int32(
scroll_duration,
0,
"Duration (in seconds) during which a slide will be scrolled into place.");
int ScrollDuration() {
return static_cast<int>(FLAGS_scroll_duration);
}
} // namespace flags
void Loopback() {
FakeNetworkPipe::Config pipe_config;
pipe_config.loss_percent = flags::LossPercent();
pipe_config.link_capacity_kbps = flags::LinkCapacityKbps();
pipe_config.queue_length_packets = flags::QueueSize();
pipe_config.queue_delay_ms = flags::AvgPropagationDelayMs();
pipe_config.delay_standard_deviation_ms = flags::StdPropagationDelayMs();
pipe_config.allow_reordering = flags::FLAGS_allow_reordering;
Call::Config::BitrateConfig call_bitrate_config;
call_bitrate_config.min_bitrate_bps = flags::MinBitrateKbps() * 1000;
call_bitrate_config.start_bitrate_bps = flags::StartBitrateKbps() * 1000;
call_bitrate_config.max_bitrate_bps = flags::MaxBitrateKbps() * 1000;
VideoQualityTest::Params params{
{flags::Width(), flags::Height(), flags::Fps(),
flags::MinBitrateKbps() * 1000, flags::TargetBitrateKbps() * 1000,
flags::MaxBitrateKbps() * 1000, flags::Codec(),
flags::NumTemporalLayers(), flags::SelectedTL(),
flags::MinTransmitBitrateKbps() * 1000, call_bitrate_config,
flags::FLAGS_send_side_bwe},
{}, // Video specific.
{true, flags::SlideChangeInterval(), flags::ScrollDuration()},
{"screenshare", 0.0, 0.0, flags::DurationSecs(), flags::OutputFilename(),
flags::GraphTitle()},
pipe_config,
flags::FLAGS_logs};
std::vector<std::string> stream_descriptors;
stream_descriptors.push_back(flags::Stream0());
stream_descriptors.push_back(flags::Stream1());
std::vector<std::string> SL_descriptors;
SL_descriptors.push_back(flags::SL0());
SL_descriptors.push_back(flags::SL1());
VideoQualityTest::FillScalabilitySettings(
¶ms, stream_descriptors, flags::SelectedStream(),
flags::NumSpatialLayers(), flags::SelectedSL(), SL_descriptors);
VideoQualityTest test;
if (flags::DurationSecs()) {
test.RunWithAnalyzer(params);
} else {
test.RunWithVideoRenderer(params);
}
}
} // namespace webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
webrtc::test::InitFieldTrialsFromString(
webrtc::flags::FLAGS_force_fieldtrials);
webrtc::test::RunTest(webrtc::Loopback);
return 0;
}
<commit_msg>Update default parameters in screenshare_loopback test<commit_after>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/run_test.h"
#include "webrtc/video/video_quality_test.h"
namespace webrtc {
namespace flags {
// Flags common with video loopback, with different default values.
DEFINE_int32(width, 1850, "Video width (crops source).");
size_t Width() {
return static_cast<size_t>(FLAGS_width);
}
DEFINE_int32(height, 1110, "Video height (crops source).");
size_t Height() {
return static_cast<size_t>(FLAGS_height);
}
DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
return static_cast<int>(FLAGS_fps);
}
DEFINE_int32(min_bitrate, 50, "Call and stream min bitrate in kbps.");
int MinBitrateKbps() {
return static_cast<int>(FLAGS_min_bitrate);
}
DEFINE_int32(start_bitrate,
Call::Config::kDefaultStartBitrateBps / 1000,
"Call start bitrate in kbps.");
int StartBitrateKbps() {
return static_cast<int>(FLAGS_start_bitrate);
}
DEFINE_int32(target_bitrate, 200, "Stream target bitrate in kbps.");
int TargetBitrateKbps() {
return static_cast<int>(FLAGS_target_bitrate);
}
DEFINE_int32(max_bitrate, 2000, "Call and stream max bitrate in kbps.");
int MaxBitrateKbps() {
return static_cast<int>(FLAGS_max_bitrate);
}
DEFINE_int32(num_temporal_layers, 2, "Number of temporal layers to use.");
int NumTemporalLayers() {
return static_cast<int>(FLAGS_num_temporal_layers);
}
// Flags common with video loopback, with equal default values.
DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
return static_cast<std::string>(FLAGS_codec);
}
DEFINE_int32(selected_tl,
-1,
"Temporal layer to show or analyze. -1 to disable filtering.");
int SelectedTL() {
return static_cast<int>(FLAGS_selected_tl);
}
DEFINE_int32(
duration,
0,
"Duration of the test in seconds. If 0, rendered will be shown instead.");
int DurationSecs() {
return static_cast<int>(FLAGS_duration);
}
DEFINE_string(output_filename, "", "Target graph data filename.");
std::string OutputFilename() {
return static_cast<std::string>(FLAGS_output_filename);
}
DEFINE_string(graph_title,
"",
"If empty, title will be generated automatically.");
std::string GraphTitle() {
return static_cast<std::string>(FLAGS_graph_title);
}
DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
return static_cast<int>(FLAGS_loss_percent);
}
DEFINE_int32(link_capacity,
0,
"Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacityKbps() {
return static_cast<int>(FLAGS_link_capacity);
}
DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
return static_cast<int>(FLAGS_queue_size);
}
DEFINE_int32(avg_propagation_delay_ms,
0,
"Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}
DEFINE_int32(std_propagation_delay_ms,
0,
"Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
return static_cast<int>(FLAGS_std_propagation_delay_ms);
}
DEFINE_int32(selected_stream, 0, "ID of the stream to show or analyze.");
int SelectedStream() {
return static_cast<int>(FLAGS_selected_stream);
}
DEFINE_int32(num_spatial_layers, 1, "Number of spatial layers to use.");
int NumSpatialLayers() {
return static_cast<int>(FLAGS_num_spatial_layers);
}
DEFINE_int32(selected_sl,
-1,
"Spatial layer to show or analyze. -1 to disable filtering.");
int SelectedSL() {
return static_cast<int>(FLAGS_selected_sl);
}
DEFINE_string(stream0,
"",
"Comma separated values describing VideoStream for stream #0.");
std::string Stream0() {
return static_cast<std::string>(FLAGS_stream0);
}
DEFINE_string(stream1,
"",
"Comma separated values describing VideoStream for stream #1.");
std::string Stream1() {
return static_cast<std::string>(FLAGS_stream1);
}
DEFINE_string(sl0,
"",
"Comma separated values describing SpatialLayer for layer #0.");
std::string SL0() {
return static_cast<std::string>(FLAGS_sl0);
}
DEFINE_string(sl1,
"",
"Comma separated values describing SpatialLayer for layer #1.");
std::string SL1() {
return static_cast<std::string>(FLAGS_sl1);
}
DEFINE_bool(logs, false, "print logs to stderr");
DEFINE_bool(send_side_bwe, true, "Use send-side bandwidth estimation");
DEFINE_bool(allow_reordering, false, "Allow packet reordering to occur");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
" will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
// Screenshare-specific flags.
DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrateKbps() {
return FLAGS_min_transmit_bitrate;
}
DEFINE_int32(slide_change_interval,
10,
"Interval (in seconds) between simulated slide changes.");
int SlideChangeInterval() {
return static_cast<int>(FLAGS_slide_change_interval);
}
DEFINE_int32(
scroll_duration,
0,
"Duration (in seconds) during which a slide will be scrolled into place.");
int ScrollDuration() {
return static_cast<int>(FLAGS_scroll_duration);
}
} // namespace flags
void Loopback() {
FakeNetworkPipe::Config pipe_config;
pipe_config.loss_percent = flags::LossPercent();
pipe_config.link_capacity_kbps = flags::LinkCapacityKbps();
pipe_config.queue_length_packets = flags::QueueSize();
pipe_config.queue_delay_ms = flags::AvgPropagationDelayMs();
pipe_config.delay_standard_deviation_ms = flags::StdPropagationDelayMs();
pipe_config.allow_reordering = flags::FLAGS_allow_reordering;
Call::Config::BitrateConfig call_bitrate_config;
call_bitrate_config.min_bitrate_bps = flags::MinBitrateKbps() * 1000;
call_bitrate_config.start_bitrate_bps = flags::StartBitrateKbps() * 1000;
call_bitrate_config.max_bitrate_bps = flags::MaxBitrateKbps() * 1000;
VideoQualityTest::Params params{
{flags::Width(), flags::Height(), flags::Fps(),
flags::MinBitrateKbps() * 1000, flags::TargetBitrateKbps() * 1000,
flags::MaxBitrateKbps() * 1000, flags::Codec(),
flags::NumTemporalLayers(), flags::SelectedTL(),
flags::MinTransmitBitrateKbps() * 1000, call_bitrate_config,
flags::FLAGS_send_side_bwe},
{}, // Video specific.
{true, flags::SlideChangeInterval(), flags::ScrollDuration()},
{"screenshare", 0.0, 0.0, flags::DurationSecs(), flags::OutputFilename(),
flags::GraphTitle()},
pipe_config,
flags::FLAGS_logs};
std::vector<std::string> stream_descriptors;
stream_descriptors.push_back(flags::Stream0());
stream_descriptors.push_back(flags::Stream1());
std::vector<std::string> SL_descriptors;
SL_descriptors.push_back(flags::SL0());
SL_descriptors.push_back(flags::SL1());
VideoQualityTest::FillScalabilitySettings(
¶ms, stream_descriptors, flags::SelectedStream(),
flags::NumSpatialLayers(), flags::SelectedSL(), SL_descriptors);
VideoQualityTest test;
if (flags::DurationSecs()) {
test.RunWithAnalyzer(params);
} else {
test.RunWithVideoRenderer(params);
}
}
} // namespace webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
google::ParseCommandLineFlags(&argc, &argv, true);
webrtc::test::InitFieldTrialsFromString(
webrtc::flags::FLAGS_force_fieldtrials);
webrtc::test::RunTest(webrtc::Loopback);
return 0;
}
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "util.h"
#include <grammar_registry.h>
using namespace shl;
using namespace std;
class TestSource : public GrammarSource {
public:
TestSource();
virtual const std::string load_data(const std::string& grammar_name) const;
virtual const std::vector<std::string> list_grammars() const;
private:
string ruby;
string html;
string php;
};
TestSource::TestSource() {
ruby = load_string("fixture/ruby.json");
html = load_string("fixture/html.json");
php = load_string("fixture/php.json");
}
const std::string TestSource::load_data(const std::string& grammar_name) const {
if ( grammar_name == "text.html.basic" ) return html;
if ( grammar_name == "source.ruby" ) return ruby;
if ( grammar_name == "text.html.php" ) return php;
return "";
}
const std::vector<std::string> TestSource::list_grammars() const {
vector<string> list = {"text.html.basic", "source.ruby", "text.html.php"};
return list;
}
TEST_CASE("GrammarRegistry Test") {
SECTION("can load all grammar presented by the GrammarSource") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
REQUIRE( registry.contain_grammar("text.html.basic") );
REQUIRE( registry.contain_grammar("source.ruby") );
}
SECTION("all include is resolved") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
Grammar* html_grammar_ptr = ®istry.get_grammar("text.html.basic");
Grammar& grammar = registry.get_grammar("source.ruby");
REQUIRE( grammar.patterns.size() == 88 );
REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.name == "source.ruby" );
REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.ptr == &grammar );
REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.name == "text.html.basic" );
REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.ptr == html_grammar_ptr );
}
SECTION("all injections is loaded") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
Grammar& php = registry.get_grammar("text.html.php");
REQUIRE( !php.empty() );
REQUIRE( !php.injections.empty() );
}
}
<commit_msg>test local repos are loaded. injections are all loaded<commit_after>#include "catch.hpp"
#include "util.h"
#include <grammar_registry.h>
using namespace shl;
using namespace std;
class TestSource : public GrammarSource {
public:
TestSource();
virtual const std::string load_data(const std::string& grammar_name) const;
virtual const std::vector<std::string> list_grammars() const;
private:
string ruby;
string html;
string php;
};
TestSource::TestSource() {
ruby = load_string("fixture/ruby.json");
html = load_string("fixture/html.json");
php = load_string("fixture/php.json");
}
const std::string TestSource::load_data(const std::string& grammar_name) const {
if ( grammar_name == "text.html.basic" ) return html;
if ( grammar_name == "source.ruby" ) return ruby;
if ( grammar_name == "text.html.php" ) return php;
return "";
}
const std::vector<std::string> TestSource::list_grammars() const {
vector<string> list = {"text.html.basic", "source.ruby", "text.html.php"};
return list;
}
TEST_CASE("GrammarRegistry Test") {
SECTION("can load all grammar presented by the GrammarSource") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
REQUIRE( registry.contain_grammar("text.html.basic") );
REQUIRE( registry.contain_grammar("source.ruby") );
}
SECTION("all include is resolved") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
Grammar* html_grammar_ptr = ®istry.get_grammar("text.html.basic");
Grammar& grammar = registry.get_grammar("source.ruby");
REQUIRE( grammar.patterns.size() == 88 );
REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.name == "source.ruby" );
REQUIRE( grammar.patterns[68].patterns[0].patterns[2].include.ptr == &grammar );
REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.name == "text.html.basic" );
REQUIRE( grammar.patterns[59].patterns[0].patterns[2].include.ptr == html_grammar_ptr );
}
SECTION("local repository is resolved") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
Grammar& php = registry.get_grammar("text.html.php");
REQUIRE( !php.empty() );
REQUIRE( !php.repository.empty() );
REQUIRE( !php.repository["heredoc"].repository.empty() );
REQUIRE( php.repository["heredoc"].patterns[0].patterns[0].include.ptr == &php.repository["heredoc"].repository["heredoc_interior"] );
}
SECTION("all injections is loaded") {
shared_ptr<GrammarSource> source(new TestSource());
GrammarRegistry registry(source);
Grammar& php = registry.get_grammar("text.html.php");
REQUIRE( !php.empty() );
REQUIRE( !php.injections.empty() );
REQUIRE( !php.repository["heredoc"].patterns[0].injections.empty() );
}
}
<|endoftext|>
|
<commit_before>// Polygon.cpp
#include "Polygon.h"
#include "Triangle.h"
#include "IndexTriangle.h"
#include "LineSegment.h"
#include "Surface.h"
#include "AffineTransform.h"
#include "Graph.h"
#include "Exception.h"
using namespace _3DMath;
Polygon::Polygon( void )
{
vertexArray = new VectorArray();
indexTriangleList = new IndexTriangleList();
}
/*virtual*/ Polygon::~Polygon( void )
{
delete vertexArray;
delete indexTriangleList;
}
void Polygon::Transform( const AffineTransform& transform )
{
transform.Transform( *vertexArray );
}
bool Polygon::GetPlane( Plane& plane ) const
{
if( vertexArray->size() < 3 )
return false;
Vector center;
GetCenter( center );
Vector normal;
normal.Set( 0.0, 0.0, 0.0 );
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
// This is the Newel method.
int j = ( i + 1 ) % vertexArray->size();
const Vector& pointA = ( *vertexArray )[i];
const Vector& pointB = ( *vertexArray )[j];
normal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z );
normal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x );
normal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y );
}
plane.SetCenterAndNormal( center, normal );
return true;
}
void Polygon::GetCenter( Vector& center ) const
{
center.Set( 0.0, 0.0, 0.0 );
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
center.Add( ( *vertexArray )[i] );
center.Scale( 1.0 / double( vertexArray->size() ) );
}
bool Polygon::GetTriangleAverageCenter( Vector& center ) const
{
if( indexTriangleList->size() == 0 )
return false;
center.Set( 0.0, 0.0, 0.0 );
for( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )
{
const IndexTriangle& indexTriangle = *iter;
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
Vector triangleCenter;
triangle.GetCenter( triangleCenter );
center.Add( triangleCenter );
}
center.Scale( 1.0 / double( indexTriangleList->size() ) );
return true;
}
void Polygon::GetIntegratedCenter( Vector& center, double delta ) const
{
center.Set( 0.0, 0.0, 0.0 );
int count = 0;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
int j = ( i + 1 ) % vertexArray->size();
LineSegment lineSegment( ( *vertexArray )[i], ( *vertexArray )[j] );
int stepCount = ( int )floor( lineSegment.Length() / delta );
for( int k = 0; k < stepCount; k++ )
{
double lambda = double(k) / double( stepCount );
Vector point;
lineSegment.Lerp( lambda, point );
center.Add( point );
count++;
}
}
center.Scale( 1.0 / double( count ) );
}
// This assumes that we're properly tessellated.
bool Polygon::ContainsPoint( const Vector& point, double eps /*= EPSILON*/ ) const
{
for( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )
{
const IndexTriangle& indexTriangle = *iter;
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
if( triangle.ContainsPoint( point, eps ) )
return true;
}
return false;
}
// The set of returned polygons should be pair-wise disjoint and its union should equal this polygon.
// Note that we require this polygon to be tessellated for our algorithm here to be correct.
bool Polygon::SplitAgainstSurface( const Surface* surface, PolygonList& insidePolygonList, PolygonList& outsidePolygonList, double maxDistance ) const
{
bool success = true;
Plane plane;
GetPlane( plane );
struct PointData
{
Vector point;
Surface::Side side;
bool processed;
};
typedef TemplateGraphNode< PointData > Node;
Node* anchorNode = nullptr;
try
{
Node* node = nullptr;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
Node* newNode = new Node();
newNode->data.processed = false;
newNode->data.point = ( *vertexArray )[i];
newNode->data.side = surface->GetSide( newNode->data.point );
if( !node )
anchorNode = newNode;
else
{
node->SetAdjacency( "ccw", newNode );
newNode->SetAdjacency( "cw", node );
}
node = newNode;
}
if( !node )
throw new Exception( "The polygon is empty." );
else
{
node->SetAdjacency( "ccw", anchorNode );
anchorNode->SetAdjacency( "cw", node );
}
node = nullptr;
GraphNodeList graphNodeList;
GraphNode* graphNode = nullptr;
GraphTraversor traversor( anchorNode );
while( traversor.Traverse( graphNode ) )
{
Node* cwNode = ( Node* )graphNode;
Node* ccwNode = ( Node* )cwNode->GetAdjacency( "ccw" );
if( ( cwNode->data.side == Surface::INSIDE && ccwNode->data.side == Surface::OUTSIDE ) ||
( cwNode->data.side == Surface::OUTSIDE && ccwNode->data.side == Surface::INSIDE ) )
{
graphNodeList.push_back( cwNode );
}
}
for( GraphNodeList::iterator iter = graphNodeList.begin(); iter != graphNodeList.end(); iter++ )
{
Node* cwNode = ( Node* )*iter;
Node* ccwNode = ( Node* )cwNode->GetAdjacency( "ccw" );
LineSegment lineSegment;
lineSegment.vertex[0] = cwNode->data.point;
lineSegment.vertex[1] = ccwNode->data.point;
SurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment );
if( !surfacePoint )
throw new Exception( "Failed to intersect polygon edge with surface." );
else
{
Node* newNode = new Node();
newNode->data.processed = false;
newNode->data.side = Surface::NEITHER_SIDE;
surfacePoint->GetLocation( newNode->data.point );
delete surfacePoint;
cwNode->SetAdjacency( "ccw", newNode );
ccwNode->SetAdjacency( "cw", newNode );
newNode->SetAdjacency( "cw", cwNode );
newNode->SetAdjacency( "ccw", ccwNode );
}
}
GraphNodeArray graphNodeArray;
NamedAdjacencyGraphTraversor namedTraversor( "ccw", anchorNode );
while( namedTraversor.Traverse( graphNode ) )
{
node = ( Node* )graphNode;
Node* cwNode = ( Node* )node->GetAdjacency( "cw" );
Node* ccwNode = ( Node* )node->GetAdjacency( "ccw" );
if( node->data.side == Surface::NEITHER_SIDE )
{
if( ( cwNode->data.side == Surface::INSIDE && ccwNode->data.side == Surface::OUTSIDE ) ||
( cwNode->data.side == Surface::OUTSIDE && ccwNode->data.side == Surface::INSIDE ) )
{
graphNodeArray.push_back( node );
}
}
}
int count = ( signed )graphNodeArray.size();
if( count == 2 )
count--;
for( int i = 0; i < count; i++ )
{
int j = ( i + 1 ) % graphNodeArray.size();
Node* nodeA = ( Node* )graphNodeArray[i];
Node* nodeB = ( Node* )graphNodeArray[j];
bool pathFound = false;
SurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( nodeA->data.point );
SurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( nodeB->data.point );
SurfacePoint* surfacePointC = nullptr;
VectorArray pointArray;
if( surfacePointA && surfacePointB )
{
pathFound = surface->FindDirectPath( surfacePointA, surfacePointB, pointArray, maxDistance, &plane );
if( !pathFound )
{
// This is a bit of a hack.
Vector center;
GetCenter( center );
surfacePointC = surface->GetNearestSurfacePoint( center );
pathFound = surface->FindDirectPath( surfacePointA, surfacePointC, pointArray, maxDistance, &plane );
if( pathFound )
{
pointArray.pop_back();
pathFound = surface->FindDirectPath( surfacePointC, surfacePointA, pointArray, maxDistance, &plane );
}
}
}
delete surfacePointA;
delete surfacePointB;
delete surfacePointC;
if( !pathFound )
throw new Exception( "Failed to find path along surface in plane." );
for( j = 0; j < ( signed )pointArray.size(); j++ )
if( !ContainsPoint( pointArray[j], 1e-3 ) )
break;
if( j == ( signed )pointArray.size() )
{
for( j = 1; j < ( signed )pointArray.size() - 1; j++ )
{
Node* newNode = new Node();
newNode->data.processed = false;
newNode->data.side = Surface::NEITHER_SIDE;
newNode->data.point = pointArray[j];
nodeA->SetAdjacency( "s_d0", newNode );
newNode->SetAdjacency( "s_d1", nodeA );
nodeA = newNode;
}
nodeA->SetAdjacency( "s_d0", nodeB );
nodeB->SetAdjacency( "s_d1", nodeA );
}
}
while( true )
{
Node* foundNode = nullptr;
traversor.Reset( anchorNode );
while( traversor.Traverse( graphNode ) )
{
node = ( Node* )graphNode;
if( node->data.side != Surface::NEITHER_SIDE && !node->data.processed )
{
foundNode = node;
break;
}
}
if( !foundNode )
break;
Surface::Side side = foundNode->data.side;
Polygon* polygon = new Polygon;
if( side == Surface::INSIDE )
insidePolygonList.push_back( polygon );
else if( side == Surface::OUTSIDE )
outsidePolygonList.push_back( polygon );
else
{
delete polygon;
throw new Exception( "Encountered unexpected surface side." );
}
node = foundNode;
std::string surfaceDir;
do
{
if( node->data.side != side && node->data.side != Surface::NEITHER_SIDE )
throw new Exception( "Encountered node on wrong side." );
polygon->vertexArray->push_back( node->data.point );
node->data.processed = true;
Node* adjacentNode = nullptr;
if( node->data.side == Surface::NEITHER_SIDE )
{
if( !surfaceDir.empty() )
adjacentNode = ( Node* )node->GetAdjacency( surfaceDir );
else
{
Node* nodeDir0 = ( Node* )node->GetAdjacency( "s_d0" );
Node* nodeDir1 = ( Node* )node->GetAdjacency( "s_d1" );
if( nodeDir0 && nodeDir1 )
throw new Exception( "Ambiguous case encountered." );
else if( nodeDir0 )
{
adjacentNode = nodeDir0;
surfaceDir = "s_d0";
}
else if( nodeDir1 )
{
adjacentNode = nodeDir1;
surfaceDir = "s_d1";
}
else
throw new Exception( "No where to go." );
}
}
if( !adjacentNode )
{
adjacentNode = ( Node* )node->GetAdjacency( "ccw" );
surfaceDir = "";
}
if( !adjacentNode )
throw new Exception( "Encountered unexpected boundary." );
node = adjacentNode;
}
while( node != foundNode );
}
}
catch( Exception* exception )
{
exception->Handle();
delete exception;
success = false;
}
DeleteGraph( anchorNode );
return success;
}
double Polygon::GetArea( void ) const
{
double totalArea = 0.0;
for( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->end(); iter++ )
{
const IndexTriangle& indexTriangle = *iter;
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
totalArea += triangle.Area();
}
return totalArea;
}
bool Polygon::Tessellate( void ) const
{
Plane plane;
if( !GetPlane( plane ) )
return false;
indexTriangleList->clear();
std::vector< int > indexArray;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
indexArray.push_back(i);
while( indexArray.size() > 2 )
{
int i;
for( i = 0; i < ( signed )indexArray.size(); i++ )
{
IndexTriangle indexTriangle(
indexArray[i],
indexArray[ ( i + 1 ) % indexArray.size() ],
indexArray[ ( i + 2 ) % indexArray.size() ] );
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
Vector edge[2];
edge[0].Subtract( triangle.vertex[1], triangle.vertex[0] );
edge[1].Subtract( triangle.vertex[2], triangle.vertex[1] );
Vector cross;
cross.Cross( edge[0], edge[1] );
double dot = cross.Dot( plane.normal );
if( dot < 0.0 )
continue;
int j;
for( j = 0; j < ( signed )indexArray.size(); j++ )
{
if( j == i || j == ( i + 1 ) % indexArray.size() || j == ( i + 2 ) % indexArray.size() )
continue;
if( triangle.ContainsPoint( ( *vertexArray )[ indexArray[j] ] ) )
break;
}
if( j < ( signed )indexArray.size() )
continue;
indexTriangleList->push_back( indexTriangle );
indexArray.erase( indexArray.begin() + ( i + 1 ) % indexArray.size() );
break;
}
if( i == ( signed )indexArray.size() )
return false; // Avoid an infinite loop.
}
return true;
}
// Polygon.cpp<commit_msg>thought<commit_after>// Polygon.cpp
#include "Polygon.h"
#include "Triangle.h"
#include "IndexTriangle.h"
#include "LineSegment.h"
#include "Surface.h"
#include "AffineTransform.h"
#include "Graph.h"
#include "Exception.h"
using namespace _3DMath;
Polygon::Polygon( void )
{
vertexArray = new VectorArray();
indexTriangleList = new IndexTriangleList();
}
/*virtual*/ Polygon::~Polygon( void )
{
delete vertexArray;
delete indexTriangleList;
}
void Polygon::Transform( const AffineTransform& transform )
{
transform.Transform( *vertexArray );
}
bool Polygon::GetPlane( Plane& plane ) const
{
if( vertexArray->size() < 3 )
return false;
Vector center;
GetCenter( center );
Vector normal;
normal.Set( 0.0, 0.0, 0.0 );
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
// This is the Newel method.
int j = ( i + 1 ) % vertexArray->size();
const Vector& pointA = ( *vertexArray )[i];
const Vector& pointB = ( *vertexArray )[j];
normal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z );
normal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x );
normal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y );
}
plane.SetCenterAndNormal( center, normal );
return true;
}
void Polygon::GetCenter( Vector& center ) const
{
center.Set( 0.0, 0.0, 0.0 );
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
center.Add( ( *vertexArray )[i] );
center.Scale( 1.0 / double( vertexArray->size() ) );
}
bool Polygon::GetTriangleAverageCenter( Vector& center ) const
{
if( indexTriangleList->size() == 0 )
return false;
center.Set( 0.0, 0.0, 0.0 );
for( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )
{
const IndexTriangle& indexTriangle = *iter;
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
Vector triangleCenter;
triangle.GetCenter( triangleCenter );
center.Add( triangleCenter );
}
center.Scale( 1.0 / double( indexTriangleList->size() ) );
return true;
}
void Polygon::GetIntegratedCenter( Vector& center, double delta ) const
{
center.Set( 0.0, 0.0, 0.0 );
int count = 0;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
int j = ( i + 1 ) % vertexArray->size();
LineSegment lineSegment( ( *vertexArray )[i], ( *vertexArray )[j] );
int stepCount = ( int )floor( lineSegment.Length() / delta );
for( int k = 0; k < stepCount; k++ )
{
double lambda = double(k) / double( stepCount );
Vector point;
lineSegment.Lerp( lambda, point );
center.Add( point );
count++;
}
}
center.Scale( 1.0 / double( count ) );
}
// This assumes that we're properly tessellated.
bool Polygon::ContainsPoint( const Vector& point, double eps /*= EPSILON*/ ) const
{
for( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->cend(); iter++ )
{
const IndexTriangle& indexTriangle = *iter;
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
if( triangle.ContainsPoint( point, eps ) )
return true;
}
return false;
}
// The set of returned polygons should be pair-wise disjoint and its union should equal this polygon.
// Note that we require this polygon to be tessellated for our algorithm here to be correct.
bool Polygon::SplitAgainstSurface( const Surface* surface, PolygonList& insidePolygonList, PolygonList& outsidePolygonList, double maxDistance ) const
{
bool success = true;
Plane plane;
GetPlane( plane );
struct PointData
{
Vector point;
Surface::Side side;
bool processed;
};
typedef TemplateGraphNode< PointData > Node;
Node* anchorNode = nullptr;
try
{
Node* node = nullptr;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
Node* newNode = new Node();
newNode->data.processed = false;
newNode->data.point = ( *vertexArray )[i];
newNode->data.side = surface->GetSide( newNode->data.point );
if( !node )
anchorNode = newNode;
else
{
node->SetAdjacency( "ccw", newNode );
newNode->SetAdjacency( "cw", node );
}
node = newNode;
}
if( !node )
throw new Exception( "The polygon is empty." );
else
{
node->SetAdjacency( "ccw", anchorNode );
anchorNode->SetAdjacency( "cw", node );
}
node = nullptr;
GraphNodeList graphNodeList;
GraphNode* graphNode = nullptr;
GraphTraversor traversor( anchorNode );
while( traversor.Traverse( graphNode ) )
{
Node* cwNode = ( Node* )graphNode;
Node* ccwNode = ( Node* )cwNode->GetAdjacency( "ccw" );
if( ( cwNode->data.side == Surface::INSIDE && ccwNode->data.side == Surface::OUTSIDE ) ||
( cwNode->data.side == Surface::OUTSIDE && ccwNode->data.side == Surface::INSIDE ) )
{
graphNodeList.push_back( cwNode );
}
}
for( GraphNodeList::iterator iter = graphNodeList.begin(); iter != graphNodeList.end(); iter++ )
{
Node* cwNode = ( Node* )*iter;
Node* ccwNode = ( Node* )cwNode->GetAdjacency( "ccw" );
LineSegment lineSegment;
lineSegment.vertex[0] = cwNode->data.point;
lineSegment.vertex[1] = ccwNode->data.point;
SurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment );
if( !surfacePoint )
throw new Exception( "Failed to intersect polygon edge with surface." );
else
{
Node* newNode = new Node();
newNode->data.processed = false;
newNode->data.side = Surface::NEITHER_SIDE;
surfacePoint->GetLocation( newNode->data.point );
delete surfacePoint;
cwNode->SetAdjacency( "ccw", newNode );
ccwNode->SetAdjacency( "cw", newNode );
newNode->SetAdjacency( "cw", cwNode );
newNode->SetAdjacency( "ccw", ccwNode );
}
}
GraphNodeArray graphNodeArray;
// Note that if the polygon didn't have a high-enough density of vertices,
// (we can, without changing the polygon, add vertices on edges), then we
// can miss nodes here that need to be processed.
NamedAdjacencyGraphTraversor namedTraversor( "ccw", anchorNode );
while( namedTraversor.Traverse( graphNode ) )
{
node = ( Node* )graphNode;
Node* cwNode = ( Node* )node->GetAdjacency( "cw" );
Node* ccwNode = ( Node* )node->GetAdjacency( "ccw" );
if( node->data.side == Surface::NEITHER_SIDE )
{
if( ( cwNode->data.side == Surface::INSIDE && ccwNode->data.side == Surface::OUTSIDE ) ||
( cwNode->data.side == Surface::OUTSIDE && ccwNode->data.side == Surface::INSIDE ) )
{
graphNodeArray.push_back( node );
}
}
}
int count = ( signed )graphNodeArray.size();
if( count == 2 )
count--;
for( int i = 0; i < count; i++ )
{
int j = ( i + 1 ) % graphNodeArray.size();
Node* nodeA = ( Node* )graphNodeArray[i];
Node* nodeB = ( Node* )graphNodeArray[j];
bool pathFound = false;
SurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( nodeA->data.point );
SurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( nodeB->data.point );
SurfacePoint* surfacePointC = nullptr;
VectorArray pointArray;
if( surfacePointA && surfacePointB )
{
pathFound = surface->FindDirectPath( surfacePointA, surfacePointB, pointArray, maxDistance, &plane );
if( !pathFound )
{
// This is a bit of a hack.
Vector center;
GetCenter( center );
surfacePointC = surface->GetNearestSurfacePoint( center );
pathFound = surface->FindDirectPath( surfacePointA, surfacePointC, pointArray, maxDistance, &plane );
if( pathFound )
{
pointArray.pop_back();
pathFound = surface->FindDirectPath( surfacePointC, surfacePointA, pointArray, maxDistance, &plane );
}
}
}
delete surfacePointA;
delete surfacePointB;
delete surfacePointC;
if( !pathFound )
throw new Exception( "Failed to find path along surface in plane." );
for( j = 0; j < ( signed )pointArray.size(); j++ )
if( !ContainsPoint( pointArray[j], 1e-3 ) )
break;
if( j == ( signed )pointArray.size() )
{
for( j = 1; j < ( signed )pointArray.size() - 1; j++ )
{
Node* newNode = new Node();
newNode->data.processed = false;
newNode->data.side = Surface::NEITHER_SIDE;
newNode->data.point = pointArray[j];
nodeA->SetAdjacency( "s_d0", newNode );
newNode->SetAdjacency( "s_d1", nodeA );
nodeA = newNode;
}
nodeA->SetAdjacency( "s_d0", nodeB );
nodeB->SetAdjacency( "s_d1", nodeA );
}
}
while( true )
{
Node* foundNode = nullptr;
traversor.Reset( anchorNode );
while( traversor.Traverse( graphNode ) )
{
node = ( Node* )graphNode;
if( node->data.side != Surface::NEITHER_SIDE && !node->data.processed )
{
foundNode = node;
break;
}
}
if( !foundNode )
break;
Surface::Side side = foundNode->data.side;
Polygon* polygon = new Polygon;
if( side == Surface::INSIDE )
insidePolygonList.push_back( polygon );
else if( side == Surface::OUTSIDE )
outsidePolygonList.push_back( polygon );
else
{
delete polygon;
throw new Exception( "Encountered unexpected surface side." );
}
node = foundNode;
std::string surfaceDir;
do
{
if( node->data.side != side && node->data.side != Surface::NEITHER_SIDE )
throw new Exception( "Encountered node on wrong side." );
polygon->vertexArray->push_back( node->data.point );
node->data.processed = true;
Node* adjacentNode = nullptr;
if( node->data.side == Surface::NEITHER_SIDE )
{
if( !surfaceDir.empty() )
adjacentNode = ( Node* )node->GetAdjacency( surfaceDir );
else
{
Node* nodeDir0 = ( Node* )node->GetAdjacency( "s_d0" );
Node* nodeDir1 = ( Node* )node->GetAdjacency( "s_d1" );
if( nodeDir0 && nodeDir1 )
throw new Exception( "Ambiguous case encountered." );
else if( nodeDir0 )
{
adjacentNode = nodeDir0;
surfaceDir = "s_d0";
}
else if( nodeDir1 )
{
adjacentNode = nodeDir1;
surfaceDir = "s_d1";
}
else
throw new Exception( "No where to go." );
}
}
if( !adjacentNode )
{
adjacentNode = ( Node* )node->GetAdjacency( "ccw" );
surfaceDir = "";
}
if( !adjacentNode )
throw new Exception( "Encountered unexpected boundary." );
node = adjacentNode;
}
while( node != foundNode );
}
}
catch( Exception* exception )
{
exception->Handle();
delete exception;
success = false;
}
DeleteGraph( anchorNode );
return success;
}
double Polygon::GetArea( void ) const
{
double totalArea = 0.0;
for( IndexTriangleList::const_iterator iter = indexTriangleList->cbegin(); iter != indexTriangleList->end(); iter++ )
{
const IndexTriangle& indexTriangle = *iter;
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
totalArea += triangle.Area();
}
return totalArea;
}
bool Polygon::Tessellate( void ) const
{
Plane plane;
if( !GetPlane( plane ) )
return false;
indexTriangleList->clear();
std::vector< int > indexArray;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
indexArray.push_back(i);
while( indexArray.size() > 2 )
{
int i;
for( i = 0; i < ( signed )indexArray.size(); i++ )
{
IndexTriangle indexTriangle(
indexArray[i],
indexArray[ ( i + 1 ) % indexArray.size() ],
indexArray[ ( i + 2 ) % indexArray.size() ] );
Triangle triangle;
indexTriangle.GetTriangle( triangle, vertexArray );
Vector edge[2];
edge[0].Subtract( triangle.vertex[1], triangle.vertex[0] );
edge[1].Subtract( triangle.vertex[2], triangle.vertex[1] );
Vector cross;
cross.Cross( edge[0], edge[1] );
double dot = cross.Dot( plane.normal );
if( dot < 0.0 )
continue;
int j;
for( j = 0; j < ( signed )indexArray.size(); j++ )
{
if( j == i || j == ( i + 1 ) % indexArray.size() || j == ( i + 2 ) % indexArray.size() )
continue;
if( triangle.ContainsPoint( ( *vertexArray )[ indexArray[j] ] ) )
break;
}
if( j < ( signed )indexArray.size() )
continue;
indexTriangleList->push_back( indexTriangle );
indexArray.erase( indexArray.begin() + ( i + 1 ) % indexArray.size() );
break;
}
if( i == ( signed )indexArray.size() )
return false; // Avoid an infinite loop.
}
return true;
}
// Polygon.cpp<|endoftext|>
|
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "main/core.h"
#include "glsl_symbol_table.h"
#include "glsl_parser_extras.h"
#include "ir.h"
#include "program.h"
#include "program/hash_table.h"
#include "linker.h"
static ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
glsl_symbol_table *symbols, bool use_builtin);
namespace {
class call_link_visitor : public ir_hierarchical_visitor {
public:
call_link_visitor(gl_shader_program *prog, gl_linked_shader *linked,
gl_shader **shader_list, unsigned num_shaders)
{
this->prog = prog;
this->shader_list = shader_list;
this->num_shaders = num_shaders;
this->success = true;
this->linked = linked;
this->locals = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
}
~call_link_visitor()
{
hash_table_dtor(this->locals);
}
virtual ir_visitor_status visit(ir_variable *ir)
{
hash_table_insert(locals, ir, ir);
return visit_continue;
}
virtual ir_visitor_status visit_enter(ir_call *ir)
{
/* If ir is an ir_call from a function that was imported from another
* shader callee will point to an ir_function_signature in the original
* shader. In this case the function signature MUST NOT BE MODIFIED.
* Doing so will modify the original shader. This may prevent that
* shader from being linkable in other programs.
*/
const ir_function_signature *const callee = ir->callee;
assert(callee != NULL);
const char *const name = callee->function_name();
/* Determine if the requested function signature already exists in the
* final linked shader. If it does, use it as the target of the call.
*/
ir_function_signature *sig =
find_matching_signature(name, &callee->parameters, linked->symbols,
ir->use_builtin);
if (sig != NULL) {
ir->callee = sig;
return visit_continue;
}
/* Try to find the signature in one of the other shaders that is being
* linked. If it's not found there, return an error.
*/
for (unsigned i = 0; i < num_shaders; i++) {
sig = find_matching_signature(name, &ir->actual_parameters,
shader_list[i]->symbols,
ir->use_builtin);
if (sig)
break;
}
if (sig == NULL) {
/* FINISHME: Log the full signature of unresolved function.
*/
linker_error(this->prog, "unresolved reference to function `%s'\n",
name);
this->success = false;
return visit_stop;
}
/* Find the prototype information in the linked shader. Generate any
* details that may be missing.
*/
ir_function *f = linked->symbols->get_function(name);
if (f == NULL) {
f = new(linked) ir_function(name);
/* Add the new function to the linked IR. Put it at the end
* so that it comes after any global variable declarations
* that it refers to.
*/
linked->symbols->add_function(f);
linked->ir->push_tail(f);
}
ir_function_signature *linked_sig =
f->exact_matching_signature(NULL, &callee->parameters);
if ((linked_sig == NULL)
|| ((linked_sig != NULL)
&& (linked_sig->is_builtin() != ir->use_builtin))) {
linked_sig = new(linked) ir_function_signature(callee->return_type);
f->add_signature(linked_sig);
}
/* At this point linked_sig and called may be the same. If ir is an
* ir_call from linked then linked_sig and callee will be
* ir_function_signatures that have no definitions (is_defined is false).
*/
assert(!linked_sig->is_defined);
assert(linked_sig->body.is_empty());
/* Create an in-place clone of the function definition. This multistep
* process introduces some complexity here, but it has some advantages.
* The parameter list and the and function body are cloned separately.
* The clone of the parameter list is used to prime the hashtable used
* to replace variable references in the cloned body.
*
* The big advantage is that the ir_function_signature does not change.
* This means that we don't have to process the rest of the IR tree to
* patch ir_call nodes. In addition, there is no way to remove or
* replace signature stored in a function. One could easily be added,
* but this avoids the need.
*/
struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
exec_list formal_parameters;
foreach_in_list(const ir_instruction, original, &sig->parameters) {
assert(const_cast<ir_instruction *>(original)->as_variable());
ir_instruction *copy = original->clone(linked, ht);
formal_parameters.push_tail(copy);
}
linked_sig->replace_parameters(&formal_parameters);
linked_sig->is_intrinsic = sig->is_intrinsic;
if (sig->is_defined) {
foreach_in_list(const ir_instruction, original, &sig->body) {
ir_instruction *copy = original->clone(linked, ht);
linked_sig->body.push_tail(copy);
}
linked_sig->is_defined = true;
}
hash_table_dtor(ht);
/* Patch references inside the function to things outside the function
* (i.e., function calls and global variables).
*/
linked_sig->accept(this);
ir->callee = linked_sig;
return visit_continue;
}
virtual ir_visitor_status visit_leave(ir_call *ir)
{
/* Traverse list of function parameters, and for array parameters
* propagate max_array_access. Otherwise arrays that are only referenced
* from inside functions via function parameters will be incorrectly
* optimized. This will lead to incorrect code being generated (or worse).
* Do it when leaving the node so the children would propagate their
* array accesses first.
*/
const exec_node *formal_param_node = ir->callee->parameters.get_head();
if (formal_param_node) {
const exec_node *actual_param_node = ir->actual_parameters.get_head();
while (!actual_param_node->is_tail_sentinel()) {
ir_variable *formal_param = (ir_variable *) formal_param_node;
ir_rvalue *actual_param = (ir_rvalue *) actual_param_node;
formal_param_node = formal_param_node->get_next();
actual_param_node = actual_param_node->get_next();
if (formal_param->type->is_array()) {
ir_dereference_variable *deref = actual_param->as_dereference_variable();
if (deref && deref->var && deref->var->type->is_array()) {
deref->var->data.max_array_access =
MAX2(formal_param->data.max_array_access,
deref->var->data.max_array_access);
}
}
}
}
return visit_continue;
}
virtual ir_visitor_status visit(ir_dereference_variable *ir)
{
if (hash_table_find(locals, ir->var) == NULL) {
/* The non-function variable must be a global, so try to find the
* variable in the shader's symbol table. If the variable is not
* found, then it's a global that *MUST* be defined in the original
* shader.
*/
ir_variable *var = linked->symbols->get_variable(ir->var->name);
if (var == NULL) {
/* Clone the ir_variable that the dereference already has and add
* it to the linked shader.
*/
var = ir->var->clone(linked, NULL);
linked->symbols->add_variable(var);
linked->ir->push_head(var);
} else {
if (var->type->is_array()) {
/* It is possible to have a global array declared in multiple
* shaders without a size. The array is implicitly sized by
* the maximal access to it in *any* shader. Because of this,
* we need to track the maximal access to the array as linking
* pulls more functions in that access the array.
*/
var->data.max_array_access =
MAX2(var->data.max_array_access,
ir->var->data.max_array_access);
if (var->type->length == 0 && ir->var->type->length != 0)
var->type = ir->var->type;
}
if (var->is_interface_instance()) {
/* Similarly, we need implicit sizes of arrays within interface
* blocks to be sized by the maximal access in *any* shader.
*/
int *const linked_max_ifc_array_access =
var->get_max_ifc_array_access();
int *const ir_max_ifc_array_access =
ir->var->get_max_ifc_array_access();
assert(linked_max_ifc_array_access != NULL);
assert(ir_max_ifc_array_access != NULL);
for (unsigned i = 0; i < var->get_interface_type()->length;
i++) {
linked_max_ifc_array_access[i] =
MAX2(linked_max_ifc_array_access[i],
ir_max_ifc_array_access[i]);
}
}
}
ir->var = var;
}
return visit_continue;
}
/** Was function linking successful? */
bool success;
private:
/**
* Shader program being linked
*
* This is only used for logging error messages.
*/
gl_shader_program *prog;
/** List of shaders available for linking. */
gl_shader **shader_list;
/** Number of shaders available for linking. */
unsigned num_shaders;
/**
* Final linked shader
*
* This is used two ways. It is used to find global variables in the
* linked shader that are accessed by the function. It is also used to add
* global variables from the shader where the function originated.
*/
gl_linked_shader *linked;
/**
* Table of variables local to the function.
*/
hash_table *locals;
};
} /* anonymous namespace */
/**
* Searches a list of shaders for a particular function definition
*/
ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
glsl_symbol_table *symbols, bool use_builtin)
{
ir_function *const f = symbols->get_function(name);
if (f) {
ir_function_signature *sig =
f->matching_signature(NULL, actual_parameters, use_builtin);
if (sig && (sig->is_defined || sig->is_intrinsic)) {
/* If this function expects to bind to a built-in function and the
* signature that we found isn't a built-in, keep looking. Also keep
* looking if we expect a non-built-in but found a built-in.
*/
if (use_builtin == sig->is_builtin())
return sig;
}
}
return NULL;
}
bool
link_function_calls(gl_shader_program *prog, gl_linked_shader *main,
gl_shader **shader_list, unsigned num_shaders)
{
call_link_visitor v(prog, main, shader_list, num_shaders);
v.run(main->ir);
return v.success;
}
<commit_msg>glsl: Change link_functions to use a set<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "main/core.h"
#include "glsl_symbol_table.h"
#include "glsl_parser_extras.h"
#include "ir.h"
#include "program.h"
#include "util/set.h"
#include "util/hash_table.h"
#include "linker.h"
static ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
glsl_symbol_table *symbols, bool use_builtin);
namespace {
class call_link_visitor : public ir_hierarchical_visitor {
public:
call_link_visitor(gl_shader_program *prog, gl_linked_shader *linked,
gl_shader **shader_list, unsigned num_shaders)
{
this->prog = prog;
this->shader_list = shader_list;
this->num_shaders = num_shaders;
this->success = true;
this->linked = linked;
this->locals = _mesa_set_create(NULL, _mesa_hash_pointer,
_mesa_key_pointer_equal);
}
~call_link_visitor()
{
_mesa_set_destroy(this->locals, NULL);
}
virtual ir_visitor_status visit(ir_variable *ir)
{
_mesa_set_add(locals, ir);
return visit_continue;
}
virtual ir_visitor_status visit_enter(ir_call *ir)
{
/* If ir is an ir_call from a function that was imported from another
* shader callee will point to an ir_function_signature in the original
* shader. In this case the function signature MUST NOT BE MODIFIED.
* Doing so will modify the original shader. This may prevent that
* shader from being linkable in other programs.
*/
const ir_function_signature *const callee = ir->callee;
assert(callee != NULL);
const char *const name = callee->function_name();
/* Determine if the requested function signature already exists in the
* final linked shader. If it does, use it as the target of the call.
*/
ir_function_signature *sig =
find_matching_signature(name, &callee->parameters, linked->symbols,
ir->use_builtin);
if (sig != NULL) {
ir->callee = sig;
return visit_continue;
}
/* Try to find the signature in one of the other shaders that is being
* linked. If it's not found there, return an error.
*/
for (unsigned i = 0; i < num_shaders; i++) {
sig = find_matching_signature(name, &ir->actual_parameters,
shader_list[i]->symbols,
ir->use_builtin);
if (sig)
break;
}
if (sig == NULL) {
/* FINISHME: Log the full signature of unresolved function.
*/
linker_error(this->prog, "unresolved reference to function `%s'\n",
name);
this->success = false;
return visit_stop;
}
/* Find the prototype information in the linked shader. Generate any
* details that may be missing.
*/
ir_function *f = linked->symbols->get_function(name);
if (f == NULL) {
f = new(linked) ir_function(name);
/* Add the new function to the linked IR. Put it at the end
* so that it comes after any global variable declarations
* that it refers to.
*/
linked->symbols->add_function(f);
linked->ir->push_tail(f);
}
ir_function_signature *linked_sig =
f->exact_matching_signature(NULL, &callee->parameters);
if ((linked_sig == NULL)
|| ((linked_sig != NULL)
&& (linked_sig->is_builtin() != ir->use_builtin))) {
linked_sig = new(linked) ir_function_signature(callee->return_type);
f->add_signature(linked_sig);
}
/* At this point linked_sig and called may be the same. If ir is an
* ir_call from linked then linked_sig and callee will be
* ir_function_signatures that have no definitions (is_defined is false).
*/
assert(!linked_sig->is_defined);
assert(linked_sig->body.is_empty());
/* Create an in-place clone of the function definition. This multistep
* process introduces some complexity here, but it has some advantages.
* The parameter list and the and function body are cloned separately.
* The clone of the parameter list is used to prime the hashtable used
* to replace variable references in the cloned body.
*
* The big advantage is that the ir_function_signature does not change.
* This means that we don't have to process the rest of the IR tree to
* patch ir_call nodes. In addition, there is no way to remove or
* replace signature stored in a function. One could easily be added,
* but this avoids the need.
*/
struct hash_table *ht = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
_mesa_key_pointer_equal);
exec_list formal_parameters;
foreach_in_list(const ir_instruction, original, &sig->parameters) {
assert(const_cast<ir_instruction *>(original)->as_variable());
ir_instruction *copy = original->clone(linked, ht);
formal_parameters.push_tail(copy);
}
linked_sig->replace_parameters(&formal_parameters);
linked_sig->is_intrinsic = sig->is_intrinsic;
if (sig->is_defined) {
foreach_in_list(const ir_instruction, original, &sig->body) {
ir_instruction *copy = original->clone(linked, ht);
linked_sig->body.push_tail(copy);
}
linked_sig->is_defined = true;
}
_mesa_hash_table_destroy(ht, NULL);
/* Patch references inside the function to things outside the function
* (i.e., function calls and global variables).
*/
linked_sig->accept(this);
ir->callee = linked_sig;
return visit_continue;
}
virtual ir_visitor_status visit_leave(ir_call *ir)
{
/* Traverse list of function parameters, and for array parameters
* propagate max_array_access. Otherwise arrays that are only referenced
* from inside functions via function parameters will be incorrectly
* optimized. This will lead to incorrect code being generated (or worse).
* Do it when leaving the node so the children would propagate their
* array accesses first.
*/
const exec_node *formal_param_node = ir->callee->parameters.get_head();
if (formal_param_node) {
const exec_node *actual_param_node = ir->actual_parameters.get_head();
while (!actual_param_node->is_tail_sentinel()) {
ir_variable *formal_param = (ir_variable *) formal_param_node;
ir_rvalue *actual_param = (ir_rvalue *) actual_param_node;
formal_param_node = formal_param_node->get_next();
actual_param_node = actual_param_node->get_next();
if (formal_param->type->is_array()) {
ir_dereference_variable *deref = actual_param->as_dereference_variable();
if (deref && deref->var && deref->var->type->is_array()) {
deref->var->data.max_array_access =
MAX2(formal_param->data.max_array_access,
deref->var->data.max_array_access);
}
}
}
}
return visit_continue;
}
virtual ir_visitor_status visit(ir_dereference_variable *ir)
{
if (_mesa_set_search(locals, ir->var) == NULL) {
/* The non-function variable must be a global, so try to find the
* variable in the shader's symbol table. If the variable is not
* found, then it's a global that *MUST* be defined in the original
* shader.
*/
ir_variable *var = linked->symbols->get_variable(ir->var->name);
if (var == NULL) {
/* Clone the ir_variable that the dereference already has and add
* it to the linked shader.
*/
var = ir->var->clone(linked, NULL);
linked->symbols->add_variable(var);
linked->ir->push_head(var);
} else {
if (var->type->is_array()) {
/* It is possible to have a global array declared in multiple
* shaders without a size. The array is implicitly sized by
* the maximal access to it in *any* shader. Because of this,
* we need to track the maximal access to the array as linking
* pulls more functions in that access the array.
*/
var->data.max_array_access =
MAX2(var->data.max_array_access,
ir->var->data.max_array_access);
if (var->type->length == 0 && ir->var->type->length != 0)
var->type = ir->var->type;
}
if (var->is_interface_instance()) {
/* Similarly, we need implicit sizes of arrays within interface
* blocks to be sized by the maximal access in *any* shader.
*/
int *const linked_max_ifc_array_access =
var->get_max_ifc_array_access();
int *const ir_max_ifc_array_access =
ir->var->get_max_ifc_array_access();
assert(linked_max_ifc_array_access != NULL);
assert(ir_max_ifc_array_access != NULL);
for (unsigned i = 0; i < var->get_interface_type()->length;
i++) {
linked_max_ifc_array_access[i] =
MAX2(linked_max_ifc_array_access[i],
ir_max_ifc_array_access[i]);
}
}
}
ir->var = var;
}
return visit_continue;
}
/** Was function linking successful? */
bool success;
private:
/**
* Shader program being linked
*
* This is only used for logging error messages.
*/
gl_shader_program *prog;
/** List of shaders available for linking. */
gl_shader **shader_list;
/** Number of shaders available for linking. */
unsigned num_shaders;
/**
* Final linked shader
*
* This is used two ways. It is used to find global variables in the
* linked shader that are accessed by the function. It is also used to add
* global variables from the shader where the function originated.
*/
gl_linked_shader *linked;
/**
* Table of variables local to the function.
*/
set *locals;
};
} /* anonymous namespace */
/**
* Searches a list of shaders for a particular function definition
*/
ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
glsl_symbol_table *symbols, bool use_builtin)
{
ir_function *const f = symbols->get_function(name);
if (f) {
ir_function_signature *sig =
f->matching_signature(NULL, actual_parameters, use_builtin);
if (sig && (sig->is_defined || sig->is_intrinsic)) {
/* If this function expects to bind to a built-in function and the
* signature that we found isn't a built-in, keep looking. Also keep
* looking if we expect a non-built-in but found a built-in.
*/
if (use_builtin == sig->is_builtin())
return sig;
}
}
return NULL;
}
bool
link_function_calls(gl_shader_program *prog, gl_linked_shader *main,
gl_shader **shader_list, unsigned num_shaders)
{
call_link_visitor v(prog, main, shader_list, num_shaders);
v.run(main->ir);
return v.success;
}
<|endoftext|>
|
<commit_before>#include "./point_helpers.h"
#include <string>
#include <ostream>
#include "runtime/length.h"
#include "tree_sitter/runtime.h"
using namespace std;
bool operator==(const TSPoint &left, const TSPoint &right) {
return left.row == right.row && left.column == right.column;
}
bool operator==(const TSRange &left, const TSRange &right) {
return (
left.start_byte == right.start_byte &&
left.end_byte == right.end_byte &&
left.start_point == right.start_point &&
left.end_point == right.end_point
);
}
bool operator==(const Length &left, const Length &right) {
return left.bytes == right.bytes && left.extent == right.extent;
}
bool operator<(const TSPoint &left, const TSPoint &right) {
if (left.row < right.row) return true;
if (left.row > right.row) return false;
return left.column < right.column;
}
bool operator>(const TSPoint &left, const TSPoint &right) {
return right < left;
}
std::ostream &operator<<(std::ostream &stream, const TSPoint &point) {
return stream << "{" << point.row << ", " << point.column << "}";
}
std::ostream &operator<<(std::ostream &stream, const TSRange &range) {
return stream << "{" << range.start_point << ", " << range.end_point << "}";
}
ostream &operator<<(ostream &stream, const Length &length) {
return stream << "{bytes:" << length.bytes << ", extent:" << length.extent << "}";
}
TSPoint extent_for_string(const string &text, size_t end_index) {
if (end_index > text.size()) end_index = text.size();
TSPoint result = {0, 0};
for (size_t i = 0; i < end_index; i++) {
if (text[i] == '\n') {
result.row++;
result.column = 0;
} else {
result.column++;
}
}
return result;
}
TSRange range_for_substring(const string &text, const string &substring) {
size_t start = text.find(substring);
assert(start != string::npos);
size_t end = start + substring.size();
return TSRange {
extent_for_string(text, start),
extent_for_string(text, end),
static_cast<uint32_t>(start),
static_cast<uint32_t>(end),
};
};
<commit_msg>Add missing #include in point_helpers<commit_after>#include "./point_helpers.h"
#include <string>
#include <ostream>
#include <cassert>
#include "runtime/length.h"
#include "tree_sitter/runtime.h"
using namespace std;
bool operator==(const TSPoint &left, const TSPoint &right) {
return left.row == right.row && left.column == right.column;
}
bool operator==(const TSRange &left, const TSRange &right) {
return (
left.start_byte == right.start_byte &&
left.end_byte == right.end_byte &&
left.start_point == right.start_point &&
left.end_point == right.end_point
);
}
bool operator==(const Length &left, const Length &right) {
return left.bytes == right.bytes && left.extent == right.extent;
}
bool operator<(const TSPoint &left, const TSPoint &right) {
if (left.row < right.row) return true;
if (left.row > right.row) return false;
return left.column < right.column;
}
bool operator>(const TSPoint &left, const TSPoint &right) {
return right < left;
}
std::ostream &operator<<(std::ostream &stream, const TSPoint &point) {
return stream << "{" << point.row << ", " << point.column << "}";
}
std::ostream &operator<<(std::ostream &stream, const TSRange &range) {
return stream << "{" << range.start_point << ", " << range.end_point << "}";
}
ostream &operator<<(ostream &stream, const Length &length) {
return stream << "{bytes:" << length.bytes << ", extent:" << length.extent << "}";
}
TSPoint extent_for_string(const string &text, size_t end_index) {
if (end_index > text.size()) end_index = text.size();
TSPoint result = {0, 0};
for (size_t i = 0; i < end_index; i++) {
if (text[i] == '\n') {
result.row++;
result.column = 0;
} else {
result.column++;
}
}
return result;
}
TSRange range_for_substring(const string &text, const string &substring) {
size_t start = text.find(substring);
assert(start != string::npos);
size_t end = start + substring.size();
return TSRange {
extent_for_string(text, start),
extent_for_string(text, end),
static_cast<uint32_t>(start),
static_cast<uint32_t>(end),
};
};
<|endoftext|>
|
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* fflas_fdot.inl
* Copyright (C) 2005 Clement Pernet
*
* Written by Clement Pernet <Clement.Pernet@imag.fr>
*
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*.
*/
#ifndef __FFLASFFPACK_fdot_INL
#define __FFLASFFPACK_fdot_INL
#include "fflas-ffpack/fflas/fflas_helpers.inl"
// Default implementation
// Specializations should be written
// to increase efficiency
namespace FFLAS {
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy ,
ModeCategories::DefaultTag& MT)
{
typename Field::Element d;
typename Field::ConstElement_ptr xi = x;
typename Field::ConstElement_ptr yi = y;
F.init (d);
F.assign (d, F.zero);
for ( ; xi < x+N*incx; xi+=incx, yi+=incy )
F.axpyin( d, *xi, *yi );
return d;
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy ,
ModeCategories::DelayedTag& MT)
{
typedef typename associatedDelayedField<const Field>::field DelayedField;
typedef typename associatedDelayedField<const Field>::type DelayedField_t;
typedef typename DelayedField::Element DFElt;
DelayedField_t delayedF;
const DFElt MaxStorableValue = limits<typename DelayedField::Element>::max();
const DFElt AbsMax = std::max(-F.minElement(), F.maxElement());
const DFElt r = MaxStorableValue / (AbsMax*AbsMax);
size_t delayedDim = FFLAS::Protected::min_types<DFElt>(r);
typename Field::Element d;
F.init (d);
F.assign (d, F.zero);
ModeCategories::DefaultTag DM;
typename Field::ConstElement_ptr xi = x, yi = y;
size_t i=delayedDim;
typename Field::Element dp;
F.init(dp);
for (; i<N; i+= delayedDim, xi += incx*delayedDim, yi += incy*delayedDim){
F.assign(dp, fdot (delayedF, delayedDim, xi, incx, yi, incy, DM));
F.addin(d, dp);
}
F.assign (dp,fdot (delayedF, N+delayedDim-i, xi, incx, yi, incy, DM));
F.addin (d, dp);
return d;
}
template<>
inline Givaro::DoubleDomain::Element
fdot( const Givaro::DoubleDomain& , const size_t N,
Givaro::DoubleDomain::ConstElement_ptr x, const size_t incx,
Givaro::DoubleDomain::ConstElement_ptr y, const size_t incy,
ModeCategories::DefaultTag& MT)
{
#ifdef __FFLASFFPACK_OPENBLAS_NUM_THREADS
openblas_set_num_threads(__FFLASFFPACK_OPENBLAS_NUM_THREADS);
#endif
return cblas_ddot( (int)N, x, (int)incx, y, (int)incy );
}
template<>
inline Givaro::FloatDomain::Element
fdot( const Givaro::FloatDomain& , const size_t N,
Givaro::FloatDomain::ConstElement_ptr x, const size_t incx,
Givaro::FloatDomain::ConstElement_ptr y, const size_t incy,
ModeCategories::DefaultTag& MT)
{
#ifdef __FFLASFFPACK_OPENBLAS_NUM_THREADS
openblas_set_num_threads(__FFLASFFPACK_OPENBLAS_NUM_THREADS);
#endif
return cblas_sdot( (int)N, x, (int)incx, y, (int)incy );
}
template<class Field, class T>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy,
ModeCategories::ConvertTo<T>& MT)
{
typename ModeCategories::DefaultTag mt;
return fdot (F, N, x, incx, y, incy, mt);
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy,
ModeCategories::DefaultBoundedTag& dbt)
{
// Nothing special in fdot for Bounded
typename ModeCategories::DefaultTag dt;
return fdot (F, N, x, incx, y, incy, dt);
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy,
const ParSeqHelper::Sequential seq)
{
typename ModeTraits<Field>::value mt;
return fdot (F, N, x, incx, y, incy, mt);
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy)
{
return fdot (F, N, x, incx, y, incy, FFLAS::ParSeqHelper::Sequential());
}
} // FFLAS
#endif // __FFLASFFPACK_fdot_INL
<commit_msg>this init should have stayed here<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* fflas_fdot.inl
* Copyright (C) 2005 Clement Pernet
*
* Written by Clement Pernet <Clement.Pernet@imag.fr>
*
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*.
*/
#ifndef __FFLASFFPACK_fdot_INL
#define __FFLASFFPACK_fdot_INL
#include "fflas-ffpack/fflas/fflas_helpers.inl"
// Default implementation
// Specializations should be written
// to increase efficiency
namespace FFLAS {
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy ,
ModeCategories::DefaultTag& MT)
{
typename Field::Element d;
typename Field::ConstElement_ptr xi = x;
typename Field::ConstElement_ptr yi = y;
F.init (d);
F.assign (d, F.zero);
for ( ; xi < x+N*incx; xi+=incx, yi+=incy )
F.axpyin( d, *xi, *yi );
return d;
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy ,
ModeCategories::DelayedTag& MT)
{
typedef typename associatedDelayedField<const Field>::field DelayedField;
typedef typename associatedDelayedField<const Field>::type DelayedField_t;
typedef typename DelayedField::Element DFElt;
DelayedField_t delayedF;
const DFElt MaxStorableValue = limits<typename DelayedField::Element>::max();
const DFElt AbsMax = std::max(-F.minElement(), F.maxElement());
const DFElt r = MaxStorableValue / (AbsMax*AbsMax);
size_t delayedDim = FFLAS::Protected::min_types<DFElt>(r);
typename Field::Element d;
F.init (d);
F.assign (d, F.zero);
ModeCategories::DefaultTag DM;
typename Field::ConstElement_ptr xi = x, yi = y;
size_t i=delayedDim;
typename Field::Element dp;
for (; i<N; i+= delayedDim, xi += incx*delayedDim, yi += incy*delayedDim){
F.init(dp, fdot (delayedF, delayedDim, xi, incx, yi, incy, DM));
F.addin(d, dp);
}
F.init (dp,fdot (delayedF, N+delayedDim-i, xi, incx, yi, incy, DM));
F.addin (d, dp);
return d;
}
template<>
inline Givaro::DoubleDomain::Element
fdot( const Givaro::DoubleDomain& , const size_t N,
Givaro::DoubleDomain::ConstElement_ptr x, const size_t incx,
Givaro::DoubleDomain::ConstElement_ptr y, const size_t incy,
ModeCategories::DefaultTag& MT)
{
#ifdef __FFLASFFPACK_OPENBLAS_NUM_THREADS
openblas_set_num_threads(__FFLASFFPACK_OPENBLAS_NUM_THREADS);
#endif
return cblas_ddot( (int)N, x, (int)incx, y, (int)incy );
}
template<>
inline Givaro::FloatDomain::Element
fdot( const Givaro::FloatDomain& , const size_t N,
Givaro::FloatDomain::ConstElement_ptr x, const size_t incx,
Givaro::FloatDomain::ConstElement_ptr y, const size_t incy,
ModeCategories::DefaultTag& MT)
{
#ifdef __FFLASFFPACK_OPENBLAS_NUM_THREADS
openblas_set_num_threads(__FFLASFFPACK_OPENBLAS_NUM_THREADS);
#endif
return cblas_sdot( (int)N, x, (int)incx, y, (int)incy );
}
template<class Field, class T>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy,
ModeCategories::ConvertTo<T>& MT)
{
typename ModeCategories::DefaultTag mt;
return fdot (F, N, x, incx, y, incy, mt);
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy,
ModeCategories::DefaultBoundedTag& dbt)
{
// Nothing special in fdot for Bounded
typename ModeCategories::DefaultTag dt;
return fdot (F, N, x, incx, y, incy, dt);
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy,
const ParSeqHelper::Sequential seq)
{
typename ModeTraits<Field>::value mt;
return fdot (F, N, x, incx, y, incy, mt);
}
template<class Field>
inline typename Field::Element
fdot( const Field& F, const size_t N,
typename Field::ConstElement_ptr x, const size_t incx,
typename Field::ConstElement_ptr y, const size_t incy)
{
return fdot (F, N, x, incx, y, incy, FFLAS::ParSeqHelper::Sequential());
}
} // FFLAS
#endif // __FFLASFFPACK_fdot_INL
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.